diff --git a/.github/labeler.yml b/.github/labeler.yml deleted file mode 100644 index fcb9198..0000000 --- a/.github/labeler.yml +++ /dev/null @@ -1,33 +0,0 @@ -# List of PR labels for readline - -tags: -- tag.go -- internal/tag/* -commands: -- command.go -- gen/flags/command* -flags: -- flag.go -- camelcase* -- gen/flags/flags* -positionals: -- internal/positional/* -- gen/flags/positional* -completions: -- gen/completions/* -options: -- options.go -- internal/scan/options.go -scan: -- parser.go -- errors.go -- parser_test.go -- internal/scan/* -validation: -- validator/* -- internal/validation/* -types: -- internal/convert/* -- cmd/genvalues/* -- values* -- converters* diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 0b7c422..b10abc1 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -18,7 +18,7 @@ on: # The branches below must be a subset of the branches above branches: [ "main" ] schedule: - - cron: '27 8 * * 0' + - cron: '15 22 * * 3' jobs: analyze: @@ -40,11 +40,11 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v3 + uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. @@ -58,7 +58,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun @@ -71,6 +71,6 @@ jobs: # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 with: category: "/language:${{matrix.language}}" diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index ffc80b7..e5fe8da 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -15,12 +15,12 @@ jobs: runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Go and tools - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: - go-version: 1.19 + go-version: 1.24.2 - run: go install golang.org/x/tools/cmd/goimports@latest @@ -36,18 +36,18 @@ jobs: run: go test -race -coverprofile=coverage.txt - name: Upload coverage - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 windows: runs-on: windows-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Set up Go and tools - uses: actions/setup-go@v3 + uses: actions/setup-go@v5 with: - go-version: 1.19 + go-version: 1.24.2 - run: go install golang.org/x/tools/cmd/goimports@latest diff --git a/.github/workflows/label.yml b/.github/workflows/label.yml deleted file mode 100644 index a8a1bd7..0000000 --- a/.github/workflows/label.yml +++ /dev/null @@ -1,22 +0,0 @@ -# This workflow will triage pull requests and apply a label based on the -# paths that are modified in the pull request. -# -# To use this workflow, you will need to set up a .github/labeler.yml -# file with configuration. For more information, see: -# https://github.com/actions/labeler - -name: Labeler -on: [pull_request] - -jobs: - label: - - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write - - steps: - - uses: actions/labeler@v4 - with: - repo-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/.gitignore b/.gitignore index daf913b..5330979 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,6 @@ _testmain.go *.exe *.test *.prof + +# Example binaries +example/flags diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 369f903..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "flags.wiki"] - path = flags.wiki - url = https://github.com/reeflective/flags.wiki diff --git a/.golangci.yml b/.golangci.yml index 7261e07..5a01d59 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,382 +1,144 @@ - -# ************************************************************************************* # -# Golang CI Lint Global Configuration # -# ************************************************************************************* # - -# This configuration is divided into several subsections: -# - Options for analysis running -# - Enabled/disabled linters -# - Other exclusions & Issues management -# - Issues severity management -# - Per-linter configurations - -# -# -------------------------- Options for analysis running -------------------------- # -# +version: "2" run: - # - # ***** Tests **** - # - # Include test files or not. - # Default: true + modules-download-mode: readonly tests: true - - # - # ***** Ignored directories, files & patterns ***** - # - # Which dirs to skip: issues from them won't be reported. - # Can use regexp here: `generated.*`, regexp is applied on full path. - # Default value is empty list, - # but default dirs are skipped independently of this option's value (see skip-dirs-use-default). - # "/" will be replaced by current OS file path separator to properly work on Windows. - # skip-dirs: - - # Enables skipping of directories: - # - vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - # Default: true - skip-dirs-use-default: true - - # Which files to skip: they will be analyzed, but issues from them won't be reported. - # Default value is empty list, - # but there is no need to include all autogenerated files, - # we confidently recognize autogenerated files. - # If it's not please let us know. - # "/" will be replaced by current OS file path separator to properly work on Windows. - # skip-files: - # - ".*\\.my\\.go$" - # - lib/bad.go - - # - # ***** Dependencies & Modules ***** - # - # If set we pass it to "go list -mod={option}". From "go help modules": - # If invoked with -mod=readonly, the go command is disallowed from the implicit - # automatic updating of go.mod described above. Instead, it fails when any changes - # to go.mod are needed. This setting is most useful to check that go.mod does - # not need updates, such as in a continuous integration and testing system. - # If invoked with -mod=vendor, the go command assumes that the vendor - # directory holds the correct copies of dependencies and ignores - # the dependency descriptions in go.mod. - # - # Allowed values: readonly|vendor|mod - # By default, it isn't set. - modules-download-mode: readonly # NOT SURE WHICH ONE TO USE BY DEFAULT - - # - # ***** Other ***** - # - # Allow multiple parallel golangci-lint instances running. - # If false (default) - golangci-lint acquires file lock on start. - allow-parallel-runners: true - - -# -# -------------------------- Output Configuration Options --------------------------- # -# -# output: - # Format: colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions - # - # Multiple can be specified by separating them by comma, output can be provided - # for each of them by separating format name and path by colon symbol. - # Output path can be either `stdout`, `stderr` or path to the file to write to. - # Example: "checkstyle:report.json,colored-line-number" - # - # Default: colored-line-number - # format: json - # Print lines of code with issue. - # Default: true - # print-issued-lines: false - # Print linter name in the end of issue text. - # Default: true - # print-linter-name: false - # Make issues output unique by line. - # Default: true - # uniq-by-line: false - # Add a prefix to the output file references. - # Default is no prefix. - # path-prefix: "" - # Sort results by: filepath, line and column. - # sort-results: false - -# -# ------------------------------------- Linters ------------------------------------ # -# + allow-parallel-runners: true linters: - # Disable all linters. - # disable-all: true - - # Enable presets. Used to enable entire sets of linters based on their "tags". - # Some of these enabled sets might be redundant with the explicitly & individually - # enabled linters above, so pay attention to what you want to do. - # Also, some linters are explicitly deactived in some section below, which might - # be undesired behavior to you. - # https://golangci-lint.run/usage/linters - presets: - - bugs - - comment - - complexity - - error - - format - - import - - metalinter - - module - - performance - # - sql - - style - - test - - unused - - # Enable specific linter - # https://golangci-lint.run/usage/linters/#enabled-by-default-linters - # - # Example line: - # - lintername # Description () - # where: - # () means the linter is not fast, and not auto-fix capable - # (fast) means the linter is only fast - # (auto) means the linter can auto-fix its detected issues. - # enable: - # Linters enabled by default (commented out in list of disabled linters below) - - deadcode # Finds unused code () - - errcheck # Finds unchecked errors in Go programs () - - gosimple # Specializes in simplifying a code () - - govet # Reports suspicious constructs, such as Printf calls with wrong args () - - ineffassign # Detects when assignments to existing variables are not used (fast) - - staticcheck # A ton of static analysis checks () - - structcheck # Finds unused struct fields () - - unused # Checks for unused constants, variables, functions and types () - - varcheck # Finds unused global variables and constants () - - # Other linters (not enabled by default, thus optional) - # - asciicheck # Checks that code does not contain non-ASCII identifiers (bugs, style) - - bidichk # checks for dangerous unicode character sequences (bugs) - - bodyclose # checks HTTP response body is closed successfully (perf,bugs) - - containedctx # detects struct-contained context.Context field (style) - - contextcheck # check the function use a non-inherited context (bugs) - - cyclop # checks function and package cyclomatic complexity (cplx) - - decorder # checks declaration order/count of types/consts/vars/funcs (fmt,style) - # - depguard # checks if imports are in a list of acceptable packages (style,imp,mod) - - dogsled # checks assignments with too many blank identifiers (style) - - dupl # tool for code clone detection (style) - - durationcheck # checks for two durations multiplied together (bugs) - - errchkjson # checks types passed to JSON encoding functions & related (bugs) - - errname # checks that sentinel errors are prefix with Err (style) - - errorlint # finds potential problems with Go 1.13 error wrap scheme (bugs, err) - # - exhaustive # checks exhaustiveness of enum switch statements (bugs) - # - exhaustivestruct # checks if all struct fields are initialized (style,test) - - exportloopref # checks for pointers to enclosing loop variables (bugs) - # - forbidigo # Forbids identifiers (style) - - forcetypeassert # finds forced type assertions (style) - - funlen # tool for detection of long functions (cplx) - - gci # Controls package import order and makes deterministic (fmt,import) - - gochecknoglobals # checks that no global variables exist (style) - # - gochecknoinits # checks that no init functions are present (style) - - gocognit # computes and checks the cognitive complexity of functions (cplx) - - goconst # finds repeated strings that can be replaced by a constant (style) - - gocritic # diagnostics for bugs/perf/style issues. Extensible (style,meta) - - gocyclo # computes and checks cyclomatic complexity of functions (cplx) - - godot # checks if comments end in a period (style,cmt) - - godox # tool for detection of FIXME, TODO and other comments (style,cmt) - - goerr113 # checks the errors handling expressions (style,err) - - gofmt # formats and checks for code simplification (fmt) - - gofumpt # checks whether code was gofumpt-ed (fmt) - - goheader # checks if file header matches to pattern (style) - # - goimports # fixes imports, formats code same as gofmt (fmt,import) - # - golint # Deprecated - - gomnd # analyzer to detect magic numbers (style) - - gomoddirectives # manage replace/retract/excludes directives in go.mod (style,mod) - - gomodguard # allow/block for direct module deps. (style,imp,mod) - - goprintffuncname # check that printf-like funcs are named with f at end (style) - - gosec # inspect code for security problems (bugs) - - grouper # analyzer to analyze expression groups (style) - - ifshort # checks that code uses short syntax for if statements (style) - - importas # enforces consistent import aliases (style) - # - interfacer # Deprecated - # - ireturn # accept Interfaces, return Concrete Types (style) - - lll # Report long lines (style) - - maintidx # measures the maintainability index of each function (cplx) - - makezero # finds slice declarations with non-zero initial length (style,bugs) - # - maligned # Deprecated - - misspell # finds commonly misspelled English words in comments (style,cmt) - - nakedret # finds naked returns in functions greater than spec len (style) - - nestif # reports deeply nested if statements (cplx) - - nilerr # finds code returning nil even if checks error not nil (bugs) - - nilnil # checks no simultaneous return of nil err and invalid value (style) - - nlreturn # checks for a new line before return and branch statements (style) - - noctx # fnds sending HTTP requests without context.Context (perf,bugs) - - nolintlint # reports ill-formed or insufficient nolint directives (style) - - paralleltest # detects missing usage of t.Parallel() in your tests (style,test) - - prealloc # finds slice declarations that could be preallocated (perf) - - predeclared # finds code shadowing one of Go's predeclared identifiers (style) - # - promlinter # checks Prometheus metrics naming via promlint - - revive # fast,extensible,flexible linter. Replacement of golint (style,meta) - # - rowserrcheck # checks if Err of rows is checked successfully (bugs,sql) - # - scopelint # Deprecated - # - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed (bugs,sql) - # - stylecheck # replacement for golint (style) - - tagliatelle # checks struct tags (style) - - tenv # detects using os.Setenv instead of t.Setenv since go1.17 (style) - # - testpackage # makes you use a separate _test package (style,test) - - thelper # detects test helpers without t.Helper(), checks consistent (style) - - tparallel # detects inappropriate use of t.Parallel() in your tests (style,test) - # - typecheck # Like the front-end of the Go compiler, parses and type-checks Go code () - - unconvert # remove unnecessary type convertions (style) - - unparam # reports unused function parameters (unused) - - varnamelen # checks that the length of a var name matches its scope (style) - - wastedassign # finds wasted assignment statements (style) - # - whitespace # detection of leading and trailing whitespace (style) - - wrapcheck # checks errors returned from external packages are wrapped (style,err) - - wsl # forces you to use empty lines ! (style) - - # Enable all available linters. - # enable-all: true - - # Disable specific linter - # https://golangci-lint.run/usage/linters/#disabled-by-default-linters--e--enable + - asasalint + - bidichk + - bodyclose + - canonicalheader + - containedctx + - contextcheck + - copyloopvar + - cyclop + - decorder + - dogsled + - dupl + - dupword + - durationcheck + - err113 + - errchkjson + - errname + - errorlint + - exptostd + - fatcontext + - forcetypeassert + - funlen + - ginkgolinter + - gocheckcompilerdirectives + - gochecknoglobals + - gochecksumtype + - gocognit + - goconst + - gocritic + - gocyclo + - godot + - godox + - goheader + - gomoddirectives + - gomodguard + - goprintffuncname + - gosec + - gosmopolitan + - grouper + - iface + - importas + - inamedparam + - interfacebloat + - intrange + - lll + - loggercheck + - maintidx + - makezero + - mirror + - misspell + - mnd + - musttag + - nakedret + - nestif + - nilerr + - nilnesserr + - nilnil + - nlreturn + - noctx + - nolintlint + - nonamedreturns + - nosprintfhostport + - paralleltest + - perfsprint + - prealloc + - predeclared + - protogetter + - reassign + - recvcheck + - revive + - sloglint + - spancheck + - tagalign + - tagliatelle + - testableexamples + - testifylint + - thelper + - tparallel + - unconvert + - unparam + - usestdlibvars + - usetesting + - varnamelen + - wastedassign + - wrapcheck + - zerologlint disable: - # Linters enabled by default (commented out in list of disabled linters below) - # - deadcode - # - errcheck - # - gosimple - # - govet - # - ineffassign - # - staticcheck - # - structcheck - - typecheck - # - unused - # - varcheck - - # Deactivated linters above (explicitly deactived here, so that `presets` section - # above does not activate them again) - - asciicheck # Checks that code does not contain non-ASCII identifiers (bugs,style) - - depguard # checks if imports are in list of acceptable pkgs (style,imp,mod) - - exhaustive # checks exhaustiveness of enum switch statements (bugs) - - exhaustruct # checks if all struct fields are initialized (style,test) - - exhaustivestruct # checks if all struct fields are initialized (style,test) - - forbidigo # Forbids identifiers (style) - - gochecknoinits # checks that no init functions are present (style) - - goimports # fixes imports, formats code same as gofmt (fmt,import) - - ireturn # accept Interfaces, return Concrete Types (style) - - promlinter # checks Prometheus metrics naming via promlint - - rowserrcheck # checks if Err of rows is checked successfully (bugs,sql) - - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed (bugs,sql) - - stylecheck # replacement for golint (style) - - testpackage # makes you use a separate _test package (style,test) - - whitespace # detection of leading and trailing whitespace (style) - - # Run only fast linters from enabled linters set (first run won't be fast) - # Default: false - # fast: true + - asciicheck + - depguard + - exhaustive + - exhaustruct + - forbidigo + - gochecknoinits + - ireturn + - promlinter + - rowserrcheck + - sqlclosecheck + - testpackage + - whitespace + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - dupl + - errcheck + - gocyclo + - gosec + path: _test\.go + - linters: + - lll + source: '^//go:generate ' + paths: + - third_party$ + - builtin$ + - examples$ -# -# ----------------------- Other exclusions & Issues management -------------------------- # -# issues: - # List of regexps of issue texts to exclude. - # - # But independently of this option we use default exclude patterns, - # it can be disabled by `exclude-use-default: false`. - # To list all excluded by default patterns execute `golangci-lint run --help` - # - # Default: [] - # exclude: - # - abcdef - - # Excluding configuration per-path, per-linter, per-text and per-source - exclude-rules: - # Exclude some linters from running on tests files. - - path: _test\.go - linters: - - gocyclo - - errcheck - - dupl - - gosec - - # Exclude known linters from partially hard-vendored code, - # which is impossible to exclude via `nolint` comments. - # - path: internal/hmac/ - # text: "weak cryptographic primitive" - # linters: - # - gosec - - # Exclude some `staticcheck` messages. - # - linters: - # - staticcheck - # text: "SA9003:" - - # Exclude `lll` issues for long lines with `go:generate`. - - linters: - - lll - source: "^//go:generate " - - # Independently of option `exclude` we use default exclude patterns, - # it can be disabled by this option. - # To list all excluded by default patterns execute `golangci-lint run --help`. - # Default: true. - # exclude-use-default: false - - # If set to true exclude and exclude-rules regular expressions become case-sensitive. - # Default: false - # exclude-case-sensitive: false - - # The list of ids of default excludes to include or disable. - # Default: [] - # include: - # - EXC0002 # disable excluding of issues about comments from golint. - - # Maximum issues count per one linter. - # Set to 0 to disable. - # Default: 50 - # max-issues-per-linter: 0 - # Maximum count of issues with the same text. - # Set to 0 to disable. - # Default: 3 max-same-issues: 0 - # Show only new issues: if there are unstaged changes or untracked files, - # only those changes are analyzed, else only changes in HEAD~ are analyzed. - # It's a super-useful option for integration of golangci-lint into existing large codebase. - # It's not practical to fix all existing issues at the moment of integration: - # much better don't allow issues in new code. - # - # Default: false. - new: true - # Show only new issues created after git revision `REV`. new-from-rev: HEAD - # Show only new issues created in git patch with set file path. new-from-patch: path/to/patch/file - # Fix found issues (if it's supported by the linter). - fix : true - -# -# ---------------------------- Issues severity manament -------------------------------- # -# -# severity: - # Set the default severity for issues. - # - # If severity rules are defined and the issues do not match or no severity is provided to the rule - # this will be the default severity applied. - # Severities should match the supported severity names of the selected out format. - # - Code climate: https://docs.codeclimate.com/docs/issues#issue-severity - # - Checkstyle: https://checkstyle.sourceforge.io/property_types.html#severity - # - GitHub: https://help.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message - # - # Default value is an empty string. - # default-severity: error - # If set to true `severity-rules` regular expressions become case-sensitive. - # Default: false - # case-sensitive: true - # When a list of severity rules are provided, severity information will be added to lint issues. - # Severity rules have the same filtering capability as exclude rules - # except you are allowed to specify one matcher per severity rule. - # Only affects out formats that support setting severity information. - # - # Default: [] - # rules: - # - linters: - # - dupl - # severity: info - -# -# ---------------------------- Per-linter Configuration -------------------------------- # -# + new: true + fix: true +formatters: + # enable: + # - gci + # - gofmt + # - gofumpt + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/README.md b/README.md index 2d62c45..6a6d475 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,3 @@ -
@@ -6,8 +5,8 @@

Flags

Generate cobra commands from structs

-

jessevdk/go-flags and octago/sflags compliant tags.

-

Enhanced with advanced related CLI functionality, at minimum cost.

+

jessevdk/go-flags, urfave/sflags and alecthomas/kong compliant tags.

+

Advanced related CLI features (validations, completions and more), at a minimum cost.

@@ -44,54 +43,120 @@

+`reeflective/flags` lets you effortlessly build powerful, feature-rich `spf13/cobra` command-line applications directly from Go structs. Stop writing boilerplate for flags, commands, and argument parsing. Instead, define your entire CLI structure declaratively and let `flags` handle the generation. -## Summary - -The flags library allows to declare cobra CLI commands, flags and positional arguments from structs and field tags. -It originally aimed to enhance [go-flags](https://github.com/jessevdk/go-flags), but ended up shifting its approach in order to leverage the widely -used and battle-tested [cobra](https://github.com/spf13/cobra) CLI library. In addition, it provides other generators leveraging the [carapace](https://github.com/rsteube/carapace) -completion engine, thus allowing for very powerful yet simple completion and as-you-type usage generation for -the commands, flags and positional arguments. - -In short, the main purpose of this library is to let users focus on writing programs. It requires very little -time and focus spent on declaring CLI interface specs (commands, flags, groups of flags/commands) and associated -functionality (completions and validations), and then generates powerful and ready to use CLI programs. +## Features - -## Features +### Overview +* **Declarative & Simple:** Define your entire CLI—commands, subcommands, flags, and positional arguments—using simple Go struct tags. +* **Powerful Completions:** Instantly generate rich, context-aware shell completions for 9 shells, powered by a single call to `carapace`. +* **Built-in Validation:** Add validation rules (`required`, `min`, `max`, `oneof`, etc.) directly in your struct tags using the `validate` tag. +* **Seamless Cobra Integration:** Generates a standard `cobra.Command`, so you can still use the full power of the Cobra ecosystem. +* **High Compatibility:** Offers a familiar experience for developers coming from `jessevdk/go-flags`, `alecthomas/kong` or `octago/sflags` by supporting their tag formats. +* **Focus on Your Logic:** Spend less time on CLI boilerplate and more time on what your application actually does. ### Commands, flags & positionals -- Easily declare commands, flags, and positional arguments through struct tags. -- Various ways to structure the command trees in groups (tagged, or encapsulated in structs). -- Almost entirely retrocompatible with [go-flags](https://github.com/jessevdk/go-flags), with a ported and enlarged test suite. -- Advanced and versatile positional arguments declaration, with automatic binding to `cobra.Args`. -- Large array of native types supported as flags or positional arguments. +- Various ways to structure the command trees in groups (tagged, or encapsulated in structs). +- Almost entirely retrocompatible with [go-flags](https://github.com/jessevdk/go-flags), [sflags](https://github.com/urfave/sflags) and [kong](https://github.com/alecthomas/kong) with a ported and enlarged test suite. +- Advanced and versatile positional arguments declaration, with automatic binding to `cobra.Args`. +- Large array of native types supported as flags or positional arguments. ### Related functionality -- Easily declare validations on command flags or positional arguments, with [go-validator](https://github.com/go-playground/validator) tags. -- Generate advanced completions with the [carapace](https://github.com/rsteube/carapace) completion engine in a single call. -- Implement completers on positional/flag types, or declare builtin completers via struct tags. -- Generated completions include commands/flags groups, descriptions, usage strings. -- Live validation of command-line input with completers running flags' validations. -- All of these features, cross-platform and cross-shell, almost for free. - - -## Documentation - -- A good way to introduce you to this library is to [install and use the example application binary](https://github.com/reeflective/flags/tree/main/example). - This example application will give you a taste of the behavior and supported features. -- The generation package [flags](https://github.com/reeflective/flags/tree/main/gen/flags) has a [godoc file](https://github.com/reeflective/flags/tree/main/gen/flags/flags.go) with all the valid tags for each component - (commands/groups/flags/positionals), along with some notes and advices. This is so that you can - quickly get access to those from your editor when writing commands and functionality. -- Another [godoc file](https://github.com/reeflective/flags/tree/main/flags.go) provides quick access to global parsing options (for global behavior, - validators, etc) located in the root package of this library. Both godoc files will be merged. +- Easily declare validations on command flags or positional arguments, with [go-validator](https://github.com/go-playground/validator) tags. +- Generate advanced completions with the [carapace](https://github.com/rsteube/carapace) completion engine in a single call. +- Implement completers on positional/flag types, or declare builtin completers via struct tags. +- Generated completions include commands/flags groups, descriptions, usage strings. +- Live validation of command-line input with completers running flags' validations. + +## Discovering the Library + +A good way to introduce you to this library is to [install and use the example application binary](https://github.com/reeflective/flags/tree/main/example). +This example application will give you a taste of the behavior and supported features. + +## Quick Start + +Go beyond simple flags. Define commands, grouped flags, positional arguments with validation, and shell completions—all from a single struct. + +```go +package main + +import ( + "fmt" + "os" + + "github.comcom/reeflective/flags" +) + +// Define the root command structure. +var opts struct { + Verbose bool `short:"v" long:"verbose" desc:"Show verbose debug information"` + Hello HelloCmd `command:"hello" description:"A command to say hello"` +} + +// Define the 'hello' subcommand. +type HelloCmd struct { + // Add a required positional argument with shell completion for usernames. + Name string `arg:"" required:"true" description:"The name to greet" complete:"users"` + + // Add an optional positional argument with a default value. + Greeting string `arg:"" help:"An optional, custom greeting"` + + // Group flags together for better --help output. + Output struct { + Formal bool `long:"formal" description:"Use a more formal greeting"` + Color string `long:"color" default:"auto" description:"When to use color output" choice:"auto always never"` + } `group:"Output Settings"` +} + +// Execute will be automatically discovered and used as the handler for the 'hello' command. +func (c *HelloCmd) Execute(args []string) error { + greeting := c.Greeting + if c.Output.Formal { + greeting = "Greetings" + } + + message := fmt.Sprintf("%s, %s!", greeting, c.Name) + + // A real app would check if stdout is a TTY for "auto" + if c.Output.Color == "always" || c.Output.Color == "auto" { + message = "\033[32m" + message + "\033[0m" // Green text + } + + fmt.Println(message) + + if opts.Verbose { + fmt.Println("(Executed with verbose flag)") + } + + return nil +} + +func main() { + // Generate the cobra.Command from your struct. + // Completions will be automatically generated. + cmd, err := flags.Parse(&opts) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + + // Execute the application. + if err := cmd.Execute(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} +``` + +## Advanced Usage & Wiki + - Along with the above, the following is the table of contents of the [wiki documentation](https://github.com/reeflective/flags/wiki): ### Development * [Introduction and principles](https://github.com/reeflective/flags/wiki/Introduction) -* [Declaring and using commands](https://github.com/reeflective/flags/wiki/Commands) -* [Positional arguments](https://github.com/reeflective/flags/wiki/Positionals) +* [Commands](https://github.com/reeflective/flags/wiki/Commands) * [Flags](https://github.com/reeflective/flags/wiki/Flags) +* [Positional arguments](https://github.com/reeflective/flags/wiki/Positionals) * [Completions](https://github.com/reeflective/flags/wiki/Completions) * [Validations](https://github.com/reeflective/flags/wiki/Validations) * [Side features](https://github.com/reeflective/flags/wiki/Side-Features) @@ -99,30 +164,16 @@ functionality (completions and validations), and then generates powerful and rea ### Coming from other libraries * [Changes from octago/sflags](https://github.com/reeflective/flags/wiki/Sflags) * [Changes from jessevdk/go-flags](https://github.com/reeflective/flags/wiki/Go-Flags) - +* [Changes from alecthomas/kong](https://github.com/reeflective/flags/wiki/Kong) ## Status -This library is currently in a pre-release candidate state, for several reasons: -- It has not been widely tested, and some features/enhancements remain to be done. -- There might be bugs, or behavior inconsistencies that I might have missed. -- The codebase is not huge, but significant nonetheless. I aimed to write it - as structured and cleanly as possible. +This library is approaching v1.0 status: it has been under a big refactoring and has seen many +improvements in many aspects (Compatibility, completions, validations, failure safety, etc). +However, it has not been much tested outside of its test suite: there might be bugs, or behavior +inconsistencies that I might have missed. Please open a PR or an issue if you wish to bring enhancements to it. For newer features, please consider if there is a large number of people who might benefit from it, or if it has a chance of impairing on future development. If everything is fine, please propose ! Other contributions, as well as bug fixes and reviews are also welcome. - - -## Credits - -- This library is _heavily_ based on [octago/sflags](https://github.com/octago/sflags) code (it is actually forked from it since most of its code was needed). - The flags generation is almost entirely his, and this library would not be as nearly as powerful without it. He should also - be credited for 99% of this library's 99% coverage rate. It is also the inspiration for the trajectory this project has taken, - which originally would just enhance go-flags. -- The [go-flags](https://github.com/jessevdk/go-flags) is probably the most widely used reflection-based CLI library. While it will be hard to find a lot of - similarities with this project's codebase, the internal logic for scanning arbitrary structures draws almost all of its - inspiration out of this project. -- The completion engine [carapace](https://github.com/rsteube/carapace), a fantastic library for providing cross-shell, multi-command CLI completion with hundreds - of different system completers. The flags project makes use of it for generation the completers for the command structure. diff --git a/camelcase.go b/camelcase.go deleted file mode 100644 index d817110..0000000 --- a/camelcase.go +++ /dev/null @@ -1,119 +0,0 @@ -package flags - -// This part was taken from the https://github.com/fatih/camelcase package. -// The only fix is for integers, they stay with previous words. -// -// The MIT License (MIT) -// -// Copyright (c) 2015 Fatih Arslan -// -// 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. - -import ( - "unicode" - "unicode/utf8" -) - -const ( - classLower = 1 - classUpper = 2 - classDigit = 3 - classOther = 4 -) - -// split splits the camelcase word and returns a list of words. It also -// supports digits. Both lower camel case and upper camel case are supported. -// For more info please check: http://en.wikipedia.org/wiki/CamelCase -// -// Examples -// -// "" => [""] -// "lowercase" => ["lowercase"] -// "Class" => ["Class"] -// "MyClass" => ["My", "Class"] -// "MyC" => ["My", "C"] -// "HTML" => ["HTML"] -// "PDFLoader" => ["PDF", "Loader"] -// "AString" => ["A", "String"] -// "SimpleXMLParser" => ["Simple", "XML", "Parser"] -// "vimRPCPlugin" => ["vim", "RPC", "Plugin"] -// "GL11Version" => ["GL11", "Version"] -// "99Bottles" => ["99", "Bottles"] -// "May5" => ["May5"] -// "BFG9000" => ["BFG9000"] -// "BöseÜberraschung" => ["Böse", "Überraschung"] -// "Two spaces" => ["Two", " ", "spaces"] -// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] -// -// Splitting rules -// -// 1. If string is not valid UTF-8, return it without splitting as -// single item array. -// 2. Assign all unicode characters into one of 4 sets: lower case -// letters, upper case letters, numbers, and all other characters. -// 3. Iterate through characters of string, introducing splits -// between adjacent characters that belong to different sets. -// 4. Iterate through array of split strings, and if a given string -// is upper case: -// if subsequent string is lower case: -// move last character of upper case string to beginning of -// lower case string -func split(src string) (entries []string) { - // don't split invalid utf8 - if !utf8.ValidString(src) { - return []string{src} - } - entries = []string{} - var runes [][]rune - var class int - lastClass := 0 - // split into fields based on class of unicode character - for _, r := range src { - switch true { - case unicode.IsLower(r): - class = classLower - case unicode.IsUpper(r): - class = classUpper - case unicode.IsDigit(r): - class = classDigit - default: - class = classOther - } - if lastClass != 0 && (class == lastClass || class == classDigit) { - runes[len(runes)-1] = append(runes[len(runes)-1], r) - } else { - runes = append(runes, []rune{r}) - } - lastClass = class - } - // handle upper case -> lower case sequences, e.g. - // "PDFL", "oader" -> "PDF", "Loader" - for i := 0; i < len(runes)-1; i++ { - if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) { - runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...) - runes[i] = runes[i][:len(runes[i])-1] - } - } - // construct []string from results - for _, s := range runes { - if len(s) > 0 { - entries = append(entries, string(s)) - } - } - return -} diff --git a/command.go b/command.go deleted file mode 100644 index 8bed8ba..0000000 --- a/command.go +++ /dev/null @@ -1,80 +0,0 @@ -package flags - -import ( - "reflect" -) - -// PreRunner is the equivalent of cobra cmd.PreRun(cmd *cobra.Command, args []string). -// The args parameter is populated following the same rules as `Commander.Execute()`. -type PreRunner interface { - PreRun(args []string) -} - -// PreRunnerE is the equivalent of cobra cmd.PreRunE(cmd *cobra.Command, args []string) error -// The args parameter is populated following the same rules as `Commander.Execute()`. -type PreRunnerE interface { - PreRunE(args []string) error -} - -// Commander is the simplest and smallest interface that a type must -// implement to be a valid, local, client command. This command can -// be used either in a single-run CLI app, or in a closed-loop shell. -type Commander interface { - // Execute runs the command implementation. - // The args parameter is any argument that has not been parsed - // neither on any parent command and/or its options, or this - // command and/or its args/options. - Execute(args []string) (err error) -} - -// Runner is the equivalent of cobra cmd.Run(cmd *cobra.Command, args []string) -// It will be ignored if the `flags.Commander` interface is satisfied. -// The args parameter is populated following the same rules as `Commander.Execute()`. -type Runner interface { - Run(args []string) -} - -// PostRunnerE is the equivalent of cobra cmd.RunE(cmd *cobra.Command, args []string) error -// The args parameter is populated following the same rules as `Commander.Execute()`. -type RunnerE interface { - RunE(args []string) error -} - -// PostRunnerE is the equivalent of cobra cmd.PostRun(cmd *cobra.Command, args []string) -// The args parameter is populated following the same rules as `Commander.Execute()`. -type PostRunner interface { - PostRun(args []string) -} - -// PostRunnerE is the equivalent of cobra cmd.PostRunE(cmd *cobra.Command, args []string) error -// The args parameter is populated following the same rules as `Commander.Execute()`. -type PostRunnerE interface { - PostRunE(args []string) error -} - -// IsCommand checks both tags and implementations on a pointer to a struct, -// initializing the value itself if it's nil (useful for callers). -func IsCommand(val reflect.Value) (reflect.Value, bool, Commander) { - // Initialize if needed - var ptrval reflect.Value - - // We just want to get interface, even if nil - if val.Kind() == reflect.Ptr { - ptrval = val - } else { - ptrval = val.Addr() - } - - // Assert implementation - cmd, implements := ptrval.Interface().(Commander) - if !implements { - return ptrval, false, nil - } - - // Once we're sure it's a command, initialize the field if needed. - if ptrval.IsNil() { - ptrval.Set(reflect.New(ptrval.Type().Elem())) - } - - return ptrval, true, cmd -} diff --git a/converters.go b/converters.go deleted file mode 100644 index dab013e..0000000 --- a/converters.go +++ /dev/null @@ -1,17 +0,0 @@ -package flags - -import ( - "strings" -) - -// transform s from CamelCase to flag-case. -func camelToFlag(s, flagDivider string) string { - splitted := split(s) - - return strings.ToLower(strings.Join(splitted, flagDivider)) -} - -// transform s from flag-case to CAMEL_CASE. -func flagToEnv(s, flagDivider, envDivider string) string { - return strings.ToUpper(strings.ReplaceAll(s, flagDivider, envDivider)) -} diff --git a/errors.go b/errors.go deleted file mode 100644 index 5c7fcb2..0000000 --- a/errors.go +++ /dev/null @@ -1,127 +0,0 @@ -package flags - -import ( - "errors" - "fmt" -) - -var ( - // ErrParse is a general error used to wrap more specific errors. - ErrParse = errors.New("parse error") - - // ErrNotPointerToStruct indicates that a provided data container is not - // a pointer to a struct. Only pointers to structs are valid data containers - // for options. - ErrNotPointerToStruct = errors.New("object must be a pointer to struct or interface") - - // ErrNotCommander is returned when an embedded struct is tagged as a command, - // but does not implement even the most simple interface, Commander. - ErrNotCommander = errors.New("provided data does not implement Commander") - - // ErrObjectIsNil is returned when the struct/object/pointer is nil. - ErrObjectIsNil = errors.New("object cannot be nil") - - // ErrInvalidTag indicates an invalid tag or invalid use of an existing tag. - ErrInvalidTag = errors.New("invalid tag") - - // ErrTag indicates an error while parsing flag tags. - ErrTag = errors.New("tag error") - - // ErrShortNameTooLong indicates that a short flag name was specified, - // longer than one character. - ErrShortNameTooLong = errors.New("short names can only be 1 character long") - - // ErrFlagHandler indicates that the custom handler for a flag has failed. - ErrFlagHandler = errors.New("custom handler for flag failed") - - // ErrNotValue indicates that a struct field type does not implement the - // Value interface. This only happens when the said type is a user-defined one. - ErrNotValue = errors.New("invalid field marked as flag") -) - -// simple wrapper for errors. -func newError(err error, msg string) error { - return fmt.Errorf("%s: %w", msg, err) -} - -// ParserError represents the type of error. -// type ParserError uint - -// ORDER IN WHICH THE ERROR CONSTANTS APPEAR MATTERS. -// const ( -// // ErrUnknown indicates a generic error. -// ErrUnknown ParserError = iota -// -// // ErrExpectedArgument indicates that an argument was expected. -// ErrExpectedArgument -// -// // ErrUnknownFlag indicates an unknown flag. -// ErrUnknownFlag -// -// // ErrUnknownGroup indicates an unknown group. -// ErrUnknownGroup -// -// // ErrMarshal indicates a marshalling error while converting values. -// ErrMarshal -// -// // ErrHelp indicates that the built-in help was shown (the error -// // contains the help message). -// ErrHelp -// -// // ErrNoArgumentForBool indicates that an argument was given for a -// // boolean flag (which don't not take any arguments). -// ErrNoArgumentForBool -// -// // ErrRequired indicates that a required flag was not provided. -// ErrRequired -// -// // ErrShortNameTooLong indicates that a short flag name was specified, -// // longer than one character. -// // ErrShortNameTooLong -// -// // ErrDuplicatedFlag indicates that a short or long flag has been -// // defined more than once. -// ErrDuplicatedFlag -// -// // ErrTag indicates an error while parsing flag tags. -// // ErrTag -// -// // ErrCommandRequired indicates that a command was required but not -// // specified. -// ErrCommandRequired -// -// // ErrUnknownCommand indicates that an unknown command was specified. -// ErrUnknownCommand -// -// // ErrInvalidChoice indicates an invalid option value which only allows -// // a certain number of choices. -// ErrInvalidChoice -// -// // ErrInvalidTag indicates an invalid tag or invalid use of an existing tag. -// // ErrInvalidTag -// ) - -// func (e ParserError) String() string { -// errs := [...]string{ -// // Public -// "unknown", // ErrUnknown -// "expected argument", // ErrExpectedArgument -// "unknown flag", // ErrUnknownFlag -// "unknown group", // ErrUnknownGroup -// "marshal", // ErrMarshal -// "help", // ErrHelp -// "no argument for bool", // ErrNoArgumentForBool -// "duplicated flag", // ErrDuplicatedFlag -// // "tag", // ErrTag -// "command required", // ErrCommandRequired -// "unknown command", // ErrUnknownCommand -// "invalid choice", // ErrInvalidChoice -// // "invalid tag", // ErrInvalidTag -// } -// if len(errs) > int(e) { -// return "unrecognized error type" -// } -// -// return errs[e] -// } -// diff --git a/example/args/commands.go b/example/args/commands.go index 158bd1d..45aaaff 100644 --- a/example/args/commands.go +++ b/example/args/commands.go @@ -50,7 +50,7 @@ type MultipleListsArgs struct { // - If one argument is passed, it will be stored in this slot. // - If two arguments, one is stored here, and the first is stored in Vuln // - If three or more, two will be stored here, and the others in Vuln. - Other []Host `description:"Other list of IP addresses" required:"1-2"` + Other []Host `desc:"Other list of IP addresses" required:"1-2"` } `positional-args:"yes"` } @@ -88,7 +88,7 @@ The behavior is the following: type FirstListArgs struct { Args struct { Hosts []Host `description:"A list of hosts with minimum and maximum requirements" required:"1-2"` - Target Proxy `description:"A single, required remaining argument" required:"1"` + Target Proxy `description:"A single, required remaining argument" required:"1"` } `positional-args:"yes" required:"yes"` } @@ -136,9 +136,9 @@ declare their own requirements. // Since the IP slot is also a list, all arguments in excess (here, if more than 5 args) will be stored in it. type MultipleMinMaxArgs struct { Args struct { - Hosts []Host `description:"A list of hosts with minimum and maximum requirements" required:"1-2"` + Hosts []Host `description:"A list of hosts with minimum and maximum requirements" required:"1-2"` Proxies []Proxy `description:"A list of proxies, with min/max requirements overlapping with Hosts" required:"1-2"` - Addresses IP `description:"A last list of IPs, which will store any words given in excess" required:"1"` + Addresses IP `description:"A last list of IPs, which will store any words given in excess" required:"1"` } `positional-args:"yes" required:"yes"` } @@ -178,10 +178,10 @@ type TagCompletedArgs struct { // Files accepts at most two values, and the completions for them will be restricted to files with a '.go' extension. // Since this slot has a min and max requirement value, once one argument is provided at the command-line, completions // will be proposed both for this slot and for the next one, up until the maximum requirements are fulfilled. - Files []string `description:"A list of files with min/max requirements" required:"1-2" complete:"FilterExt,go"` + Files []string `complete:"FilterExt,go" description:"A list of files with min/max requirements" required:"1-2"` // JSONConfig also completes files, but with a .json extension. - JSONConfig string `description:"the target of your command (anything string-based)" required:"1" complete:"FilterExt,json"` + JSONConfig string `complete:"FilterExt,json" description:"the target of your command (anything string-based)" required:"1"` } `positional-args:"yes" required:"yes"` } diff --git a/example/args/positionals.go b/example/args/positionals.go index afc680b..f7b8b9b 100644 --- a/example/args/positionals.go +++ b/example/args/positionals.go @@ -1,8 +1,8 @@ package args import ( - "github.com/rsteube/carapace" - "github.com/rsteube/carapace/pkg/style" + "github.com/carapace-sh/carapace" + "github.com/carapace-sh/carapace/pkg/style" ) // IP is another argument field, but which implements @@ -15,7 +15,7 @@ func (ip *IP) Complete(ctx carapace.Context) carapace.Action { "23:23:234:34ef:343f:47ca", "An IPv6 address", style.BrightGreen, "::1", "a test address", style.BrightGreen, "10.10.10.10", "An intruder", style.Blue, - ).Tag("IPv6 addresses").Invoke(ctx).Filter(ctx.Args).ToA() + ).Tag("IPv6 addresses").Invoke(ctx).Filter(ctx.Args...).ToA() return action } @@ -31,7 +31,7 @@ func (p *Host) Complete(ctx carapace.Context) carapace.Action { "10.203.23.45", "and a third one", style.BrightCyan, "127.0.0.1", "and a third one", style.BrightCyan, "219.293.91.10", "", style.Blue, - ).Tag("IPv4 addresses").Invoke(ctx).Filter(ctx.Args).ToA() + ).Tag("IPv4 addresses").Invoke(ctx).Filter(ctx.Args...).ToA() return action } @@ -45,7 +45,7 @@ func (p *Proxy) Complete(ctx carapace.Context) carapace.Action { "github.com", "A first ip address", "google.com", "a second address", "blue-team.com", "and a third one", - ).Tag("host domains").Invoke(ctx).Filter(ctx.Args).ToA() + ).Tag("host domains").Invoke(ctx).Filter(ctx.Args...).ToA() return action } diff --git a/example/commands/root.go b/example/commands/root.go index 96bc58b..f95aec8 100644 --- a/example/commands/root.go +++ b/example/commands/root.go @@ -1,10 +1,11 @@ package commands import ( + "github.com/spf13/cobra" + "github.com/reeflective/flags/example/args" "github.com/reeflective/flags/example/opts" "github.com/reeflective/flags/example/validated" - "github.com/spf13/cobra" ) const ( @@ -33,10 +34,10 @@ type Root struct { // First remarks: // - The commands are registered individually, but each is tagged with a group (eg, they are not grouped in a struct) args.MultipleListsArgs `command:"multiple-ambiguous" description:"Demonstrates an ambiguous use of several lists and tag min-max requirements" group:"positionals"` - args.FirstListArgs `command:"list-first" description:"Use several positionals, of which the first is a list, but not the last." group:"positionals"` - args.MultipleMinMaxArgs `command:"overlap-min-max" description:"Use multiple lists as positionals, with overlapping min/max requirements" group:"positionals"` - args.TagCompletedArgs `command:"tag-completed" description:"Specify completers with struct tags" group:"positionals"` - args.RestSliceMax `command:"rest-slice-max" desc:"Shows how declaring a rest slice will behave when having a maximum words allowed" group:"positionals"` + args.FirstListArgs `command:"list-first" description:"Use several positionals, of which the first is a list, but not the last." group:"positionals"` + args.MultipleMinMaxArgs `command:"overlap-min-max" description:"Use multiple lists as positionals, with overlapping min/max requirements" group:"positionals"` + args.TagCompletedArgs `command:"tag-completed" description:"Specify completers with struct tags" group:"positionals"` + args.RestSliceMax `command:"rest-slice-max" desc:"Shows how declaring a rest slice will behave when having a maximum words allowed" group:"positionals"` // // Flags commands ---------------------------------------------------------------- @@ -46,9 +47,9 @@ type Root struct { // // First remarks: // - As with the 'positionals' commands above, each of these command is embedded individually, and each is tagged with its group name. - opts.BasicOptions `command:"basic" alias:"ba" desc:"Shows how to use some basic flags (shows option stacking, and maps)" group:"flags"` - opts.IgnoredOptions `command:"ignored" desc:"Contains types tagged as flags (automatically initialized), and types to be ignored (not tagged)" group:"flags"` - opts.DefaultOptions `command:"defaults" desc:"Contains flags with default values, and others with validated choices" group:"flags"` + opts.BasicOptions `alias:"ba" command:"basic" desc:"Shows how to use some basic flags (shows option stacking, and maps)" group:"flags"` + opts.IgnoredOptions `command:"ignored" desc:"Contains types tagged as flags (automatically initialized), and types to be ignored (not tagged)" group:"flags"` + opts.DefaultOptions `command:"defaults" desc:"Contains flags with default values, and others with validated choices" group:"flags"` // Validated args/flags ---------------------------------------------------------- // diff --git a/example/example b/example/example deleted file mode 100755 index c1312d3..0000000 Binary files a/example/example and /dev/null differ diff --git a/example/main.go b/example/main.go index 9989248..6e4d279 100644 --- a/example/main.go +++ b/example/main.go @@ -1,11 +1,11 @@ package main import ( + "fmt" + "os" + "github.com/reeflective/flags" "github.com/reeflective/flags/example/commands" - "github.com/reeflective/flags/gen/completions" - genflags "github.com/reeflective/flags/gen/flags" - "github.com/reeflective/flags/validator" ) func main() { @@ -16,18 +16,22 @@ func main() { // Options can be used for several purposes: // influence the flags naming conventions, register // other scan handlers for specialized work, etc... - var opts []flags.OptFunc + var opts []flags.Option // One example of specialized handler is the validator, // which checks for struct tags specifying validations: // when found, this handler wraps the generated flag into // a special value which will validate the user input. - opts = append(opts, flags.Validator(validator.New())) + opts = append(opts, flags.WithValidation()) // Run the scan: this generates the entire command tree // into a cobra root command (and its subcommands). // By default, the name of the command is os.Args[0]. - rootCmd := genflags.Generate(rootData, opts...) + rootCmd, err := flags.Parse(rootData, opts...) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } // Since we now dispose of a cobra command, we can further // set it up to our liking: modify/set fields and options, etc. @@ -41,15 +45,6 @@ func main() { // various commands' packages, which we also bind now. commands.AddCommandsLongHelp(rootCmd) - // The completion generator is another example of specialized - // scan handler: it will generate completers if it finds tags - // specifying what to complete, or completer implementations - // by the positional arguments / command flags' types themselves. - comps, _ := completions.Generate(rootCmd, rootData, nil) - - // (Needed by carapace library to mute some cobra commands) - comps.Standalone() - // As well, we can now execute our cobra command tree as usual. rootCmd.Execute() } diff --git a/example/opts/commands.go b/example/opts/commands.go index c6edfce..acec212 100644 --- a/example/opts/commands.go +++ b/example/opts/commands.go @@ -14,15 +14,15 @@ import ( // (eg, options grouped in a struct), but just declares them at the root level. type BasicOptions struct { // First flag tags notation - Path string `short:"p" long:"path" description:"a path used by your command" optional-value:"/home/user" complete:"Files"` - Files []string `short:"f" long:"files" desc:"A list of files, with repeated flags or comma-separated items" complete:"Files"` - Elems map[string]string `short:"e" long:"elems" description:"A map[string]string flag, can be repeated or used with comma-separated items" choice:"user:host machine:testing another:target"` - Check bool `long:"check" short:"c" description:"a boolean checker, can be used in an option stacking, like -cp "` - Machines Machines `long:"machines" short:"m" description:"A type that implements user@host (multipart) completion"` + Path string `complete:"Files" description:"a path used by your command" long:"path" optional-value:"/home/user" short:"p" xor:"filesystem"` + Files []string `complete:"Files" desc:"A list of files, with repeated flags or comma-separated items" long:"files" short:"f" xor:"filesystem"` + Elems map[string]string `choice:"user:host machine:testing another:target" description:"A map[string]string flag, can be repeated or used with comma-separated items" long:"elems" short:"e"` + Check bool `description:"a boolean checker, can be used in an option stacking, like -cp " long:"check" short:"c"` + Machine Machine `description:"A type that implements user@host (multipart) completion" long:"machine" short:"m"` // Second flag tag notation - Alternate string `flag:"alternate a" desc:"A flag declared with struct tag flag:\"a alternate\" instead of short:\"a\" / long:\"alternate\""` - Email []string `flag:"email E" desc:"An email address, validated with go-playground/validator" validate:"email"` + Alternate string `desc:"A flag declared with struct tag flag:\"a alternate\" instead of short:\"a\" / long:\"alternate\"" flag:"alternate a"` + Email []string `desc:"An email address, validated with go-playground/validator" flag:"email E" validate:"email"` } // Execute is the command implementation, shows how options are parsed. @@ -31,6 +31,7 @@ func (c *BasicOptions) Execute(args []string) error { fmt.Printf("Files ([]string): %v\n", c.Files) fmt.Printf("Elems (map[string]string): %v\n", c.Elems) fmt.Printf("Check (bool): %v\n\n", c.Check) + fmt.Printf("Machines (string): %v\n\n", c.Machine) fmt.Printf("Alternate (string): %v\n", c.Alternate) fmt.Printf("Email (string): %v\n", c.Email) @@ -54,7 +55,6 @@ func (c *GroupedOptions) Execute(args []string) error { // fmt.Printf("Path (string): %v\n", c.Path) // fmt.Printf("Elems (map[string]string): %v\n", c.Elems) // fmt.Printf("Check (bool): %v\n", c.Check) - return nil } @@ -62,10 +62,10 @@ func (c *GroupedOptions) Execute(args []string) error { // and how it automatically initializes those fields if they are pointers. type IgnoredOptions struct { // Both types below are automatically initialized by the library, since we consider them as (groups of) flags. - Verbose *bool `short:"v" long:"verbose" desc:"This pointer to bool type is marked as flag with struct tags"` + Verbose *bool `desc:"This pointer to bool type is marked as flag with struct tags" long:"verbose" short:"v"` Group *struct { - Path *string `short:"p" long:"path" description:"A pointer to a string, which is automatically initialized by the library"` - Check bool `long:"check" short:"c" description:"a boolean checker, can be used in an option stacking, like -cp "` + Path *string `description:"A pointer to a string, which is automatically initialized by the library" long:"path" short:"p"` + Check bool `description:"a boolean checker, can be used in an option stacking, like -cp " long:"check" short:"c"` } `group:"group pointer"` // Both types below are not marked either as groups, or as options: @@ -94,8 +94,8 @@ type DefaultOptions struct { // Extensions illustrate the two possible uses of the `choice` tag: // - With a single value, but with multiple tag uses. // - With multiple values, space-separated. - Extensions []string `short:"e" long:"extensions" desc:"A flag with validated choices" choice:".json .go .yaml"` - Defaults string `short:"d" long:"default" desc:"A flag with a default value, if not specified" optional-value:"my-value"` + Extensions []string `choice:".json .go .yaml" desc:"A flag with validated choices" long:"extensions" short:"e"` + Defaults string `desc:"A flag with a default value, if not specified" long:"default" optional-value:"my-value" short:"d"` } // Execute is the command implementation, shows how options are parsed. @@ -114,6 +114,5 @@ func (c *NamespacedOptions) Execute(args []string) error { // fmt.Printf("Path (string): %v\n", c.Path) // fmt.Printf("Elems (map[string]string): %v\n", c.Elems) // fmt.Printf("Check (bool): %v\n", c.Check) - return nil } diff --git a/example/opts/options.go b/example/opts/options.go index 5bea687..a515848 100644 --- a/example/opts/options.go +++ b/example/opts/options.go @@ -4,8 +4,9 @@ import ( "reflect" "strings" - "github.com/rsteube/carapace" - "github.com/rsteube/carapace-bin/pkg/actions/net" + "github.com/carapace-sh/carapace" + "github.com/carapace-sh/carapace-bin/pkg/actions/net/ssh" + "github.com/carapace-sh/carapace-bin/pkg/actions/os" ) // @@ -14,10 +15,10 @@ import ( // GroupedOptionsBasic shows how to group options together, with basic struct tags. type GroupedOptionsBasic struct { - Path string `short:"p" long:"path" description:"a path used by your command"` - Elems map[string]string `short:"e" long:"elems" description:"A map[string]string flag, with repeated flags or comma-separated items"` - Files []string `short:"f" long:"files" desc:"A list of files, with repeated flags or comma-separated items"` - Check bool `long:"check" short:"c" description:"a boolean checker, can be used in an option stacking, like -cp "` + Path string `description:"a path used by your command" long:"path" placeholder:"PATH" short:"p"` + Elems map[string]string `description:"A map[string]string flag, with repeated flags or comma-separated items" long:"elems" short:"e"` + Files []string `desc:"A list of files, with repeated flags or comma-separated items" long:"files" placeholder:"FILE1 FILE2" short:"f"` + Check bool `description:"a boolean checker, can be used in an option stacking, like -cp " long:"check" short:"c"` } // RequiredOptions shows how to specify requirements for options. @@ -26,29 +27,30 @@ type RequiredOptions struct{} // TagCompletedOptions shows how to specify completers through struct tags. type TagCompletedOptions struct{} -// Machines is a type that implements multipart completion. -type Machines string +// Machine is a type that implements multipart completion. +type Machine string // Complete provides user@host completions. -func (m *Machines) Complete(ctx carapace.Context) carapace.Action { +func (m *Machine) Complete(ctx carapace.Context) carapace.Action { if strings.Contains(ctx.Value, "@") { prefix := strings.SplitN(ctx.Value, "@", 2)[0] - return net.ActionHosts().Invoke(ctx).Prefix(prefix + "@").ToA() + + return ssh.ActionHosts().Invoke(ctx).Prefix(prefix + "@").ToA() } else { - return net.ActionHosts() + return os.ActionUsers().Suffix("@").NoSpace('@') } } -func (p *Machines) String() string { - return string(*p) +func (m *Machine) String() string { + return string(*m) } -func (p *Machines) Set(value string) error { - *p = (Machines)(value) +func (m *Machine) Set(value string) error { + *m = (Machine)(value) return nil } -func (p *Machines) Type() string { - return reflect.TypeOf(*p).Kind().String() +func (m *Machine) Type() string { + return reflect.TypeOf(*m).Kind().String() } diff --git a/example/validated/commands.go b/example/validated/commands.go index 0b73b21..3985935 100644 --- a/example/validated/commands.go +++ b/example/validated/commands.go @@ -9,14 +9,14 @@ import ( // validation to their positional args or flags. type Commands struct { ValidatedArgs `command:"valid-positionals" desc:"Positional arguments validated with struct tag directives"` - ValidatedFlags `command:"valid-flags" desc:"Flags validated with struct tag directives"` + ValidatedFlags `command:"valid-flags" desc:"Flags validated with struct tag directives"` } // ValidatedArgs is a command whose positionals are being validated. type ValidatedArgs struct { Args struct { - IP string `description:"An IPv4 address" validate:"ipv4"` - Emails []string `description:"A list of email addresses" required:"1-2" validate:"email"` + IP string `description:"An IPv4 address" validate:"ipv4"` + Emails []string `description:"A list of email addresses" required:"1-2" validate:"email"` } `positional-args:"yes"` } @@ -29,10 +29,10 @@ func (c *ValidatedArgs) Execute(args []string) error { // ValidatedArgs is a command whose flags' arguments are being validated. type ValidatedFlags struct { - Path string `short:"p" long:"path" description:"A valid path on your system" complete:"Files" validate:"file"` - OptionalPath string `short:"d" long:"opt-dir" description:"A validated directory on your system, with a default value" optional-value:"/home/user" complete:"Files" validate:"dir"` - Files []string `short:"f" long:"files" desc:"A list of files, each validated" complete:"Files" validate:"file"` - Elems map[string]string `short:"e" long:"elems" description:"A map[string]string flag, can be repeated or used with comma-separated items" choice:"user:host machine:testing another:target"` + Path string `complete:"Files" description:"A valid path on your system" long:"filepath" short:"p" validate:"file"` + OptionalPath string `complete:"Files" description:"A validated directory on your system, with a default value" long:"opt-dir" optional-value:"/home/user" short:"d" validate:"dir"` + Files []string `complete:"Files" desc:"A list of files, each validated" long:"files" short:"f" validate:"file"` + Elems map[string]string `choice:"user:host machine:testing another:target" description:"A map[string]string flag, can be repeated or used with comma-separated items" long:"elems" short:"e"` } func (c *ValidatedFlags) Execute(args []string) error { diff --git a/flag.go b/flag.go deleted file mode 100644 index 02d0672..0000000 --- a/flag.go +++ /dev/null @@ -1,29 +0,0 @@ -// Package flags generates CLI application commands/flags by parsing structures. -package flags - -// Flag structure might be used by cli/flag libraries for their flag generation. -type Flag struct { - Name string // name as it appears on command line - Short string // optional short name - EnvName string - Usage string // help message - Value Value // value as set - DefValue []string // default value (as text); for usage message - Hidden bool - Deprecated bool - - // If true, the option _must_ be specified on the command line. If the - // option is not specified, the parser will generate an ErrRequired type - // error. - Required bool - - // If non empty, only a certain set of values is allowed for an option. - Choices []string - - // The optional value of the option. The optional value is used when - // the option flag is marked as having an OptionalArgument. This means - // that when the flag is specified, but no option argument is given, - // the value of the field this option represents will be set to - // OptionalValue. This is only valid for non-boolean options. - OptionalValue []string -} diff --git a/flags.go b/flags.go index 0f2a4e8..b8ef584 100644 --- a/flags.go +++ b/flags.go @@ -1,91 +1,193 @@ -// Package flags is the root package of the `github.com/reeflective/flags` library. +// Package flags provides a powerful, reflection-based way to generate modern +// command-line interfaces (CLIs) from Go structs. It uses spf13/cobra for +// command execution and rsteube/carapace for advanced shell completion. // -// If you are searching for the list of valid tags to use on structs for specifying -// commands/flags specs, check https://github.com/reeflective/flags/gen/flags/flags.go. +// The primary workflow is to define your CLI structure (commands, flags, +// positional arguments) using Go structs and field tags, and then call +// flags.ParseCommands() to create a fully configured *cobra.Command tree, complete +// with shell completions, ready for execution. // -// 1) Importing the various packages ----------------------------------------------------- -// -// This file gives a list of the various global parsing options that can be passed -// to the `Generate()` entrypoint function in the `gen/flags` package. Below is an -// example of how you want to import this package and use its options: -// -// package main -// -// import ( -// -// "github.com/reeflective/flags/example/commands" -// -// "github.com/reeflective/flags" -// genflags "github.com/reeflective/flags/gen/flags" -// -// "github.com/reeflective/flags/validator" -// "github.com/reeflective/flags/gen/completions" -// -// ) -// -// func main() { -// var opts []flags.OptFunc -// -// opts = append(opts, flags.Validator(validator.New())) -// -// rootData := &commands.Root{} -// rootCmd := genflags.Generate(rootData, opts...) -// -// comps, _ := completions.Generate(rootCmd, rootData, nil) -// } -// -// 2) Global parsing options (base) ------------------------------------------------------ -// -// Most of the options below are inherited from github.com/octago/sflags, with some added. -// -// DescTag sets custom description tag. It is "desc" by default. -// func DescTag(val string) -// -// FlagTag sets custom flag tag. It is "flag" be default. -// func FlagTag(val string) -// -// Prefix sets prefix that will be applied for all flags (if they are not marked as ~). -// func Prefix(val string) -// -// EnvPrefix sets prefix that will be applied for all environment variables (if they are not marked as ~). -// func EnvPrefix(val string) -// -// FlagDivider sets custom divider for flags. It is dash by default. e.g. "flag-name". -// func FlagDivider(val string) -// -// EnvDivider sets custom divider for environment variables. -// It is underscore by default. e.g. "ENV_NAME". -// func EnvDivider(val string) -// -// Flatten set flatten option. -// Set to false if you don't want anonymous structure fields to be flatten. -// func Flatten(val bool) -// -// ParseAll orders the parser to generate a flag for all struct fields, even if there isn't a struct -// tag attached to them. This is because by default the library does not considers untagged field anymore. -// func ParseAll() -// -// 3) Special parsing options/functions--------------------------------------------------- -// -// ValidateFunc describes a validation func, that takes string val for flag from command line, -// field that's associated with this flag in structure `data`. Also works for positional arguments. -// Should return error if validation fails. -// -// type ValidateFunc func(val string, field reflect.StructField, data interface{}) error -// -// Validator sets validator function for flags. -// Check existing validators in flags/validator and flags/validator/govalidator packages. -// -// func Validator(val ValidateFunc) -// FlagFunc is a generic function that can be applied to each -// value that will end up being a flags *Flag, so that users -// can perform more arbitrary operations on each, such as checking -// for completer implementations, bind to viper configurations, etc. -// -// type FlagFunc func(flag string, tag tag.MultiTag, val reflect.Value) error -// -// FlagHandler sets the handler function for flags, in order to perform arbitrary -// operations on the value of the flag identified by the name parameter of FlagFunc. -// -// func FlagHandler(val FlagFunc) +// For useful, pre-built flag types like Counter or HexBytes, see the +// subpackage at "github.com/reeflective/flags/types". package flags + +import ( + "fmt" + + "github.com/carapace-sh/carapace" + "github.com/go-playground/validator/v10" + "github.com/spf13/cobra" + + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/gen" + "github.com/reeflective/flags/internal/interfaces" + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/validation" + "github.com/reeflective/flags/internal/values" +) + +// === Primary Entry Points === + +// Generate parses a struct and creates a new, fully configured *cobra.Command. +// The provided `data` argument must be a pointer to a struct. Struct fields +// tagged with `command:"..."` become subcommands, and other tagged fields +// become flags. A struct implementing one of the Runner interfaces becomes +// an executable command. +// +// Shell completions are generated and attached automatically. +// +// This is the primary entry point for creating a new CLI application. +func Parse(data any, opts ...Option) (*cobra.Command, error) { + cmd, err := gen.Generate(data, toInternalOpts(opts)...) + if err != nil { + return nil, fmt.Errorf("failed to generate command: %w", err) + } + + return cmd, nil +} + +// Bind parses a struct and binds its commands, flags, and positional arguments +// to an existing *cobra.Command. This is useful for integrating flags with a +// command tree that is partially managed manually. +// +// Shell completions for the bound components are generated and attached automatically. +func Bind(cmd *cobra.Command, data any, opts ...Option) error { + if err := gen.Bind(cmd, data, toInternalOpts(opts)...); err != nil { + return fmt.Errorf("failed to bind command: %w", err) + } + + return nil +} + +// === Configuration (Functional Options) === + +// Option is a functional option for configuring command and flag generation. +type Option func(o *parser.Opts) + +func toInternalOpts(opts []Option) []parser.OptFunc { + internalOpts := make([]parser.OptFunc, len(opts)) + for i, opt := range opts { + internalOpts[i] = parser.OptFunc(opt) + } + + return internalOpts +} + +// WithPrefix sets a prefix that will be applied to all long flag names. +func WithPrefix(prefix string) Option { + return Option(parser.Prefix(prefix)) +} + +// WithEnvPrefix sets a prefix for all environment variables. +func WithEnvPrefix(prefix string) Option { + return Option(parser.EnvPrefix(prefix)) +} + +// WithFlagDivider sets the character used to separate words in long flag names. +func WithFlagDivider(divider string) Option { + return Option(parser.FlagDivider(divider)) +} + +// WithEnvDivider sets the character used to separate words in environment variable names. +func WithEnvDivider(divider string) Option { + return Option(parser.EnvDivider(divider)) +} + +// WithVars adds a map of variables that can be used for expansion in tags. +func WithVars(vars map[string]string) Option { + return Option(parser.WithVars(vars)) +} + +// === Validation === + +// ValidateFunc is the core validation function type. +// It takes the actual Go value to validate, the validation tag string, +// and the field name for error reporting. +// This is the simplified interface the user wants to implement. +type ValidateFunc = validation.ValidateFunc + +// WithValidation adds field validation for fields with the "validate" tag. +// This makes use of go-playground/validator internally, refer to their docs +// for an exhaustive list of valid tag validations. +func WithValidation() Option { + return Option(parser.Validator(validation.NewDefault())) +} + +// WithValidator registers a custom validation function for flags and arguments. +// It is required to pass a go-playground/validator object for customization. +// The latter library has been chosen because it supports most of the validation +// one would want in CLI, and because there are vast possibilities for registering +// and using custom validations through the *Validate type. +func WithValidator(v *validator.Validate) Option { + return Option(parser.Validator(validation.NewWith(v))) +} + +// === Completion === + +// WithCompleter adds a custom completer function to the parser options. +// You can use this completer by tagging flag or positional arg struct fields +// with `complete:"custom-completer-name"`, and bind this completer under the +// same name in this function. +func WithCompleter(name string, completer carapace.CompletionCallback) Option { + return Option(parser.WithCompleter(name, completer)) +} + +// === Core Interfaces === + +// Commander is the primary interface for a struct to be recognized as an +// executable command. Its Execute method is bound to cobra.Command.RunE. +type Commander = interfaces.Commander + +// Runner is a simpler command interface bound to cobra.Command.Run. +// It is ignored if the struct also implements Commander. +type Runner = interfaces.Runner + +// PreRunner is the equivalent of cobra.Command.PreRun. +type PreRunner = interfaces.PreRunner + +// PreRunnerE is the equivalent of cobra.Command.PreRunE. +type PreRunnerE = interfaces.PreRunnerE + +// PostRunner is the equivalent of cobra.Command.PostRun. +type PostRunner = interfaces.PostRunner + +// PostRunnerE is the equivalent of cobra.Command.PostRunE. +type PostRunnerE = interfaces.PostRunnerE + +// Value is the interface for custom flag types. +type Value = values.Value + +// Marshaler is the interface implemented by types that can marshal themselves +// to a string representation of the flag. Retroported from jessevdk/go-flags. +type Marshaler = interfaces.Marshaler + +// Unmarshaler is the interface implemented by types that can unmarshal a flag +// argument to themselves. The provided value is directly passed from the +// command line. Retroported from jessevdk/go-flags. +type Unmarshaler = interfaces.Unmarshaler + +// Completer is the interface for types that can provide their own shell +// completion suggestions. +type Completer = interfaces.Completer + +// === Public Errors === + +var ( + // ErrParse is a general error used to wrap more specific parsing errors. + ErrParse = errors.ErrParse + + // ErrNotPointerToStruct indicates that a provided data container is not + // a pointer to a struct. + ErrNotPointerToStruct = errors.ErrNotPointerToStruct + + // ErrNotCommander is returned when a struct is tagged as a command but + // does not implement a command interface (e.g., Commander). + ErrNotCommander = errors.ErrNotCommander + + // ErrInvalidTag indicates an invalid tag or invalid use of an existing tag. + ErrInvalidTag = errors.ErrInvalidTag + + // ErrNotValue indicates that a struct field type for a flag does not + // implement the flags.Value interface. + ErrNotValue = errors.ErrNotValue +) diff --git a/flags.wiki b/flags.wiki deleted file mode 160000 index 4bbb849..0000000 --- a/flags.wiki +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 4bbb84910a80ca4d17c561437ee6d09e2b135248 diff --git a/gen/completions/command.go b/gen/completions/command.go deleted file mode 100644 index 7baf5ce..0000000 --- a/gen/completions/command.go +++ /dev/null @@ -1,122 +0,0 @@ -package completions - -import ( - "fmt" - "reflect" - - "github.com/reeflective/flags" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - comp "github.com/rsteube/carapace" - "github.com/spf13/cobra" -) - -// Gen uses a carapace completion builder to register various completions to its underlying -// cobra command, parsing again the native struct for type and struct tags' information. -// Arguments: -// @cmd - The application root cobra command, or an arbitrary one. -// @data - The struct containing commands/flags/positionals to scan for. -// @comps - An optional, preexisting carapace engine. Most of the time, this can be nil. -// -// Returns the carapace, so you can further work with/register completions should you like to. -func Generate(cmd *cobra.Command, data interface{}, comps *comp.Carapace) (*comp.Carapace, error) { - // Generate the completions a first time. - completions, err := generate(cmd.Root(), data, comps) - if err != nil { - return completions, err - } - - return completions, nil -} - -// generate wraps all main steps' invocations, to be reused in various cases. -func generate(cmd *cobra.Command, data interface{}, comps *comp.Carapace) (*comp.Carapace, error) { - if comps == nil { - comps = comp.Gen(cmd) - } - - // Each command has, by default, a map of flag completions, - // which is used for flags that are not contained in a struct group. - defaultFlagComps := flagSetComps{} - - // A command always accepts embedded subcommand struct fields, so scan them. - compScanner := completionScanner(cmd, comps, &defaultFlagComps) - - // Scan the struct recursively, for both arg/option groups and subcommands - if err := scan.Type(data, compScanner); err != nil { - return comps, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - return comps, nil -} - -// completionScanner is in charge of building a recursive scanner, working on a given -// struct field at a time, checking for arguments, subcommands and option groups. -func completionScanner(cmd *cobra.Command, comps *comp.Carapace, flags *flagSetComps) scan.Handler { - handler := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { - mtag, none, err := tag.GetFieldTag(*sfield) - if none || err != nil { - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - // If the field is marked as -one or more- positional arguments, we - // return either on a successful scan of them, or with an error doing so. - if found, err := positionals(comps, mtag, val); found || err != nil { - return found, err - } - - // Else, if the field is marked as a subcommand, we either return on - // a successful scan of the subcommand, or with an error doing so. - if found, err := command(cmd, mtag, val); found || err != nil { - return found, err - } - - // Else, try scanning the field as a group of commands/options, - // and only use the completion stuff we find on them. - if found, err := groupComps(comps, cmd, val, sfield); found || err != nil { - return found, err - } - - // Else, try scanning the field as a simple option flag - return flagComps(comps, flags)(val, sfield) - } - - return handler -} - -// command finds if a field is marked as a command, and if yes, scans it. -func command(cmd *cobra.Command, tag tag.MultiTag, val reflect.Value) (bool, error) { - // Parse the command name on struct tag... - name, _ := tag.Get("command") - if len(name) == 0 { - return false, nil - } - - // ... and check the field implements at least the Commander interface - _, implements, commander := flags.IsCommand(val) - if !implements { - return false, nil - } - - var subc *cobra.Command - - // The command already exists, bound to our current command. - for _, subcmd := range cmd.Commands() { - if subcmd.Name() == name { - subc = subcmd - } - } - - if subc == nil { - return false, fmt.Errorf("%w: %s", errCommandNotFound, name) - } - - // Simply generate a new carapace around this command, - // so that we can register different positional arguments - // without overwriting those of our root command. - if _, err := generate(subc, commander, nil); err != nil { - return true, err - } - - return true, nil -} diff --git a/gen/completions/completion.go b/gen/completions/completion.go deleted file mode 100644 index a83b6e2..0000000 --- a/gen/completions/completion.go +++ /dev/null @@ -1,229 +0,0 @@ -package completions - -import ( - "errors" - "reflect" - "strings" - - "github.com/reeflective/flags/internal/tag" - comp "github.com/rsteube/carapace" -) - -// Completer represents a type that is able to return some completions based on the current carapace Context. -// Please see https://rsteube.github.io/carapace/carapace.html for using the carapace library completers, -// or https://github.com/reeflective/flags/wiki/Completions for an overview of completion features/use. -type Completer interface { - Complete(ctx comp.Context) comp.Action -} - -// compDirective identifies one of reflags' builtin completer functions. -type compDirective int - -const ( - // Public directives =========================================================. - - // compError indicates an error occurred and completions should handled accordingly. - compError compDirective = 1 << iota - - // compNoSpace indicates that the shell should not add a space after - // the completion even if there is a single completion provided. - compNoSpace - - // compNoFiles forbids file completion when no other comps are available. - compNoFiles - - // compFilterExt only complete files that are part of the given extensions. - compFilterExt - - // compFilterDirs only complete files within a given set of directories. - compFilterDirs - - // compFiles completes all files found in the current filesystem context. - compFiles - - // compDirs completes all directories in the current filesystem context. - compDirs - - // Internal directives (must be below) =======================================. - - // 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 compDirective = 0 -) - -var errCommandNotFound = errors.New("command not found") - -const ( - completeTagName = "complete" - completeTagMaxParts = 2 -) - -func getCompletionAction(name, value, desc string) comp.Action { - var action comp.Action - - switch strings.ToLower(name) { - case "nospace": - return action.NoSpace() - case "nofiles": - case "filterext": - filterExts := strings.Split(value, ",") - action = comp.ActionFiles(filterExts...).Tag("filtered extensions").NoSpace('/') - case "filterdirs": - action = comp.ActionDirectories().NoSpace('/').Tag("filtered directories") // TODO change this - case "files": - files := strings.Split(value, ",") - action = comp.ActionFiles(files...).NoSpace('/') - case "dirs": - action = comp.ActionDirectories().NoSpace('/') - - // Should normally not be used often - case "default": - return action - } - - return action -} - -// typeCompleterAlt checksw for completer implementations on the type, checks -// if the implementations are on the type of its elements (if slice/map), and -// returns the results. -func typeCompleter(val reflect.Value) (comp.CompletionCallback, bool, bool) { - isRepeatable := false - itemsImplement := false - - var completer comp.CompletionCallback - - // Always check that the type itself does implement, even if - // it's a list of type X that implements the completer as well. - // If yes, we return this implementation, since it has priority. - if val.Type().Kind() == reflect.Slice { - isRepeatable = true - - i := val.Interface() - if impl, ok := i.(Completer); ok { - completer = impl.Complete - } else if val.CanAddr() { - if impl, ok := val.Addr().Interface().(Completer); ok { - completer = impl.Complete - } - } - - // Else we reassign the value to the list type. - val = reflect.New(val.Type().Elem()) - } - - // If we did NOT find an implementation on the compound type, - // check for one on the items. - if completer == nil { - i := val.Interface() - if impl, ok := i.(Completer); ok && impl != nil { - itemsImplement = true - completer = impl.Complete - } else if val.CanAddr() { - isRepeatable = true - if impl, ok := val.Addr().Interface().(Completer); ok && impl != nil { - itemsImplement = true - completer = impl.Complete - } - } - } - - return completer, isRepeatable, itemsImplement -} - -// taggedCompletions builds a list of completion actions with struct tag specs. -func taggedCompletions(tag tag.MultiTag) (comp.CompletionCallback, bool) { - compTag := tag.GetMany(completeTagName) - description, _ := tag.Get("description") - desc, _ := tag.Get("desc") - - if description == "" { - description = desc - } - - if len(compTag) == 0 { - return nil, false - } - - // We might have several tags, so several actions. - actions := make([]comp.Action, 0) - - // ---- Example spec ---- - // Args struct { - // File string complete:"files,xml" - // Remote string complete:"files" - // Delete []string complete:"FilterExt,json,go,yaml" - // Local []string complete:"FilterDirs,/home/user" - // } - for _, tag := range compTag { - if tag == "" || strings.TrimSpace(tag) == "" { - continue - } - - items := strings.SplitAfterN(tag, ",", completeTagMaxParts) - - name, value := strings.TrimSuffix(items[0], ","), "" - - if len(items) > 1 { - value = strings.TrimSuffix(items[1], ",") - } - - // build the completion action - tagAction := getCompletionAction(name, value, description) - actions = append(actions, tagAction) - } - - // To be called when completion is needed, merging everything. - callback := func(ctx comp.Context) comp.Action { - return comp.Batch(actions...).ToA() - } - - return callback, true -} - -func hintCompletions(tag tag.MultiTag) (comp.CompletionCallback, bool) { - description, _ := tag.Get("description") - desc, _ := tag.Get("desc") - - if description == "" { - description = desc - } - - if description == "" { - return nil, false - } - - callback := func(comp.Context) comp.Action { - return comp.Action{}.Usage(desc) - } - - return callback, true -} - -// choiceCompletions builds completions from field tag choices. -func choiceCompletions(tag tag.MultiTag, val reflect.Value) comp.CompletionCallback { - choices := tag.GetMany("choice") - - if len(choices) == 0 { - return nil - } - - var allChoices []string - - flagIsList := val.Kind() == reflect.Slice || val.Kind() == reflect.Map - - if flagIsList { - for _, choice := range choices { - allChoices = append(allChoices, strings.Split(choice, " ")...) - } - } else { - allChoices = choices - } - - callback := func(ctx comp.Context) comp.Action { - return comp.ActionValues(allChoices...) - } - - return callback -} diff --git a/gen/completions/completion_test.go b/gen/completions/completion_test.go deleted file mode 100644 index 2b8bc44..0000000 --- a/gen/completions/completion_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package completions - -import ( - "testing" - - "github.com/rsteube/carapace" - "github.com/spf13/cobra" -) - -// TestCompletions just calls the carapace engine test routine -// on a generated struct with a few tagged completion directives. -func TestCompletions(t *testing.T) { - t.Parallel() - - argsCmd := struct { - Args struct { - Files []string `description:"A list of hosts with minimum and maximum requirements" complete:"Files"` - JsonConfig string `description:"A single, required remaining argument" required:"1" complete:"FilterExt,json"` - } `positional-args:"yes" required:"yes"` - }{} - - // Generate the completions, without looking - // the resulting carapace object: the carapace - // library takes care of verifying its output. - rootCmd := cobra.Command{} - Generate(&rootCmd, argsCmd, nil) - - carapace.Test(t) -} diff --git a/gen/completions/group.go b/gen/completions/group.go deleted file mode 100644 index 240ade5..0000000 --- a/gen/completions/group.go +++ /dev/null @@ -1,187 +0,0 @@ -package completions - -import ( - "errors" - "fmt" - "reflect" - - "github.com/reeflective/flags" - genflags "github.com/reeflective/flags/gen/flags" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - comp "github.com/rsteube/carapace" - "github.com/spf13/cobra" -) - -// errShortNameTooLong indicates that a short flag name was specified, -// longer than one character. -var errShortNameTooLong = errors.New("short names can only be 1 character long") - -// flagSetComps is an alias for storing per-flag completions. -type flagSetComps map[string]comp.Action - -// flagsGroup finds if a field is marked as a subgroup of options, and if yes, scans it recursively. -func groupComps(comps *comp.Carapace, cmd *cobra.Command, val reflect.Value, fld *reflect.StructField) (bool, error) { - mtag, none, err := tag.GetFieldTag(*fld) - if none || err != nil { - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - // If not tagged as group, skip it. - if _, isGroup := mtag.Get("group"); !isGroup { - return false, nil - } - - // description, _ := mtag.Get("description") - - var ptrval reflect.Value - - if val.Kind() == reflect.Ptr { - ptrval = val - - if ptrval.IsNil() { - ptrval.Set(reflect.New(ptrval.Type())) - } - } else { - ptrval = val.Addr() - } - - // We are either waiting for: - // A group of options ("group" is the legacy name) - optionsGroup, isSet := mtag.Get("group") - - // Parse the options for completions - if isSet && optionsGroup != "" { - err := addFlagComps(comps, mtag, ptrval.Interface()) - - return true, err - } - - // Or a group of commands and/or options, which we also scan, - // as each command will produce a new carapace, a new set of - // flag/positional completers, etc - _, isSet = mtag.Get("commands") - - // Parse for commands - if isSet { - defaultFlagComps := flagSetComps{} - - scannerCommand := completionScanner(cmd, comps, &defaultFlagComps) - err := scan.Type(ptrval.Interface(), scannerCommand) - - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - return true, nil -} - -// addFlagComps scans a struct (potentially nested), for a set of flags, and without -// binding them to the command, parses them for any completions specified/implemented. -func addFlagComps(comps *comp.Carapace, mtag tag.MultiTag, data interface{}) error { - var flagOpts []flags.OptFunc - - // New change, in order to easily propagate parent namespaces - // in heavily/specially nested option groups at bind time. - delim, _ := mtag.Get("namespace-delimiter") - - namespace, _ := mtag.Get("namespace") - if namespace != "" { - flagOpts = append(flagOpts, flags.Prefix(namespace+delim)) - } - - envNamespace, _ := mtag.Get("env-namespace") - if envNamespace != "" { - flagOpts = append(flagOpts, flags.EnvPrefix(envNamespace)) - } - - // All completions for this flag set only. - // The handler will append to the completions map as each flag is parsed - flagCompletions := flagSetComps{} - compScanner := flagCompsScanner(&flagCompletions) - flagOpts = append(flagOpts, flags.FlagHandler(compScanner)) - - // Parse the group into a flag set, but don't keep them, - // we're just interested in running the handler on their values. - _, err := genflags.ParseFlags(data, flagOpts...) - if err != nil { - return fmt.Errorf("%w: %s", flags.ErrParse, err.Error()) - } - - // If we are done parsing the flags without error and we have - // some completers found on them (implemented or tagged), bind them. - if len(flagCompletions) > 0 { - comps.FlagCompletion(comp.ActionMap(flagCompletions)) - } - - return nil -} - -// flagScan builds a small struct field handler so that we can scan -// it as an option and add it to our current command flags. -func flagComps(comps *comp.Carapace, flagComps *flagSetComps) scan.Handler { - flagScanner := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { - compScanner := flagCompsScanner(flagComps) - - // Parse a single field, returning one or more generic Flags - _, found, err := flags.ParseField(val, *sfield, flags.FlagHandler(compScanner)) - if err != nil { - return found, err - } - - // If we are done parsing the flags without error and we have - // some completers found on them (implemented or tagged), bind them. - if len(*flagComps) > 0 { - comps.FlagCompletion(comp.ActionMap(*flagComps)) - } - - if !found { - return false, nil - } - - return true, nil - } - - return flagScanner -} - -// flagCompsScanner builds a scanner that will register some completers for an option flag. -func flagCompsScanner(actions *flagSetComps) flags.FlagFunc { - handler := func(flag string, tag tag.MultiTag, val reflect.Value) error { - // First get any completer implementation, and identifies if - // type is an array, and if yes, where the completer is implemented. - completer, isRepeatable, itemsImplement := typeCompleter(val) - - // Check if the flag has some choices: if yes, we simply overwrite - // the completer implementation with a builtin one. - if choices := choiceCompletions(tag, val); choices != nil { - completer = choices - itemsImplement = true - } - - // Or we might find struct tags specifying some completions, - // in which case we also override the completer implementation - if tagged, found := taggedCompletions(tag); found { - completer = tagged - itemsImplement = true - } - - // We are done if no completer is found whatsoever. - if completer == nil { - return nil - } - - action := comp.ActionCallback(completer) - - // Then, and irrespectively of where the completer comes from, - // we adapt it considering the kind of type we're dealing with. - if isRepeatable && itemsImplement { - action = action.UniqueList(",") - } - - (*actions)[flag] = action - - return nil - } - - return handler -} diff --git a/gen/completions/positional.go b/gen/completions/positional.go deleted file mode 100644 index 4f5b42f..0000000 --- a/gen/completions/positional.go +++ /dev/null @@ -1,225 +0,0 @@ -package completions - -import ( - "fmt" - "reflect" - - "github.com/reeflective/flags/internal/positional" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - comp "github.com/rsteube/carapace" -) - -// positionals finds a struct tagged as containing positional arguments and scans them. -func positionals(comps *comp.Carapace, tag tag.MultiTag, val reflect.Value) (bool, error) { - // We need the struct to be marked as such - if pargs, _ := tag.Get("positional-args"); len(pargs) == 0 { - return false, nil - } - - // Scan all the fields on the struct and build the list of arguments - // with their own requirements, and references to their values. - // Return a type storing all the fields, references, and with the - // tools to manage, parse words and raise any errors related - args, err := positional.ScanArgs(val, tag) - if err != nil || args == nil { - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - // Find all completer implementations, or - // build ones based on struct tag specs. - // Put them in a cache of completion callbacks that is accessed - // by all positional arguments in order to use their completions. - completionCache := getCompleters(args, comps) - - // Make a custom function for consuming the command words, - args = positional.WithWordConsumer(args, consumeWith(completionCache)) - - // Once we a have a list of positionals, completers for each, - // and the number of arguments required, we can build a single - // completion handler, similar to our ValidArgs function handler - handler := func(ctx comp.Context) comp.Action { - // Simply call the positionals with our command words. - // This function will call each positional with a copy - // of the list. - // Arguments that don't have enough words to work with - // will be ignored. The function blocks until all slots - // are done processing their word list. - args.ParseConcurrent(ctx.Args) - - // We are done processing some/all of the positional words. - // The cache contains all the completions it needs, so we - // just unload them into one action to be returned - return completionCache.flush(ctx) - } - - // And bind this positional completer to our command - comps.PositionalAnyCompletion(comp.ActionCallback(handler)) - - return true, nil -} - -// getCompleters populates the completers for each positional argument in -// a list of them, through either implemented methods or struct tag specs. -func getCompleters(args *positional.Args, comps *comp.Carapace) *compCache { - // The cache stores all completer functions, to be used later. - cache := newCompletionCache() - - for _, arg := range args.Positionals() { - // By default, use the argument description as hint, in case there is - // no completion directive or implementation. - if completer, _ := hintCompletions(arg.Tag); completer != nil { - cache.add(arg.Index, completer) - } - - // Make parser function, get completer implementations, how many arguments, etc. - if completer, _, _ := typeCompleter(arg.Value); completer != nil { - cache.add(arg.Index, completer) - } - - // But struct tags have precedence, so here should take place - // most of the work, since it's quite easy to specify powerful completions. - if completer, found := taggedCompletions(arg.Tag); found { - cache.add(arg.Index, completer) - } - } - - return cache -} - -// consumeWith returns a custom handler which will be called on each positional -// argument, so that it can consume one/more of the positional words and add -// completions to the cache if needed. -func consumeWith(comps *compCache) positional.WordConsumer { - handler := func(args *positional.Args, arg *positional.Arg, _ int) error { - // First, pop all the words we KNOW we're not - // interested in, which is the number of minimum - // required words BEFORE us. - for i := 0; i < arg.StartMin; i++ { - args.Pop() - } - - // Always complete if we have no maximum - if arg.Maximum == -1 { - return completeOrIgnore(arg, comps, 0) - } - - // If there is a drift between the accumulated words and - // the maximum requirements of the PREVIOUS positionals, - // we use this drift in order not to pop the words as soon - // as we would otherwise do. Useful when more than one positional - // arguments have a minimum-maximum range of allowed arguments. - drift := arg.StartMax - arg.StartMin - actuallyParsed := 0 - - // As long as we've got a word, and nothing told us to quit. - for !args.Empty() { - if drift == 0 { - // That we either consider to be parsed by - // our current positional slot, we pop an - // argument that should be parsed by us. - actuallyParsed++ - } else if drift > 0 { - // Or to be left to one of the preceding - // positionals, which have still some slots - // available for arguments. - drift-- - } - - // Pop the next positional word, as if we would - // parse/convert it into our slot at exec time. - args.Pop() - - // If we have reached the maximum number - // of args we accept, don't complete - if arg.Maximum == actuallyParsed { - break - } - } - - // This function makes the final call on whether to - // complete for this positional or not. - return completeOrIgnore(arg, comps, actuallyParsed) - } - - return handler -} - -// completeOrIgnore finally takes the decision of completing this positional or not. -func completeOrIgnore(arg *positional.Arg, comps *compCache, actuallyParsed int) error { - mustComplete := false - - switch { - case arg.Maximum == -1: - // Always complete if we have no maximum - mustComplete = true - case actuallyParsed < arg.Minimum: - // If we are still lacking some required words, - // but we have exhausted the available ones. - mustComplete = true - case actuallyParsed < arg.Maximum: - // Or we have the minimum required, but we could - // take more. - mustComplete = true - } - - // If something has said we must, cache the comps. - if mustComplete { - comps.useCompleter(arg.Index) - } - - return nil -} - -// a list used to store completion callbacks produced by our -// positional arguments' slots at some point in the process. -type compCache struct { - // All positionals have given their completers - // before running, so we can access them - completers *map[int]comp.CompletionCallback - // And the cache is the list of completion callbacks - // we will actually use when exiting the full process. - cache []comp.CompletionCallback -} - -func newCompletionCache() *compCache { - return &compCache{ - completers: &map[int]comp.CompletionCallback{}, - } -} - -func (c *compCache) add(index int, cb comp.CompletionCallback) { - (*c.completers)[index] = cb -} - -func (c *compCache) useCompleter(index int) { - completer, found := (*c.completers)[index] - if found { - c.cache = append(c.cache, completer) - } -} - -// flush returns all the completions cached by our positional arguments, -// so we invoke each of them with the context so that they can perform -// so filtering tasks if they need to. -func (c *compCache) flush(ctx comp.Context) comp.Action { - actions := make([]comp.Action, 0) - - // fixed-max positional completers - for _, cb := range c.cache { - actions = append(actions, comp.ActionCallback(cb)) - } - - // Each of the completers should invoke with - // the context so that they can filter out - // the candidates that are already present. - processed := make([]comp.Action, 0) - - for _, completion := range actions { - completion = completion.Invoke(ctx).Filter(ctx.Args).ToA() - processed = append(processed, completion) - } - - // Let carapace merge all of our callbacks. - return comp.Batch(processed...).ToA() -} diff --git a/gen/flags/command.go b/gen/flags/command.go deleted file mode 100644 index 754de02..0000000 --- a/gen/flags/command.go +++ /dev/null @@ -1,277 +0,0 @@ -package flags - -import ( - "fmt" - "os" - "reflect" - "strings" - - "github.com/reeflective/flags" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - "github.com/spf13/cobra" -) - -// Generate returns a root cobra Command to be used directly as an entry-point. -// The data interface parameter can be nil, or arbitrarily: -// - A simple group of options to bind at the local, root level -// - A struct containing substructs for postional parameters, and other with options. -func Generate(data interface{}, opts ...flags.OptFunc) *cobra.Command { - cmd := &cobra.Command{ - Use: os.Args[0], - Annotations: map[string]string{}, - TraverseChildren: true, - } - - // Scan the struct and bind all commands to this root. - generate(cmd, data, opts...) - - return cmd -} - -// generate wraps all main steps' invocations, to be reused in various cases. -func generate(cmd *cobra.Command, data interface{}, opts ...flags.OptFunc) { - // Make a scan handler that will run various scans on all - // the struct fields, with arbitrary levels of nesting. - scanner := scanRoot(cmd, nil, opts) - - // And scan the struct recursively, for arg/option groups and subcommands - if err := scan.Type(data, scanner); err != nil { - fmt.Fprintln(os.Stderr, "Error:", err.Error()) - os.Exit(1) - } - - // Subcommands, optional or not - if cmd.HasSubCommands() { - cmd.RunE = unknownSubcommandAction - } else { - setRuns(cmd, data) - } -} - -// scan is in charge of building a recursive scanner, working on a given struct field at a time, -// checking for arguments, subcommands and option groups. It also checks if additional handlers -// should be applied on the given struct field, such as when our application can run itself as -// a module. -func scanRoot(cmd *cobra.Command, group *cobra.Group, opts []flags.OptFunc) scan.Handler { - handler := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { - // Parse the tag or die tryin. We should find one, or we're not interested. - mtag, _, err := tag.GetFieldTag(*sfield) - if err != nil { - return true, fmt.Errorf("%w: %s", tag.ErrTag, err.Error()) - } - - // If the field is marked as -one or more- positional arguments, we - // return either on a successful scan of them, or with an error doing so. - if found, err := positionals(cmd, mtag, val, opts); found || err != nil { - return found, err - } - - // Else, if the field is marked as a subcommand, we either return on - // a successful scan of the subcommand, or with an error doing so. - if found, err := command(cmd, group, mtag, val, opts); found || err != nil { - return found, err - } - - // Else, if the field is a struct group of options - if found, err := flagsGroup(cmd, val, sfield, opts); found || err != nil { - return found, err - } - - // Else, try scanning the field as a simple option flag - return flagScan(cmd, opts)(val, sfield) - } - - return handler -} - -// command finds if a field is marked as a subcommand, and if yes, scans it. We have different cases: -// - When our application can run its commands as modules, we must build appropriate handlers. -func command(cmd *cobra.Command, grp *cobra.Group, tag tag.MultiTag, val reflect.Value, opts []flags.OptFunc) (bool, error) { - // Parse the command name on struct tag... - name, _ := tag.Get("command") - if len(name) == 0 { - return false, nil - } - - // Initialize the field if nil - data := initialize(val) - - // Always populate the maximum amount of information - // in the new subcommand, so that when it scans recursively, - // we can have a more granular context. - subc := newCommand(name, tag, grp) - - // Set the group to which the subcommand belongs - tagged, _ := tag.Get("group") - setGroup(cmd, subc, grp, tagged) - - // Scan the struct recursively, for arg/option groups and subcommands - scanner := scanRoot(subc, grp, opts) - if err := scan.Type(data, scanner); err != nil { - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - // Bind the various pre/run/post implementations of our command. - if _, isSet := tag.Get("subcommands-optional"); !isSet && subc.HasSubCommands() { - subc.RunE = unknownSubcommandAction - } else { - data := initialize(val) - setRuns(subc, data) - } - - // And bind this subcommand back to us - cmd.AddCommand(subc) - - return true, nil -} - -// builds a quick command template based on what has been specified through tags, and in context. -func newCommand(name string, mtag tag.MultiTag, parent *cobra.Group) *cobra.Command { - subc := &cobra.Command{ - Use: name, - Annotations: map[string]string{}, - } - - if desc, _ := mtag.Get("description"); desc != "" { - subc.Short = desc - } else if desc, _ := mtag.Get("desc"); desc != "" { - subc.Short = desc - } - - subc.Long, _ = mtag.Get("long-description") - subc.Aliases = mtag.GetMany("alias") - _, subc.Hidden = mtag.Get("hidden") - - return subc -} - -func setGroup(parent, subc *cobra.Command, parentGroup *cobra.Group, tagged string) { - var group *cobra.Group - - // The group tag on the command has priority - if tagged != "" { - for _, grp := range parent.Groups() { - if grp.ID == tagged { - group = grp - } - } - - if group == nil { - group = &cobra.Group{ID: tagged, Title: tagged} - parent.AddGroup(group) - } - } else if parentGroup != nil { - group = parentGroup - } - - // Use the group we settled on - if group != nil { - subc.GroupID = group.ID - } -} - -func unknownSubcommandAction(cmd *cobra.Command, args []string) error { - if len(args) == 0 { - return cmd.Help() - } - - err := fmt.Sprintf("unknown subcommand %q for %q", args[0], cmd.Name()) - - if suggestions := cmd.SuggestionsFor(args[0]); len(suggestions) > 0 { - err += "\n\nDid you mean this?\n" - for _, s := range suggestions { - err += fmt.Sprintf("\t%v\n", s) - } - - err = strings.TrimSuffix(err, "\n") - } - - return fmt.Errorf(err) -} - -func setRuns(cmd *cobra.Command, data interface{}) { - // No implementation means that this command - // requires subcommands by default. - if data == nil { - return - } - - // If our command hasn't any positional argument handler, - // we must make one to automatically put any of them in Execute - if cmd.Args == nil { - cmd.Args = func(cmd *cobra.Command, args []string) error { - setRemainingArgs(cmd, args) - - return nil - } - } - - // Pre-runners - if runner, ok := data.(flags.PreRunner); ok && runner != nil { - cmd.PreRun = func(c *cobra.Command, _ []string) { - retargs := getRemainingArgs(c) - runner.PreRun(retargs) - } - } - if runner, ok := data.(flags.PreRunnerE); ok && runner != nil { - cmd.PreRunE = func(c *cobra.Command, _ []string) error { - retargs := getRemainingArgs(c) - return runner.PreRunE(retargs) - } - } - - // Runners - if commander, ok := data.(flags.Commander); ok && commander != nil { - cmd.RunE = func(c *cobra.Command, _ []string) error { - retargs := getRemainingArgs(c) - cmd.SetArgs(retargs) - return commander.Execute(retargs) - } - } else if runner, ok := data.(flags.RunnerE); ok && runner != nil { - cmd.RunE = func(c *cobra.Command, _ []string) error { - retargs := getRemainingArgs(c) - return runner.RunE(retargs) - } - } - - if runner, ok := data.(flags.Runner); ok && runner != nil { - cmd.Run = func(c *cobra.Command, _ []string) { - retargs := getRemainingArgs(c) - runner.Run(retargs) - } - } - - // Post-runners - if runner, ok := data.(flags.PostRunner); ok && runner != nil { - cmd.PreRun = func(c *cobra.Command, _ []string) { - retargs := getRemainingArgs(c) - runner.PostRun(retargs) - } - } - if runner, ok := data.(flags.PostRunnerE); ok && runner != nil { - cmd.PreRunE = func(c *cobra.Command, _ []string) error { - retargs := getRemainingArgs(c) - return runner.PostRunE(retargs) - } - } -} - -func initialize(val reflect.Value) interface{} { - // Initialize if needed - var ptrval reflect.Value - - // We just want to get interface, even if nil - if val.Kind() == reflect.Ptr { - ptrval = val - } else { - ptrval = val.Addr() - } - - // Once we're sure it's a command, initialize the field if needed. - if ptrval.IsNil() { - ptrval.Set(reflect.New(ptrval.Type().Elem())) - } - - return ptrval.Interface() -} diff --git a/gen/flags/flag.go b/gen/flags/flag.go deleted file mode 100644 index 52fa114..0000000 --- a/gen/flags/flag.go +++ /dev/null @@ -1,95 +0,0 @@ -package flags - -import ( - "fmt" - "os" - "strings" - - "github.com/reeflective/flags" - "github.com/spf13/pflag" -) - -// flagSet describes interface, -// that's implemented by pflag library and required by flags. -type flagSet interface { - VarPF(value pflag.Value, name, shorthand, usage string) *pflag.Flag -} - -var _ flagSet = (*pflag.FlagSet)(nil) - -// GenerateTo takes a list of sflag.Flag, -// that are parsed from some config structure, and put it to dst. -func generateTo(src []*flags.Flag, dst flagSet) { - for _, srcFlag := range src { - flag := dst.VarPF(srcFlag.Value, srcFlag.Name, srcFlag.Short, srcFlag.Usage) - - // Annotations used for things like completions - flag.Annotations = map[string][]string{} - - var annots []string - - flag.NoOptDefVal = strings.Join(srcFlag.OptionalValue, " ") - - if boolFlag, casted := srcFlag.Value.(flags.BoolFlag); casted && boolFlag.IsBoolFlag() { - // pflag uses -1 in this case, - // we will use the same behaviour as in flag library - flag.NoOptDefVal = "true" - } else if srcFlag.Required { - // Only non-boolean flags can be required. - annots = append(annots, "required") - } - - flag.Hidden = srcFlag.Hidden - - if srcFlag.Deprecated { - // we use Usage as Deprecated message for a pflag - flag.Deprecated = srcFlag.Usage - if flag.Deprecated == "" { - flag.Deprecated = "Deprecated" - } - } - - // Register annotations to be used by clients and completers - flag.Annotations["flags"] = annots - } -} - -// Parse parses cfg, that is a pointer to some structure, puts it to the new -// pflag.FlagSet and returns it. -// -// This is generally not needed if you intend to generate a directly working CLI: -// This function is used for generating things like completions for flags, etc. -func ParseFlags(cfg interface{}, optFuncs ...flags.OptFunc) (*pflag.FlagSet, error) { - flagSet := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) - - err := parseTo(cfg, flagSet, optFuncs...) - if err != nil { - return nil, err - } - - return flagSet, nil -} - -// parseTo parses cfg, that is a pointer to some structure, -// and puts it to dst. -func parseTo(cfg interface{}, dst flagSet, optFuncs ...flags.OptFunc) error { - flagSet, err := flags.ParseStruct(cfg, optFuncs...) - if err != nil { - return fmt.Errorf("%w: %s", flags.ErrParse, err.Error()) - } - - generateTo(flagSet, dst) - - return nil -} - -// ParseToDef parses cfg, that is a pointer to some structure and -// puts it to the default pflag.CommandLine. -func parseToDef(cfg interface{}, optFuncs ...flags.OptFunc) error { - err := parseTo(cfg, pflag.CommandLine, optFuncs...) - if err != nil { - return err - } - - return nil -} diff --git a/gen/flags/flag_test.go b/gen/flags/flag_test.go deleted file mode 100644 index dca9001..0000000 --- a/gen/flags/flag_test.go +++ /dev/null @@ -1,383 +0,0 @@ -package flags - -import ( - "errors" - "fmt" - "io" - "net" - "os" - "testing" - "time" - - "github.com/reeflective/flags" - "github.com/spf13/pflag" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -// -// Flag structs & test helpers -------------------------------------------------------- // -// - -// testConfig stores all data needed for a single test. -// This is different from flagsConfig, which is the CLI -// structure to be parsed and used. -type testConfig struct { - cfg interface{} // Initial state of the struct before parsing arguments - expCfg interface{} // Expected state of the struct after parsing arguments. - args []string // Command-line args - expErr1 error // flags Parse error - expErr2 error // pflag Parse error -} - -// flagsConfig is an example structure to be used to produce CLI flags. -type flagsConfig struct { - StringValue1 string - StringValue2 string `flag:"string-value-two s"` - - CounterValue1 flags.Counter - - StringSliceValue1 []string - DeprecatedValue1 string `flag:",deprecated" desc:"DEP_MESSAGE"` -} - -// allPflags contains all possible types to be parsed as pflags. -type allPflags struct { - IntValue int - Int8Value int8 - Int32Value int32 - Int64Value int64 - - UintValue uint - Uint8Value uint8 - Uint16Value uint16 - Uint32Value uint32 - Uint64Value uint64 - - Float32Value float32 - Float64Value float64 - - BoolValue bool - StringValue string - DurationValue time.Duration - CountValue flags.Counter - - IPValue net.IP - IPNetValue net.IPNet - - StringSliceValue []string - IntSliceValue []int -} - -// run condenses all CLI/flags parsing steps, and compares -// all structs/errors against their expected state. -func run(t *testing.T, test *testConfig) { - t.Helper() - - // We must parse all struct fields regardless of them being tagged. - parseOptions := flags.ParseAll() - - flagSet, err := ParseFlags(test.cfg, parseOptions) - - if test.expErr1 != nil { - require.Error(t, err) - require.Equal(t, test.expErr1, err) - } else { - require.NoError(t, err) - } - - if err != nil { - return - } - - flagSet.Init("pflagTest", pflag.ContinueOnError) - flagSet.SetOutput(io.Discard) - - err = flagSet.Parse(test.args) - if test.expErr2 != nil { - require.Error(t, err) - require.Equal(t, test.expErr2, err) - } else { - require.NoError(t, err) - } - - if err != nil { - return - } - - assert.Equal(t, test.expCfg, test.cfg) -} - -// -// Tests ---------------------------------------------------------------------------- // -// - -// TestFlagsBase tests for a simple (old sflags) struct to be parsed. -func TestFlagsBase(t *testing.T) { - t.Parallel() - - // Test setup - test := &testConfig{ - cfg: &flagsConfig{ - StringValue1: "string_value1_value", - StringValue2: "string_value2_value", - - CounterValue1: 1, - - StringSliceValue1: []string{"one", "two"}, - }, - expCfg: &flagsConfig{ - StringValue1: "string_value1_value2", - StringValue2: "string_value2_value2", - - CounterValue1: 3, - - StringSliceValue1: []string{ - "one2", "two2", "three", "4", - }, - }, - args: []string{ - "--string-value1", "string_value1_value2", - "--string-value-two", "string_value2_value2", - "--counter-value1", "--counter-value1", - "--string-slice-value1", "one2", - "--string-slice-value1", "two2", - "--string-slice-value1", "three,4", - }, - } - - run(t, test) -} - -// TestParseNoArgs tests that no arguments -// passed as command-line invocation works. -func TestParseNoArgs(t *testing.T) { - t.Parallel() - - test := &testConfig{ - cfg: &flagsConfig{ - StringValue1: "string_value1_value", - StringValue2: "", - }, - expCfg: &flagsConfig{ - StringValue1: "string_value1_value", - StringValue2: "", - }, - args: []string{}, - } - - run(t, test) -} - -// TestParseShortOptions checks that flags -// invoked as short options correctly parse. -func TestParseShortOptions(t *testing.T) { - t.Parallel() - - test := &testConfig{ - cfg: &flagsConfig{ - StringValue2: "string_value2_value", - }, - expCfg: &flagsConfig{ - StringValue2: "string_value2_value2", - }, - args: []string{ - "-s=string_value2_value2", - }, - } - - run(t, test) -} - -// TestParseBadOptions checks that flag invoked while not -// existing in the struct will correctly error out. -func TestParseBadOptions(t *testing.T) { - t.Parallel() - - test := &testConfig{ - cfg: &flagsConfig{ - StringValue1: "string_value1_value", - }, - args: []string{ - "--bad-value=string_value1_value2", - }, - expErr2: errors.New("unknown flag: --bad-value"), - } - - run(t, test) -} - -// TestParseNoDefaultValues checks that flags that do NOT specify -// their default values will leave their current state untouched. -func TestParseNoDefaultValues(t *testing.T) { - t.Parallel() - - test := &testConfig{ - cfg: &flagsConfig{}, - expCfg: &flagsConfig{ - StringValue1: "string_value1_value2", - StringValue2: "string_value2_value2", - - CounterValue1: 3, - }, - args: []string{ - "--string-value1", "string_value1_value2", - "--string-value-two", "string_value2_value2", - "--counter-value1=2", "--counter-value1", - }, - } - - run(t, test) -} - -// TestParseBadConfig checks that unsupported types are correctly rejected. -func TestParseBadConfig(t *testing.T) { - t.Parallel() - - pointerErr := fmt.Errorf("%w: %s", flags.ErrParse, flags.ErrNotPointerToStruct.Error()) - test := &testConfig{ - cfg: "bad config", - expErr1: pointerErr, - } - - run(t, test) -} - -func TestParseToDef(t *testing.T) { - t.Parallel() - - oldCommandLine := pflag.CommandLine - - defer func() { - pflag.CommandLine = oldCommandLine - }() - - cfg := &flagsConfig{StringValue1: "value1"} - pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ContinueOnError) - - parseOptions := flags.ParseAll() - - err := parseToDef(cfg, parseOptions) - assert.NoError(t, err) - - err = pflag.CommandLine.Parse([]string{"--string-value1", "value2"}) - assert.NoError(t, err) - assert.Equal(t, "value2", cfg.StringValue1) - - err = parseToDef("bad string", parseOptions) - assert.Error(t, err) -} - -// Test that pflag getter functions like GetInt work as expected. -func TestPFlagGetters(t *testing.T) { - _, ipNet, err := net.ParseCIDR("127.0.0.1/24") - require.NoError(t, err) - - cfg := &allPflags{ - IntValue: 10, - Int8Value: 11, - Int32Value: 12, - Int64Value: 13, - - UintValue: 14, - Uint8Value: 15, - Uint16Value: 16, - Uint32Value: 17, - Uint64Value: 18, - - Float32Value: 19.1, - Float64Value: 20.1, - - BoolValue: true, - StringValue: "stringValue", - DurationValue: time.Second * 10, - CountValue: 30, - - IPValue: net.ParseIP("127.0.0.1"), - IPNetValue: *ipNet, - - StringSliceValue: []string{"one", "two"}, - IntSliceValue: []int{10, 20}, - } - - parseOptions := flags.ParseAll() - - flagSet, err := ParseFlags(cfg, parseOptions) - require.NoError(t, err) - - intValue, err := flagSet.GetInt("int-value") - assert.NoError(t, err) - assert.Equal(t, 10, intValue) - - int8Value, err := flagSet.GetInt8("int8-value") - assert.NoError(t, err) - assert.Equal(t, int8(11), int8Value) - - int32Value, err := flagSet.GetInt32("int32-value") - assert.NoError(t, err) - assert.Equal(t, int32(12), int32Value) - - int64Value, err := flagSet.GetInt64("int64-value") - assert.NoError(t, err) - assert.Equal(t, int64(13), int64Value) - - uintValue, err := flagSet.GetUint("uint-value") - assert.NoError(t, err) - assert.Equal(t, uint(14), uintValue) - - uint8Value, err := flagSet.GetUint8("uint8-value") - assert.NoError(t, err) - assert.Equal(t, uint8(15), uint8Value) - - uint16Value, err := flagSet.GetUint16("uint16-value") - assert.NoError(t, err) - assert.Equal(t, uint16(16), uint16Value) - - uint32Value, err := flagSet.GetUint32("uint32-value") - assert.NoError(t, err) - assert.Equal(t, uint32(17), uint32Value) - - uint64Value, err := flagSet.GetUint64("uint64-value") - assert.NoError(t, err) - assert.Equal(t, uint64(18), uint64Value) - - float32Value, err := flagSet.GetFloat32("float32-value") - assert.NoError(t, err) - assert.Equal(t, float32(19.1), float32Value) - - float64Value, err := flagSet.GetFloat64("float64-value") - assert.NoError(t, err) - assert.Equal(t, float64(20.1), float64Value) - - boolValue, err := flagSet.GetBool("bool-value") - assert.NoError(t, err) - assert.Equal(t, true, boolValue) - - countValue, err := flagSet.GetCount("count-value") - assert.NoError(t, err) - assert.Equal(t, 30, countValue) - - durationValue, err := flagSet.GetDuration("duration-value") - assert.NoError(t, err) - assert.Equal(t, time.Second*10, durationValue) - - stringValue, err := flagSet.GetString("string-value") - assert.NoError(t, err) - assert.Equal(t, "stringValue", stringValue) - - ipValue, err := flagSet.GetIP("ip-value") - assert.NoError(t, err) - assert.Equal(t, net.ParseIP("127.0.0.1"), ipValue) - - ipNetValue, err := flagSet.GetIPNet("ip-net-value") - assert.NoError(t, err) - assert.Equal(t, cfg.IPNetValue, ipNetValue) - - stringSliceValue, err := flagSet.GetStringSlice("string-slice-value") - assert.NoError(t, err) - assert.Equal(t, []string{"one", "two"}, stringSliceValue) - - intSliceValue, err := flagSet.GetIntSlice("int-slice-value") - assert.NoError(t, err) - assert.Equal(t, []int{10, 20}, intSliceValue) -} diff --git a/gen/flags/group.go b/gen/flags/group.go deleted file mode 100644 index 50a888f..0000000 --- a/gen/flags/group.go +++ /dev/null @@ -1,131 +0,0 @@ -package flags - -import ( - "fmt" - "reflect" - - "github.com/reeflective/flags" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - "github.com/spf13/cobra" -) - -// flagScan builds a small struct field handler so that we can scan -// it as an option and add it to our current command flags. -func flagScan(cmd *cobra.Command, opts []flags.OptFunc) scan.Handler { - flagScanner := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { - // Parse a single field, returning one or more generic Flags - flagSet, found, err := flags.ParseField(val, *sfield, opts...) - if err != nil { - return found, err - } - - if !found { - return false, nil - } - - // Put these flags into the command's flagset. - generateTo(flagSet, cmd.Flags()) - - return true, nil - } - - return flagScanner -} - -// flagsGroup finds if a field is marked as a subgroup of options, and if yes, scans it recursively. -func flagsGroup(cmd *cobra.Command, val reflect.Value, field *reflect.StructField, opts []flags.OptFunc) (bool, error) { - mtag, skip, err := tag.GetFieldTag(*field) - if err != nil { - return true, fmt.Errorf("%w: %s", flags.ErrParse, err.Error()) - } else if skip { - return false, nil - } - - legacyGroup, legacyIsSet := mtag.Get("group") - commandGroup, commandsIsSet := mtag.Get("commands") - - if !legacyIsSet && !commandsIsSet { - return false, nil - } - - // If we have to work on this struct, check pointers n stuff - var ptrval reflect.Value - - if val.Kind() == reflect.Ptr { - ptrval = val - if ptrval.IsNil() { - ptrval.Set(reflect.New(ptrval.Type().Elem())) - } - } else { - ptrval = val.Addr() - } - - // A group of options ("group" is the legacy name) - if legacyIsSet && legacyGroup != "" { - err := addFlagSet(cmd, mtag, ptrval.Interface(), opts) - - return true, err - } - - // Or a group of commands and options - if commandsIsSet { - var group *cobra.Group - if !isStringFalsy(commandGroup) { - group = &cobra.Group{ - Title: commandGroup, - ID: commandGroup, - } - cmd.AddGroup(group) - } - - // Parse for commands - scannerCommand := scanRoot(cmd, group, opts) - if err := scan.Type(ptrval.Interface(), scannerCommand); err != nil { - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - return true, nil - } - - // If we are here, we didn't find a command or a group. - return false, nil -} - -// addFlagSet scans a struct (potentially nested) for flag sets to bind to the command. -func addFlagSet(cmd *cobra.Command, mtag tag.MultiTag, data interface{}, opts []flags.OptFunc) error { - // New change, in order to easily propagate parent namespaces - // in heavily/specially nested option groups at bind time. - delim, _ := mtag.Get("namespace-delimiter") - - namespace, _ := mtag.Get("namespace") - if namespace != "" { - opts = append(opts, flags.Prefix(namespace+delim)) - } - - envNamespace, _ := mtag.Get("env-namespace") - if envNamespace != "" { - opts = append(opts, flags.EnvPrefix(envNamespace)) - } - - // Create a new set of flags in which we will put our options - flags, err := ParseFlags(data, opts...) - if err != nil { - return err - } - - flags.SetInterspersed(true) - - persistent, _ := mtag.Get("persistent") - if persistent != "" { - cmd.PersistentFlags().AddFlagSet(flags) - } else { - cmd.Flags().AddFlagSet(flags) - } - - return nil -} - -func isStringFalsy(s string) bool { - return s == "" || s == "false" || s == "no" || s == "0" -} diff --git a/gen/flags/positional.go b/gen/flags/positional.go deleted file mode 100644 index 82adb55..0000000 --- a/gen/flags/positional.go +++ /dev/null @@ -1,80 +0,0 @@ -package flags - -import ( - "fmt" - "reflect" - "strings" - - "github.com/reeflective/flags" - "github.com/reeflective/flags/internal/positional" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - "github.com/spf13/cobra" -) - -// positionals finds a struct tagged as containing positionals arguments and scans them. -func positionals(cmd *cobra.Command, stag tag.MultiTag, val reflect.Value, opts []flags.OptFunc) (bool, error) { - // We need the struct to be marked as such - if pargs, _ := stag.Get("positional-args"); len(pargs) == 0 { - return false, nil - } - - // If the generation options include a validator, use it on arguments - optFuncs := make([]scan.OptFunc, len(opts)) - for i, optFunc := range opts { - optFuncs[i] = scan.OptFunc(optFunc) - } - - // Scan all the fields on the struct and build the list of arguments - // with their own requirements, and references to their values. - // Return a type storing all the fields, references, and with the - // tools to manage, parse words and raise any errors related - positionals, err := positional.ScanArgs(val, stag, optFuncs...) - if err != nil || positionals == nil { - return true, fmt.Errorf("%w: %s", scan.ErrScan, err.Error()) - } - - // Finally, assemble all the parsers into our cobra Args function. - cmd.Args = func(cmd *cobra.Command, args []string) error { - // Apply the words on the all/some of the positional fields, - // returning any words that have not been parsed in fields, - // and an error if one of the positionals has failed. - retargs, err := positionals.Parse(args, cmd.ArgsLenAtDash()) - - // Once we have consumed the words we wanted, we update the - // command's return (non-consummed) arguments, to be passed - // later to the Execute(args []string) implementation. - defer setRemainingArgs(cmd, retargs) - - // Directly return the error, which might be non-nil. - return err - } - - return true, nil -} - -func setRemainingArgs(cmd *cobra.Command, retargs []string) { - if len(retargs) == 0 || retargs == nil || cmd == nil { - return - } - - if cmd.Annotations == nil { - cmd.Annotations = map[string]string{} - } - // Add these arguments in an annotation to be used - // in our Run implementation, where we pass just the - // unparsed positional arguments to the command Execute(args []string). - cmd.Annotations["flags"] = strings.Join(retargs, " ") -} - -func getRemainingArgs(cmd *cobra.Command) []string { - if cmd.Annotations == nil { - return nil - } - - if argString, found := cmd.Annotations["flags"]; found { - return strings.Split(argString, " ") - } - - return nil -} diff --git a/gen/flags/positional_test.go b/gen/flags/positional_test.go deleted file mode 100644 index eff9ed1..0000000 --- a/gen/flags/positional_test.go +++ /dev/null @@ -1,526 +0,0 @@ -package flags - -import ( - "errors" - // "os" - // "os/exec". - "strings" - "testing" - - "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" -) - -// Tests partially ported from github.com/jessevdk/go-flags/arg_test.go, -// either enhanced and simplified where needed. To these have been added -// a few ones, with more complex positional argument patterns/setups. - -// -// Tests ported from jessevdk/go-flags --------------------------------------- // -// - -// TestPositionalAllOptional is the most simple test for positional arguments, -// since none of them is required to have something. The result, however, should -// be identical to TestPositionalAllRequired. -func TestAllOptional(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Command int // 1 minimum - Filename string // 1 minimum - Rest []string // All others here - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"10", "arg_test.go", "a", "b"}) - cmd.Args(cmd, []string{"10", "arg_test.go", "a", "b"}) - err := cmd.Execute() - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal(10, opts.Positional.Command, "Expected opts.Positional.Command to match") - pt.Equal("arg_test.go", opts.Positional.Filename, "Expected opts.Positional.Filename to match") - pt.Equal([]string{"a", "b"}, opts.Positional.Rest, "Expected opts.Positional.Rest to match") -} - -// TestStructRequiredWithRestFail checks positionals without per-field tag minimum -// requirements specified, but with the struct having one. This makes all positional -// fields required with at least one word each, except the last it it's a slice. -func TestAllRequired(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Command int - Filename string - Rest []string - } `positional-args:"yes" required:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"10"}) - err := cmd.Args(cmd, []string{"10"}) - - pt := assert.New(t) - pt.ErrorContains(err, "required argument: `Filename` and `Rest (at least 1 argument)` were not provided") -} - -// TestRequiredRestUndefinedFail checks that fields marked with a non-numeric -// (and non-nil, or "not falsy"), will correctly error out. -func TestRequiredRestUndefinedFail(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"yes"` - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{}) - err := cmd.Args(cmd, []string{}) - - pt := assert.New(t) - pt.ErrorContains(err, - "`Rest (at least 1 argument)` was not provided") -} - -// TestRequiredRestUndefinedPass checks that fields marked with a non-numeric -// (and non-nil, or "not falsy"), will accept and parse only one argument word. -func TestRequiredRestUndefinedPass(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"yes"` - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"rest1"}) - err := cmd.Args(cmd, []string{"rest1"}) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal("rest1", opts.Positional.Rest[0], - "Expected opts.Positional.Rest[0] to match") -} - -// TestRequiredRestQuantityPass cheks that slice/map fields marked with a numeric -// quantity - and at the last position in the positionals struct - will correctly -// fail if they are not given the minimum words they want. -func TestRequiredRestQuantityFail(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"2"` - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"rest1"}) - err := cmd.Args(cmd, []string{"rest1"}) - - pt := assert.New(t) - pt.ErrorContains(err, - "`Rest (at least 2 arguments, but got only 1)` was not provided") -} - -// TestRequiredRestQuantityPass cheks that slice/map fields marked with a numeric -// quantity will accept and parse at minimum the specified number. -func TestRequiredRestQuantityPass(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"2"` - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"rest1", "rest2", "rest3"}) - err := cmd.Args(cmd, []string{"rest1", "rest2", "rest3"}) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal("rest1", opts.Positional.Rest[0]) - pt.Equal("rest2", opts.Positional.Rest[1]) - pt.Equal("rest3", opts.Positional.Rest[2]) -} - -// TestRequiredRestRangeFail checks that the last positional field -// will correctly error out if there are words left after they have -// consumed some, up to their maximum allowed. -func TestRequiredRestRangeFail(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"1-2"` - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"rest1", "rest2", "rest3"}) - err := cmd.Args(cmd, []string{"rest1", "rest2", "rest3"}) - - pt := assert.New(t) - pt.ErrorContains(err, - "`Rest (at most 2 arguments, but got 3)` was not provided") -} - -// TestRequiredRestRangeEmptyFail checks that an incorrectly specified 0-0 range -// will actually throw an error BEFORE executing the command, not AFTER and with -// using the rest words as lambda parameters passed to the command implementation. -// -// In essence this function is just a check that internal code will not -// misinterpret some tag values in relation to all the positionals, so -// an invalid 0-0 is a good test case candidate for this. -func TestRequiredRestRangeEmptyFail(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - Rest []string `required:"0-0"` - } `positional-args:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"some", "thing"}) - err := cmd.Args(cmd, []string{"some", "thing"}) - - pt := assert.New(t) - pt.ErrorContains(err, "`Rest (zero arguments)` was not provided") -} - -// -// Added Tests (more complex cases) --------------------------------------- // -// - -// TestOptionalNonRestRangeMinimumPass checks that a slice of positionals -// that is not the last positional struct field will parse only one argument. -func TestOptionalNonRestRangeMinimumPass(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - NonRest []string - Second string - Third string - } `positional-args:"yes" required:"yes"` - }{} - - cmd := newCommandWithArgs(&opts, []string{"first", "second", "third"}) - err := cmd.Args(cmd, []string{"first", "second", "third"}) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal([]string{"first"}, opts.Positional.NonRest) - pt.Equal("second", opts.Positional.Second) - pt.Equal("third", opts.Positional.Third) -} - -// TestRequiredNonRestRangeExcessPass checks that a slice of positionals -// that is not the last positional struct field, will accept: -// - Only up to its specified maximum number. -// This is only slightly different from TestOptionalNonRestRange, -// since, we are not here trying to feed just the bare mininum of -// words to satisfy our requirements. -func TestRequiredNonRestRangeExcessPass(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - NonRest []string `required:"0-2"` - Second string - Third string - } `positional-args:"yes" required:"yes"` - }{} - - args := []string{"nonrest1", "nonrest2", "second", "third", "lambda"} - cmd := newCommandWithArgs(&opts, args) - err := cmd.Args(cmd, args) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal([]string{"nonrest1", "nonrest2"}, opts.Positional.NonRest) - pt.Equal("second", opts.Positional.Second) - pt.Equal("third", opts.Positional.Third) -} - -// TestRequiredNonRestRangeFail checks that a slice of positionals -// that is not the last positional struct field, after parsing words -// according to their minimum requirements, will correctly cause one -// or more of the next positional fields to raise an error. -func TestRequiredNonRestRangeFail(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - NonRest []string `required:"2-3"` - Second string - Third string // Third will fail - } `positional-args:"yes" required:"yes"` - }{} - - args := []string{"nonrest1", "nonrest2", "second"} - cmd := newCommandWithArgs(&opts, args) - err := cmd.Args(cmd, args) - - pt := assert.New(t) - pt.ErrorContains(err, "`Third` was not provided") -} - -// TestMixedSlicesMaxIsMinDefault checks that a struct containing -// at least two slices for which a single numeric value has been specified, -// will automatically set their maximum to the same value, thus correctly -// parsing the words that are given: just enough for all named positionals. -func TestMixedSlicesMaxIsMinDefault(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - FirstList []string `required:"2"` - SecondList []string `required:"2"` - Third string - } `positional-args:"yes" required:"yes"` - }{} - - args := []string{"first1", "first2", "second1", "second2", "third"} - cmd := newCommandWithArgs(&opts, args) - err := cmd.Args(cmd, args) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal([]string{"first1", "first2"}, opts.Positional.FirstList) - pt.Equal([]string{"second1", "second2"}, opts.Positional.SecondList) - pt.Equal("third", opts.Positional.Third) -} - -// TestMixedSlicesNonRestPass checks that two slices of positionals -// will correctly parse according to their minimum/maximum number of -// words accepted, leaving the other words for next arguments. -// This test only provides the minimum valid number of argument words. -func TestMixedSlicesMinimumNonRestPass(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - FirstList []string `required:"2-3"` - SecondList []string `required:"1-2"` - Third string - } `positional-args:"yes" required:"yes"` - }{} - - args := []string{"first1", "first2", "second1", "third"} - cmd := newCommandWithArgs(&opts, args) - err := cmd.Args(cmd, args) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal([]string{"first1", "first2"}, opts.Positional.FirstList) - pt.Equal([]string{"second1"}, opts.Positional.SecondList) - pt.Equal("third", opts.Positional.Third) -} - -// TestMixedSlicesNonRestFail checks that two slices of positionals, -// after parsing words according to their minimum requirements, will -// correctly cause one or more of the next positional fields to raise -// an error. -func TestMixedSlicesMinimumNonRestFail(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - FirstList []string `required:"2-3"` - SecondList []string `required:"1-2"` - Third string - } `positional-args:"yes" required:"yes"` - }{} - - args := []string{"first1", "first2", "second1"} - cmd := newCommandWithArgs(&opts, args) - err := cmd.Args(cmd, args) - - pt := assert.New(t) - pt.ErrorContains(err, "`Third` was not provided") -} - -// TestMixedSlicesLastHasPriority checks that 2 slices of positionals, -// when being given less words than what their combined maximum allows, -// will: -// - Fill the slices according to their ordering in the struct: the -// fist one is being fed words until max, and then passes the words -// up to the next slice. -// - Will still respect the minimum requirements of the following fields. -// -// The function is therefore passed a number of words that is higher -// than the total minimum required, but less than the "max". -func TestMixedSlicesLastHasPriority(t *testing.T) { - t.Parallel() - - opts := struct { - Value bool `short:"v"` - - Positional struct { - FirstList []string `required:"2-3"` - SecondList []string `required:"1-2"` - ThirdList []string `required:"1-2"` - Third string - } `positional-args:"yes" required:"yes"` - }{} - - args := []string{"first1", "first2", "second1", "third1", "third2", "single"} - cmd := newCommandWithArgs(&opts, args) - err := cmd.Args(cmd, args) - - pt := assert.New(t) - pt.Nilf(err, "Unexpected error: %v", err) - pt.Equal([]string{"first1", "first2", "second1"}, opts.Positional.FirstList) - pt.Equal([]string{"third1"}, opts.Positional.SecondList) - pt.Equal([]string{"third2"}, opts.Positional.ThirdList) - pt.Equal("single", opts.Positional.Third) -} - -// TestTwoInfiniteSlicesExplicitFail checks that if a struct containing -// at least two slices that are explicitly marked infinite (no maximum), -// will return an error next to the cobra command being returned. -// func TestTwoInfiniteSlicesExplicitFail(t *testing.T) { -// t.Parallel() -// -// if os.Getenv("TestTwoInfiniteSlicesExplicitFail") == "1" { -// opts := struct { -// Value bool `short:"v"` -// -// Positional struct { -// FirstList []string -// SecondList []string -// ThirdList []string `required:"1-2"` -// Third string -// } `positional-args:"yes" required:"yes"` -// }{} -// -// newCommandWithArgs(&opts, []string{}) // This will fail -// return -// } -// -// cmd := exec.Command(os.Args[0], "-test.run=TestTwoInfiniteSlicesExplicitFail") -// cmd.Env = append(os.Environ(), "TestTwoInfiniteSlicesExplicitFail=1") -// -// err := cmd.Run() -// if e, ok := err.(*exec.ExitError); ok && e.Success() { -// t.Fatalf("process ran with err %v, want exit status 1", err) -// return -// } -// -// pt := assert.New(t) -// pt.NotNilf(err, "Unexpected error: %v", err) -// } - -// -// Double dash positionals (more complex cases) --------------------------------------- // -// - -type doubleDashCommand struct { - Value bool `short:"v"` - - Positional struct { - FirstList []string `required:"2-3"` - SecondList []string `required:"1-2"` - Third string - } `positional-args:"yes" required:"yes"` -} - -// Execute - The double dash command errors out when it does -// not receive some unparsed positional arguments. -func (d *doubleDashCommand) Execute(args []string) error { - if len(args) == 0 { - return errors.New("Did not receive retargs") - } - - return nil -} - -// TestPositionalDoubleDashSuccess checks that a command being fed the correct -// number of required arguments will correctly parse them into their slots, and -// that all remaining arguments after the double dash will be used as retargs. -func TestPositionalDoubleDashSuccess(t *testing.T) { - t.Parallel() - - opts := struct { - Double doubleDashCommand `command:"double-dash"` - }{} - - args := []string{"double-dash", "first1", "first2", "second1", "third1", "--", "third2", "single"} - cmd := newCommandWithArgs(&opts, args) - _, err := cmd.ExecuteC() - - pt := assert.New(t) - pt.Equal([]string{"first1", "first2"}, opts.Double.Positional.FirstList) - pt.Equal([]string{"second1"}, opts.Double.Positional.SecondList) - pt.Equal("third1", opts.Double.Positional.Third) - pt.Nilf(err, "The command returned a retargs error: %v", err) -} - -// TestPositionalDoubleDashFail checks that a command being fed a sufficient -// number of positional arguments but with the double dash positioned such -// that required slots cannot be fulfilled, will indeed fail. -func TestPositionalDoubleDashFail(t *testing.T) { - t.Parallel() - - opts := struct { - Double doubleDashCommand `command:"double-dash"` - }{} - - args := []string{"double-dash", "first1", "first2", "--", "second1", "third1", "third2", "single"} - cmd := newCommandWithArgs(&opts, args) - _, err := cmd.ExecuteC() - - pt := assert.New(t) - pt.ErrorContains(err, "`SecondList (at least 1 argument)` and `Third` were not provided") -} - -// -// Helpers --------------------------------------------------------------- // -// - -func newCommandWithArgs(data interface{}, args []string) *cobra.Command { - cmd := Generate(data) // Generate the command - cmd.SetArgs(args) // And use our args for execution - - // We don't want the errors to be printed to stdout. - cmd.SilenceErrors = true - cmd.SilenceUsage = true - - // by default our root command has name os.Args[1], - // which makes it fail, so only remove it when we - // find in the args sequence - if strings.Contains(cmd.Name(), "cobra.test") { - cmd.Use = "" - } - - return cmd -} diff --git a/go.mod b/go.mod index e45c9e1..7378fd6 100644 --- a/go.mod +++ b/go.mod @@ -1,18 +1,20 @@ module github.com/reeflective/flags -go 1.19 +go 1.23.1 + +toolchain go1.24.2 require ( - github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d + github.com/carapace-sh/carapace v1.8.6 + github.com/carapace-sh/carapace-bin v1.3.3 github.com/go-playground/validator/v10 v10.11.1 - github.com/rsteube/carapace v0.30.0 - github.com/rsteube/carapace-bin v0.19.0 - github.com/spf13/cobra v1.7.0 - github.com/spf13/pflag v1.0.5 - github.com/stretchr/testify v1.8.0 + github.com/spf13/cobra v1.9.1 + github.com/spf13/pflag v1.0.6 + github.com/stretchr/testify v1.8.1 ) require ( + github.com/carapace-sh/carapace-shlex v1.0.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/go-playground/locales v0.14.0 // indirect github.com/go-playground/universal-translator v0.18.0 // indirect @@ -20,9 +22,8 @@ require ( github.com/leodido/go-urn v1.2.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/crypto v0.3.0 // indirect + golang.org/x/mod v0.25.0 // indirect golang.org/x/sys v0.2.0 // indirect golang.org/x/text v0.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) - -replace github.com/rsteube/carapace v0.30.0 => github.com/reeflective/carapace v0.25.2-0.20230416191807-fc9b8c3aa6f6 diff --git a/go.sum b/go.sum index d236223..5f88137 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,10 @@ -github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d h1:Byv0BzEl3/e6D5CLfI0j/7hiIEtvGVFPCZ7Ei2oq8iQ= -github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/carapace-sh/carapace v1.8.6 h1:nYHFcooPyN7ZlAsr21sHKAkkpAYOEPkSO2S6/LQdQvs= +github.com/carapace-sh/carapace v1.8.6/go.mod h1:C0PH0NpNW+Gb2nvnJ8nl2yRvvPxEHqVgYU8fphWGoEg= +github.com/carapace-sh/carapace-bin v1.3.3 h1:/BY+DkFMCTrpKQ9zvouTdkH8tSbqjIkZuHDK8DndV4M= +github.com/carapace-sh/carapace-bin v1.3.3/go.mod h1:6vaM6dixg0709JT/6ad+n+YXohgJanEElw8Hk+GtI/I= +github.com/carapace-sh/carapace-shlex v1.0.1 h1:ww0JCgWpOVuqWG7k3724pJ18Lq8gh5pHQs9j3ojUs1c= +github.com/carapace-sh/carapace-shlex v1.0.1/go.mod h1:lJ4ZsdxytE0wHJ8Ta9S7Qq0XpjgjU0mdfCqiI2FHx7M= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -28,28 +32,28 @@ github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ic github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/reeflective/carapace v0.25.2-0.20230416191807-fc9b8c3aa6f6 h1:3HHTRiXvaEz8iACxwlOBc9jHDYxYNvW60U63Q97/31w= -github.com/reeflective/carapace v0.25.2-0.20230416191807-fc9b8c3aa6f6/go.mod h1:jkLt41Ne2TD2xPuMdX/2O05Smhy8vMgG7O2TYvC0yOc= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= -github.com/rsteube/carapace-bin v0.19.0 h1:pmWOrtO0Fz4G+55OKHjjA4ihIKZKzDZh3Z8X1pY8IBk= -github.com/rsteube/carapace-bin v0.19.0/go.mod h1:yAF4advL85gx7ZFxYYsJu8Rgp2akz4TqvD6M0Bg0VGc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I= -github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= +github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= +github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= +github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.3.0 h1:a06MkbcxBrEFc0w0QIZWXrH/9cCX6KJyWbBOIwAn+7A= golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= +golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w= +golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/internal/completions/cache.go b/internal/completions/cache.go new file mode 100644 index 0000000..2e08321 --- /dev/null +++ b/internal/completions/cache.go @@ -0,0 +1,41 @@ +package completions + +import "github.com/carapace-sh/carapace" + +type compCache struct { + completers *map[int]carapace.CompletionCallback + cache []carapace.CompletionCallback +} + +func newCompletionCache() *compCache { + return &compCache{ + completers: &map[int]carapace.CompletionCallback{}, + } +} + +func (c *compCache) add(index int, cb carapace.CompletionCallback) { + (*c.completers)[index] = cb +} + +func (c *compCache) useCompleter(index int) { + completer, found := (*c.completers)[index] + if found { + c.cache = append(c.cache, completer) + } +} + +func (c *compCache) flush(ctx carapace.Context) carapace.Action { + actions := make([]carapace.Action, 0) + for _, cb := range c.cache { + actions = append(actions, carapace.ActionCallback(cb)) + } + + processed := make([]carapace.Action, 0) + + for _, completion := range actions { + completion = completion.Invoke(ctx).Filter(ctx.Args...).ToA() + processed = append(processed, completion) + } + + return carapace.Batch(processed...).ToA() +} diff --git a/internal/completions/completion.go b/internal/completions/completion.go new file mode 100644 index 0000000..ab6bc80 --- /dev/null +++ b/internal/completions/completion.go @@ -0,0 +1,214 @@ +package completions + +import ( + "reflect" + "strings" + + "github.com/carapace-sh/carapace" + + "github.com/reeflective/flags/internal/interfaces" + "github.com/reeflective/flags/internal/parser" +) + +const ( + completeTagName = "complete" + completeTagMaxParts = 2 +) + +// GetCombinedCompletionAction returns a combined completion action from both the type and the struct tag. +func GetCombinedCompletionAction(val reflect.Value, tag parser.Tag, opts *parser.Opts) (carapace.CompletionCallback, bool, bool) { + typeCompCallback, isRepeatable, itemsImplement := typeCompleter(val) + tagCompCallback, combineWithCompleter, found := getTaggedCompletionAction(tag, opts) + + // Combine the type-implemented completer with tagged completions. + if typeCompCallback != nil && combineWithCompleter { + return func(ctx carapace.Context) carapace.Action { + return carapace.Batch(typeCompCallback(ctx), tagCompCallback(ctx)).ToA() + }, isRepeatable, itemsImplement + + // Or only the type implemented one if no tagged completions. + } else if typeCompCallback != nil && !found { + return typeCompCallback, isRepeatable, itemsImplement + } + + // Or tagged completion directives + if found { + return tagCompCallback, isRepeatable, itemsImplement + } + + return nil, isRepeatable, false +} + +// ChoiceCompletions produces a completer proposing the tagged choices for a flag/arg. +func ChoiceCompletions(tag parser.Tag, val reflect.Value) carapace.CompletionCallback { + choices := tag.GetMany("choice") + + if len(choices) == 0 { + return nil + } + + var allChoices []string + + flagIsList := val.Kind() == reflect.Slice || val.Kind() == reflect.Map + + if flagIsList { + for _, choice := range choices { + allChoices = append(allChoices, strings.Split(choice, " ")...) + } + } else { + allChoices = choices + } + + callback := func(_ carapace.Context) carapace.Action { + return carapace.ActionValues(allChoices...) + } + + return callback +} + +func getCompletionAction(name, value, desc string) carapace.Action { + var action carapace.Action + + switch strings.ToLower(name) { + case "nospace": + return action.NoSpace() + case "nofiles": + case "filterext": + filterExts := strings.Split(value, ",") + action = carapace.ActionFiles(filterExts...).Tag("filtered extensions").FilterArgs() + case "filterdirs": + action = carapace.ActionDirectories().Tag("filtered directories").FilterArgs() // TODO change this + case "files": + files := strings.Split(value, ",") + action = carapace.ActionFiles(files...).FilterArgs() + case "dirs": + action = carapace.ActionDirectories().FilterArgs() + case "default": + return action + } + + return action +} + +// typeCompleter checks for completer implementations on a type. +// It first checks the type itself, and if it's a slice and has no implementation, +// it then checks the slice's element type. +func typeCompleter(val reflect.Value) (carapace.CompletionCallback, bool, bool) { + var callback carapace.CompletionCallback + isRepeatable := (val.Type().Kind() == reflect.Slice) + itemsImplement := false + + // Always check that the type itself does implement, even if + // it's a list of type X that implements the completer as well. + // If yes, we return this implementation, since it has priority. + if isRepeatable { + if callback = getCompleter(val); callback != nil { + return callback, isRepeatable, itemsImplement + } + + // Else we reassign the value to the list type. + val = reflect.New(val.Type().Elem()) + } + + // If we did NOT find an implementation on the + // compound type, check for one on the items. + i := val.Interface() + if impl, ok := i.(interfaces.Completer); ok && impl != nil { + itemsImplement = true + callback = impl.Complete + } else if val.CanAddr() { + isRepeatable = true + if impl, ok := val.Addr().Interface().(interfaces.Completer); ok && impl != nil { + itemsImplement = true + callback = impl.Complete + } + } + + return callback, isRepeatable, itemsImplement +} + +// getCompleter checks if a value (or a pointer to it) implements the Completer interface. +func getCompleter(val reflect.Value) carapace.CompletionCallback { + if val.CanInterface() { + if impl, ok := val.Interface().(interfaces.Completer); ok && impl != nil { + return impl.Complete + } + } + if val.CanAddr() { + if impl, ok := val.Addr().Interface().(interfaces.Completer); ok && impl != nil { + return impl.Complete + } + } + + return nil +} + +func getTaggedCompletionAction(tag parser.Tag, opts *parser.Opts) (carapace.CompletionCallback, bool, bool) { + compTag := tag.GetMany(completeTagName) + description, _ := tag.Get("description") + desc, _ := tag.Get("desc") + + if description == "" { + description = desc + } + + if len(compTag) == 0 { + return nil, false, false + } + + actions := make([]carapace.Action, 0) + combineWithCompleter := false + + for _, tagVal := range compTag { + if tagVal == "" || strings.TrimSpace(tagVal) == "" { + continue + } + + if strings.HasPrefix(tagVal, "+") { + combineWithCompleter = true + tagVal = strings.TrimPrefix(tagVal, "+") + } + + // Check for a custom completer first. + if completer, ok := opts.Completers[tagVal]; ok { + actions = append(actions, carapace.ActionCallback(completer)) + + continue + } + + items := strings.SplitAfterN(tagVal, ",", completeTagMaxParts) + name, value := strings.TrimSuffix(items[0], ","), "" + + if len(items) > 1 { + value = strings.TrimSuffix(items[1], ",") + } + + tagAction := getCompletionAction(name, value, description) + actions = append(actions, tagAction) + } + + callback := func(_ carapace.Context) carapace.Action { + return carapace.Batch(actions...).ToA() + } + + return callback, combineWithCompleter, true +} + +func hintCompletions(tag parser.Tag) (string, bool) { + description, _ := tag.Get("description") + desc, _ := tag.Get("desc") + help, _ := tag.Get("help") + + if description == "" { + description = desc + } + if description == "" { + description = help + } + + if description == "" { + return "", false + } + + return description, true +} diff --git a/internal/completions/positional.go b/internal/completions/positional.go new file mode 100644 index 0000000..3c553d9 --- /dev/null +++ b/internal/completions/positional.go @@ -0,0 +1,150 @@ +package completions + +import ( + "github.com/carapace-sh/carapace" + + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/positional" +) + +// BindPositionals registers the completions for a set of positional arguments. +func BindPositionals(comps *carapace.Carapace, args *positional.Args, opts *parser.Opts) { + compArgs := args.Copy() + completionCache := positionalCompleters(compArgs, opts) + compArgs = positional.WithWordConsumer(compArgs, consumePositionalWith(completionCache)) + + handler := func(ctx carapace.Context) carapace.Action { + compArgs.ParseConcurrent(ctx.Args) + + return completionCache.flush(ctx) + } + + comps.PositionalAnyCompletion(carapace.ActionCallback(handler)) +} + +func positionalCompleters(args *positional.Args, opts *parser.Opts) *compCache { + cache := newCompletionCache() + + for _, arg := range args.Positionals() { + completer := buildPositionalCompleter(arg, opts) + if completer != nil { + cache.add(arg.Index, completer) + } + } + + return cache +} + +func buildPositionalCompleter(arg *parser.Positional, opts *parser.Opts) carapace.CompletionCallback { + // 1. Get all potential completer components. + hint, hasHint := hintCompletions(*arg.Tag) + typeCompleter, _, _ := typeCompleter(arg.Value) + tagCompleter, combine, hasTagCompleter := getTaggedCompletionAction(*arg.Tag, opts) + + // 2. Combine value completers. + var valueCompleter carapace.CompletionCallback + if typeCompleter != nil && tagCompleter != nil && combine { + // Combine both type and tag completers. + valueCompleter = func(c carapace.Context) carapace.Action { + return carapace.Batch(typeCompleter(c), tagCompleter(c)).ToA() + } + } else if hasTagCompleter { + // Prioritize tag completer. + valueCompleter = tagCompleter + } else { + // Fallback to type completer. + valueCompleter = typeCompleter + } + + // 3. Wrap with hint. + var finalCompleter carapace.CompletionCallback + if valueCompleter != nil { + finalCompleter = func(c carapace.Context) carapace.Action { + return valueCompleter(c).Usage(hint) + } + } else if hasHint { + // If only a hint is available, use it directly. + finalCompleter = func(c carapace.Context) carapace.Action { + return carapace.Action{}.Usage(hint) + } + } + + return finalCompleter +} + +// consumePositionalWith returns a custom handler which will be called on each +// positional argument, so that it can consume one/more of the positional words +// and add completions to the cache if needed. +func consumePositionalWith(comps *compCache) positional.WordConsumer { + handler := func(args *positional.Args, arg *parser.Positional, _ int) error { + // First, pop all the words we KNOW we're not + // interested in, which is the number of minimum + // required words BEFORE us. + for range arg.StartMin { + args.Pop() + } + + // Always complete if we have no maximum + if arg.Max == -1 { + return completeOrIgnore(arg, comps, 0) + } + + // If there is a drift between the accumulated words and + // the maximum requirements of the PREVIOUS positionals, + // we use this drift in order not to pop the words as soon + // as we would otherwise do. Useful when more than one positional + // arguments have a minimum-maximum range of allowed arguments. + drift := arg.StartMax - arg.StartMin + actuallyParsed := 0 + + // As long as we've got a word, and nothing told us to quit. + for !args.Empty() { + if drift == 0 { + // That we either consider to be parsed by + // our current positional slot, we pop an + // argument that should be parsed by us. + actuallyParsed++ + } else if drift > 0 { + // Or to be left to one of the preceding + // positionals, which have still some slots + // available for arguments. + drift-- + } + + // Pop the next positional word, as if we would + // parse/convert it into our slot at exec time. + args.Pop() + + // If we have reached the maximum number + // of args we accept, don't complete + if arg.Max == actuallyParsed { + break + } + } + + // This function makes the final call on whether to + // complete for this positional or not. + return completeOrIgnore(arg, comps, actuallyParsed) + } + + return handler +} + +func completeOrIgnore(arg *parser.Positional, comps *compCache, actuallyParsed int) error { + mustComplete := false + + switch { + case arg.Max == -1: + mustComplete = true + case actuallyParsed < arg.Min: + mustComplete = true + case actuallyParsed < arg.Max: + mustComplete = true + } + + if mustComplete { + comps.useCompleter(arg.Index) + } + + return nil +} diff --git a/internal/convert/convert.go b/internal/convert/convert.go deleted file mode 100644 index 2beaf16..0000000 --- a/internal/convert/convert.go +++ /dev/null @@ -1,491 +0,0 @@ -package convert - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "time" - - "github.com/reeflective/flags/internal/tag" -) - -const ( - baseParseInt = 10 - bitsizeParseInt = 32 - requiredNumParsedValues = 2 -) - -// Internal errors. -var ( - errStringer = errors.New("type assertion to `fmt.Stringer` failed") - errUnmarshaler = errors.New("type assertion to `flags.Unmarshaler` failed") -) - -// ErrConvertion is used to notify that converting -// a string value onto a native type has failed. -var ErrConvertion = errors.New("conversion error") - -// marshaler is the interface implemented by types that can marshal themselves -// to a string representation of the flag. Retroported from jessevdk/go-flags. -type marshaler interface { - // MarshalFlag marshals a flag value to its string representation. - MarshalFlag() (string, error) -} - -// unmarshaler is the interface implemented by types that can unmarshal a flag -// argument to themselves. The provided value is directly passed from the -// command line. Retroported from jessevdk/go-flags. -type unmarshaler interface { - // UnmarshalFlag unmarshals a string value representation to the flag - // value (which therefore needs to be a pointer receiver). - UnmarshalFlag(value string) error -} - -// --------------------------------------------------------------------------------------------------- // -// Internal // -// --------------------------------------------------------------------------------------------------- // -// -// 1) Main, entrypoint convert functions -// 2) Per-type convert functions (dispatched by entrypoints) -// 3) Other helpers - -// -// 1) Main, entrypoint convert functions ----------------------------------------------- // -// - -// Value converts a string to its underlying/native value type, therefore -// directly applying this value on the struct field it was created from. -func Value(val string, retval reflect.Value, options tag.MultiTag) error { - // Use unmarshaller if available/possible - if ok, err := convertUnmarshal(val, retval); ok { - return err - } - - valType := retval.Type() - - // Support for time.Duration - if valType == reflect.TypeOf((*time.Duration)(nil)).Elem() { - return convertDuration(val, retval) - } - - switch valType.Kind() { - // Strings & bools - case reflect.String: - retval.SetString(val) - case reflect.Bool: - return convertBool(val, retval) - - // Numbers - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return convertInt(val, valType, retval, options) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return convertUint(val, valType, retval, options) - case reflect.Float32, reflect.Float64: - return convertFloat(val, valType, retval) - - // Arrays - case reflect.Slice: - return convertSlice(val, valType, retval, options) - case reflect.Map: - return convertMap(val, valType, retval, options) - - // Types - case reflect.Ptr: - if retval.IsNil() { - retval.Set(reflect.New(retval.Type().Elem())) - } - - return Value(val, reflect.Indirect(retval), options) - case reflect.Interface: - if !retval.IsNil() { - return Value(val, retval.Elem(), options) - } - } - - return nil -} - -func convertToString(val reflect.Value, options tag.MultiTag) (string, error) { - if ok, ret, err := convertMarshal(val); ok { - return ret, err - } - - if !val.IsValid() { - return "", nil - } - - valType := val.Type() - - // Support for time.Duration - if valType == reflect.TypeOf((*time.Duration)(nil)).Elem() { - stringer, ok := val.Interface().(fmt.Stringer) - if !ok { - return "", fmt.Errorf("convert duration: %w", errStringer) - } - - return stringer.String(), nil - } - - switch valType.Kind() { - case reflect.String: - return val.String(), nil - case reflect.Bool: - return convertBoolStr(val) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return convertIntStr(val, options) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return convertUintStr(val, options) - case reflect.Float32, reflect.Float64: - return strconv.FormatFloat(val.Float(), 'g', -1, valType.Bits()), nil - case reflect.Slice: - return convertSliceStr(val, options) - case reflect.Map: - return convertMapStr(val, options) - case reflect.Ptr: - return convertToString(reflect.Indirect(val), options) - case reflect.Interface: - if !val.IsNil() { - return convertToString(val.Elem(), options) - } - } - - return "", nil -} - -func convertMarshal(val reflect.Value) (bool, string, error) { - // Check first for the Marshaler interface - if val.IsValid() && val.Type().NumMethod() > 0 && val.CanInterface() { - if marshaler, ok := val.Interface().(marshaler); ok { - ret, err := marshaler.MarshalFlag() - - return true, ret, fmt.Errorf("marshal error: %w", err) - } - } - - return false, "", nil -} - -func convertUnmarshal(val string, retval reflect.Value) (bool, error) { - // Use any unmarshalling implementation found on the concrete type. - if unm, found := typeIsUnmarshaller(retval); found && unm != nil { - return convertWithUnmarshaler(val, retval, unm) - } - - // Or recursively call ourselves with embedded types - if retval.Type().Kind() != reflect.Ptr && retval.CanAddr() { - return convertUnmarshal(val, retval.Addr()) - } - - if retval.Type().Kind() == reflect.Interface && !retval.IsNil() { - return convertUnmarshal(val, retval.Elem()) - } - - return false, nil -} - -func convertWithUnmarshaler(val string, retval reflect.Value, unm unmarshaler) (bool, error) { - // If we have an existing value, just use it - if !retval.IsNil() { - if err := unm.UnmarshalFlag(val); err != nil { - return true, fmt.Errorf("unmarshal error: %w", err) - } - - return true, nil - } - - // Else we need to re-assign from the new value - retval.Set(reflect.New(retval.Type().Elem())) - - unm, found := retval.Interface().(unmarshaler) - if !found { - return false, fmt.Errorf("convert marshal: %w", errUnmarshaler) - } - - // And finally perform the custom unmarshaling - if err := unm.UnmarshalFlag(val); err != nil { - return true, fmt.Errorf("unmarshal error: %w", err) - } - - return true, nil -} - -// -// 2) Per-type convert functions (dispatched by entrypoints) ------------------------------- // -// - -func convertDuration(val string, retval reflect.Value) error { - parsed, err := time.ParseDuration(val) - if err != nil { - return fmt.Errorf("convert duration: %w", err) - } - - retval.SetInt(int64(parsed)) - - return nil -} - -func convertBool(val string, retval reflect.Value) error { - if val == "" { - retval.SetBool(true) - } else { - value, err := strconv.ParseBool(val) - if err != nil { - return fmt.Errorf("convert bool: %w", err) - } - - retval.SetBool(value) - } - - return nil -} - -func convertBoolStr(val reflect.Value) (string, error) { - if val.Bool() { - return "true", nil - } - - return "false", nil -} - -func convertInt(val string, valType reflect.Type, retval reflect.Value, options tag.MultiTag) error { - base, err := getBase(options, baseParseInt) - if err != nil { - return err - } - - parsed, err := strconv.ParseInt(val, base, valType.Bits()) - if err != nil { - return fmt.Errorf("convert int: %w", err) - } - - retval.SetInt(parsed) - - return nil -} - -func convertIntStr(val reflect.Value, options tag.MultiTag) (string, error) { - base, err := getBase(options, baseParseInt) - if err != nil { - return "", err - } - - return strconv.FormatInt(val.Int(), base), nil -} - -func convertUint(val string, valType reflect.Type, retval reflect.Value, options tag.MultiTag) error { - base, err := getBase(options, baseParseInt) - if err != nil { - return err - } - - parsed, err := strconv.ParseUint(val, base, valType.Bits()) - if err != nil { - return fmt.Errorf("convert uint: %w", err) - } - - retval.SetUint(parsed) - - return nil -} - -func convertUintStr(val reflect.Value, options tag.MultiTag) (string, error) { - base, err := getBase(options, baseParseInt) - if err != nil { - return "", err - } - - return strconv.FormatUint(val.Uint(), base), nil -} - -func convertFloat(val string, valType reflect.Type, retval reflect.Value) error { - parsed, err := strconv.ParseFloat(val, valType.Bits()) - if err != nil { - return fmt.Errorf("convert float: %w", err) - } - - retval.SetFloat(parsed) - - return nil -} - -func convertSlice(val string, valType reflect.Type, retval reflect.Value, options tag.MultiTag) error { - elemtp := valType.Elem() - - elemvalptr := reflect.New(elemtp) - elemval := reflect.Indirect(elemvalptr) - - if err := Value(val, elemval, options); err != nil { - return err - } - - retval.Set(reflect.Append(retval, elemval)) - - return nil -} - -func convertSliceStr(val reflect.Value, options tag.MultiTag) (string, error) { - if val.Len() == 0 { - return "", nil - } - - ret := "[" - - for i := 0; i < val.Len(); i++ { - if i != 0 { - ret += ", " - } - - item, err := convertToString(val.Index(i), options) - if err != nil { - return "", err - } - - ret += item - } - - return ret + "]", nil -} - -func convertMap(val string, valType reflect.Type, retval reflect.Value, options tag.MultiTag) error { - parts := strings.SplitN(val, ":", requiredNumParsedValues) - - key := parts[0] - - var value string - - if len(parts) == requiredNumParsedValues { - value = parts[1] - } - - keytp := valType.Key() - keyval := reflect.New(keytp) - - if err := Value(key, keyval, options); err != nil { - return err - } - - valuetp := valType.Elem() - valueval := reflect.New(valuetp) - - if err := Value(value, valueval, options); err != nil { - return err - } - - if retval.IsNil() { - retval.Set(reflect.MakeMap(valType)) - } - - retval.SetMapIndex(reflect.Indirect(keyval), reflect.Indirect(valueval)) - - return nil -} - -func convertMapStr(val reflect.Value, options tag.MultiTag) (string, error) { - ret := "{" - - for i, key := range val.MapKeys() { - if i != 0 { - ret += ", " - } - - keyitem, err := convertToString(key, options) - if err != nil { - return "", err - } - - item, err := convertToString(val.MapIndex(key), options) - if err != nil { - return "", err - } - - ret += keyitem + ":" + item - } - - return ret + "}", nil -} - -// -// 3) Other helpers ------------------------------------------------------------------------ // -// - -func typeIsUnmarshaller(retval reflect.Value) (unmarshaler, bool) { - if retval.Type().NumMethod() == 0 || retval.CanInterface() { - return nil, false - } - - if unm, isImplemented := retval.Interface().(unmarshaler); isImplemented { - return unm, true - } - - return nil, false -} - -func getBase(options tag.MultiTag, base int) (int, error) { - var err error - - var ivbase int64 - - if sbase, _ := options.Get("base"); sbase != "" { - ivbase, err = strconv.ParseInt(sbase, baseParseInt, bitsizeParseInt) - base = int(ivbase) - } - - if err != nil { - return base, fmt.Errorf("base int: %w", err) - } - - return base, nil -} - -func isPrint(s string) bool { - for _, c := range s { - if !strconv.IsPrint(c) { - return false - } - } - - return true -} - -func quoteIfNeeded(s string) string { - if !isPrint(s) { - return strconv.Quote(s) - } - - return s -} - -func quoteIfNeededV(s []string) []string { - ret := make([]string, len(s)) - - for i, v := range s { - ret[i] = quoteIfNeeded(v) - } - - return ret -} - -func quoteV(s []string) []string { - ret := make([]string, len(s)) - - for i, v := range s { - ret[i] = strconv.Quote(v) - } - - return ret -} - -func unquoteIfPossible(s string) (string, error) { - if len(s) == 0 || s[0] != '"' { - return s, nil - } - - unquoted, err := strconv.Unquote(s) - if err != nil { - return unquoted, fmt.Errorf("error unquoting: %w", err) - } - - return unquoted, nil -} diff --git a/internal/errors/errors.go b/internal/errors/errors.go new file mode 100644 index 0000000..5846aaf --- /dev/null +++ b/internal/errors/errors.go @@ -0,0 +1,83 @@ +package errors + +import "errors" + +// Generation errors: command/flag/argument generation errors. +var ( + // ErrUnknownSubcommand indicates that the invoked subcommand has not been found. + ErrUnknownSubcommand = errors.New("unknown subcommand") +) + +// Parsing errors: command/flag/argument parsing errors. +var ( + // ErrParse is a general error used to wrap more specific parsing errors. + ErrParse = errors.New("parse error") + + // ErrNotPointerToStruct indicates that a provided data container is not + // a pointer to a struct. + ErrNotPointerToStruct = errors.New("object must be a pointer to struct or interface") + + // ErrNotCommander is returned when a struct is tagged as a command but + // does not implement a command interface (e.g., Commander). + ErrNotCommander = errors.New("struct tagged as command does not implement a runner interface") + + // ErrInvalidTag indicates an invalid tag or invalid use of an existing tag. + ErrInvalidTag = errors.New("invalid tag") + + // ErrNotValue indicates that a struct field type for a flag does not + // implement the flags.Value interface. + ErrNotValue = errors.New("field marked as flag does not implement flags.Value") + + // ErrNilObject indicates that an object is nil although it should not. + ErrNilObject = errors.New("object cannot be nil") + + // ErrPositionalShadowing indicates that a positional argument with an unbounded + // maximum number of values is followed by other positional arguments, which + // it will shadow. + ErrPositionalShadowing = errors.New("positional argument shadows subsequent arguments") + + // ErrUnsupportedType indicates that a type is not supported for a given operation. + ErrUnsupportedType = errors.New("unsupported type") + + // ErrInvalidRequiredQuantity indicates that the minimum number of required arguments is greater + // than the maximum number of arguments that can be accepted. + ErrInvalidRequiredQuantity = errors.New("maximum number of arguments cannot be 0") + + // ErrUnexportedField indicates that an unexported field has been tagged. + ErrUnexportedField = errors.New("unexported field") +) + +// Validation errors: command/flag/argument validation errors. +var ( + // ErrInvalidDuration indicates that a string could not be parsed as a time.Duration. + ErrInvalidDuration = errors.New("invalid duration value") + + // ErrInvalidInteger indicates that a string could not be parsed as an integer. + ErrInvalidInteger = errors.New("invalid integer value") + + // ErrInvalidUint indicates that a string could not be parsed as an unsigned integer. + ErrInvalidUint = errors.New("invalid unsigned integer value") + + // ErrInvalidFloat indicates that a string could not be parsed as a float. + ErrInvalidFloat = errors.New("invalid float value") + + // ErrInvalidChoice indicates that the provided flag argument is not among the valid choices. + ErrInvalidChoice = errors.New("invalid choice") + + // ErrInvalidValue indicates that the provided flag argument is not a valid value for the flag type. + ErrInvalidValue = errors.New("invalid value") + + // ErrRequired signals an argument field has not been + // given its minimum amount of positional words to use. + ErrRequired = errors.New("required argument") + + // ErrTooManyArguments indicates that too many arguments were provided to the command. + ErrTooManyArguments = errors.New("too many arguments") +) + +// Internal errors: should not happen, but are here for safety. +var ( + // ErrTypeAssertion indicates that a type assertion failed unexpectedly. + // This typically points to an internal logic error in the library. + ErrTypeAssertion = errors.New("internal type assertion error") +) diff --git a/internal/gen/command.go b/internal/gen/command.go new file mode 100644 index 0000000..149cc44 --- /dev/null +++ b/internal/gen/command.go @@ -0,0 +1,327 @@ +package gen + +import ( + "fmt" + "reflect" + "strings" + + "github.com/carapace-sh/carapace" + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/interfaces" + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/positional" +) + +// command finds if a field is marked as a subcommand, and if yes, scans it. +func command(parentCtx *context, tag *parser.Tag, val reflect.Value) (bool, error) { + name, isCommand := getCommandName(tag) + if !isCommand { + return false, nil + } + + // 1. Initialize the command object (root or subcommand). + cmd, data := setupCommand(parentCtx, name, tag, val) + + // 2. Scan the command's struct to find its flags, positionals, etc. + subCtx, err := scanCommand(cmd, parentCtx, data) + if err != nil { + return true, err + } + + // 3. Finalize the command's own configuration (args, run funcs, flag rules). + if err := finalizeCommand(subCtx, data, tag); err != nil { + return true, err + } + + // 4. Add the subcommand to its parent (if it's not the root). + if cmd != parentCtx.cmd { + parentCtx.cmd.AddCommand(cmd) + } + + // 5. Handle special modifications to the parent, like setting this as the default. + if err := handleDefaultCommand(parentCtx, cmd, tag); err != nil { + return true, err + } + + return true, nil +} + +// getCommandName extracts the command name from the struct tag. +func getCommandName(tag *parser.Tag) (name string, isCommand bool) { + if name, ok := tag.Get("command"); ok { + return name, true + } + if name, ok := tag.Get("cmd"); ok { + return name, true + } + + return "", false +} + +// setupCommand initializes the cobra.Command and its context. +func setupCommand(ctx *context, name string, tag *parser.Tag, val reflect.Value) (*cobra.Command, any) { + ptrVal := parser.EnsureAddr(val) + data := ptrVal.Interface() + + var sub *cobra.Command + if name == ctx.cmd.Use { + sub = ctx.cmd + } else { + sub = newCommand(name, tag) + tagged, _ := tag.Get("group") + setCommandGroup(ctx.cmd, sub, ctx.group, tagged) + } + + return sub, data +} + +// scanCommand scans the command's struct for flags, positionals, and subcommands. +func scanCommand(cmd *cobra.Command, parentCtx *context, data any) (*context, error) { + subCtx := &context{ + cmd: cmd, + group: parentCtx.group, + opts: parentCtx.opts, + positionals: positional.NewArgs(), + comps: carapace.Gen(cmd), + flagComps: make(map[string]carapace.Action), + } + + scanner := newFieldScanner(subCtx) + if err := parser.Scan(data, scanner); err != nil { + return nil, err + } + + return subCtx, nil +} + +// finalizeCommand applies final configurations to the command. +func finalizeCommand(ctx *context, data any, tag *parser.Tag) error { + if err := ctx.positionals.Finalize(ctx.cmd); err != nil { + return err + } + ctx.cmd.Args = ctx.positionals.ToCobraArgs() + + if err := applyFlagRules(ctx); err != nil { + return err + } + + setRuns(ctx.cmd, tag, data) + + ctx.bindCompletions() + + return nil +} + +// handleDefaultCommand checks and sets the command as the default if specified. +func handleDefaultCommand(ctx *context, cmd *cobra.Command, tag *parser.Tag) error { + defaultVal, isDefault := tag.Get("default") + if !isDefault { + return nil + } + + if ctx.defaultCommand != nil { + return fmt.Errorf("cannot set '%s' as default command, '%s' is already the default", + cmd.Name(), ctx.defaultCommand.Name()) + } + + ctx.defaultCommand = cmd + cmd.Flags().VisitAll(func(f *pflag.Flag) { + f.Hidden = true + ctx.cmd.Flags().AddFlag(f) + }) + + ctx.cmd.RunE = func(c *cobra.Command, args []string) error { + return runDefaultCommand(c, cmd, defaultVal, args) + } + + return nil +} + +// runDefaultCommand executes the default command logic. +func runDefaultCommand(parent, sub *cobra.Command, defaultVal string, args []string) error { + if defaultVal == "1" && len(args) > 0 { + return nil + } + + var defaultCmd *cobra.Command + for _, subCmd := range parent.Commands() { + if subCmd.Name() == sub.Name() { + defaultCmd = subCmd + + break + } + } + + if defaultCmd == nil { + return fmt.Errorf("default command %s not found", sub.Name()) + } + + if defaultCmd.RunE != nil { + return defaultCmd.RunE(defaultCmd, args) + } + + return nil +} + +// newCommand builds a quick command template based on +// what has been specified through tags, and in context. +func newCommand(name string, tag *parser.Tag) *cobra.Command { + subc := &cobra.Command{ + Use: name, + Annotations: map[string]string{}, + } + + if desc, _ := tag.Get("description"); desc != "" { + subc.Short = desc + } else if desc, _ := tag.Get("desc"); desc != "" { + subc.Short = desc + } + + subc.Long, _ = tag.Get("long-description") + subc.Aliases = tag.GetMany("alias") + subc.Aliases = append(subc.Aliases, tag.GetMany("aliases")...) + _, subc.Hidden = tag.Get("hidden") + + return subc +} + +// setCommandGroup sets the command group for a subcommand. +func setCommandGroup(cmd, sub *cobra.Command, parentGroup *cobra.Group, tagged string) { + var group *cobra.Group + + // The group tag on the command has priority + if tagged != "" { + for _, grp := range cmd.Groups() { + if grp.ID == tagged { + group = grp + } + } + + if group == nil { + group = &cobra.Group{ID: tagged, Title: tagged} + cmd.AddGroup(group) + } + } else if parentGroup != nil { + group = parentGroup + } + + // Use the group we settled on + if group != nil { + sub.GroupID = group.ID + } +} + +// unknownSubcommandAction is the action taken when a subcommand is not recognized. +func unknownSubcommandAction(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + //nolint:wrapcheck + return cmd.Help() + } + + err := fmt.Sprintf("%q for %q", args[0], cmd.Name()) + + if suggestions := cmd.SuggestionsFor(args[0]); len(suggestions) > 0 { + err += "\n\nDn" + for _, s := range suggestions { + err += fmt.Sprintf("\t%v\n", s) + } + + err = strings.TrimSuffix(err, "\n") + } + + return fmt.Errorf("%w %s", errors.ErrUnknownSubcommand, err) +} + +// hasSubcommands checks that a command has at least one +// command that is not the _carapace completion command. +func hasSubcommands(cmd *cobra.Command) bool { + for _, sub := range cmd.Commands() { + if sub.Name() != "_carapace" { + return true + } + } + + return false +} + +// setRuns sets the run functions for a command, based +// on the interfaces implemented by the command struct. +func setRuns(cmd *cobra.Command, tag *parser.Tag, data any) { + if data == nil { + return + } + + // By default, always bind a generic positional word handler. + if cmd.Args == nil { + cmd.Args = func(cmd *cobra.Command, args []string) error { + positional.SetRemainingArgs(cmd, args) + + return nil + } + } + + // Next, if subcommand invocation is mandatory, + // bind a non-persistent run function. If not, + // bind a default Run implementation: this will + // ensure any positional args/flags will be parsed + // onto the command's struct, even if it doesn't + // have an actually run implementation. + _, isSet := tag.Get("subcommands-optional") + if !isSet && hasSubcommands(cmd) { + cmd.RunE = unknownSubcommandAction + } else { + cmd.RunE = func(cmd *cobra.Command, args []string) error { + return nil + } + + // The default RunE might be overwritten + // by any type-implemented Run method. + setPreRuns(cmd, data) + setMainRuns(cmd, data) + setPostRuns(cmd, data) + } +} + +// setPreRuns sets the pre-run functions for a command. +func setPreRuns(cmd *cobra.Command, data any) { + if runner, ok := data.(interfaces.PreRunner); ok && runner != nil { + cmd.PreRun = func(c *cobra.Command, _ []string) { + runner.PreRun(positional.GetRemainingArgs(c)) + } + } + if runner, ok := data.(interfaces.PreRunnerE); ok && runner != nil { + cmd.PreRunE = func(c *cobra.Command, _ []string) error { + return runner.PreRunE(positional.GetRemainingArgs(c)) + } + } +} + +// setMainRuns sets the main run functions for a command. +func setMainRuns(cmd *cobra.Command, data any) { + if commander, ok := data.(interfaces.Commander); ok && commander != nil { + cmd.RunE = func(c *cobra.Command, _ []string) error { + return commander.Execute(positional.GetRemainingArgs(c)) + } + } else if runner, ok := data.(interfaces.Runner); ok && runner != nil { + cmd.Run = func(c *cobra.Command, _ []string) { + runner.Run(positional.GetRemainingArgs(c)) + } + } +} + +// setPostRuns sets the post-run functions for a command. +func setPostRuns(cmd *cobra.Command, data any) { + if runner, ok := data.(interfaces.PostRunner); ok && runner != nil { + cmd.PostRun = func(c *cobra.Command, _ []string) { + runner.PostRun(positional.GetRemainingArgs(c)) + } + } + if runner, ok := data.(interfaces.PostRunnerE); ok && runner != nil { + cmd.PostRunE = func(c *cobra.Command, _ []string) error { + return runner.PostRunE(positional.GetRemainingArgs(c)) + } + } +} diff --git a/gen/flags/command_test.go b/internal/gen/command_test.go similarity index 60% rename from gen/flags/command_test.go rename to internal/gen/command_test.go index f0cdd31..4aab41f 100644 --- a/gen/flags/command_test.go +++ b/internal/gen/command_test.go @@ -1,9 +1,14 @@ -package flags +package gen import ( + "strings" "testing" + "github.com/spf13/cobra" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/reeflective/flags/internal/parser" ) // Test only partially ported from github.com/jessevdk/go-flags, since we are @@ -36,7 +41,7 @@ type root struct { } // Execute - The root command implementation. -func (*root) Execute(args []string) error { +func (*root) Execute(_ []string) error { return nil } @@ -51,10 +56,53 @@ type testCommand struct { } // Execute - Generic command that is used as child command to programs. -func (t *testCommand) Execute(args []string) error { +func (t *testCommand) Execute(_ []string) error { + return nil +} + +type optionalCommandsRoot struct { + C1 struct { + SC1 testCommand `command:"sc1"` + SC2 testCommand `command:"sc2"` + } `command:"c1" subcommands-optional:"yes"` + + C2 struct { + SC1 testCommand `command:"sc1"` + SC2 testCommand `command:"sc2"` + } `command:"c2"` +} + +// +// Default Command structs ----------------------------------------------------- // +// + +type defaultCommandRoot struct { + Run runCommand `command:"run" default:"withargs"` + Test testCommand `command:"test"` +} + +type runCommand struct { + Value string `long:"value"` +} + +func (r *runCommand) Execute(args []string) error { + if len(args) > 0 { + r.Value = args[0] + } + return nil } +type simpleDefaultCommandRoot struct { + Run runCommand `command:"run" default:"1"` + Test testCommand `command:"test"` +} + +type invalidDoubleDefaultCommandRoot struct { + Run runCommand `command:"run" default:"1"` + Test runCommand `command:"test" default:"1"` +} + // // Command Flags --------------------------------------------------------------- // // @@ -65,7 +113,7 @@ func TestParseCommand(t *testing.T) { t.Parallel() data := &testCommand{} - cmd := Generate(data) + cmd, _ := Generate(data) test := assert.New(t) test.NotNil(cmd, "The command parser should have returned a command") @@ -77,17 +125,17 @@ func TestCommandInline(t *testing.T) { t.Parallel() opts := struct { - Value bool `short:"v" long:"version"` + Value bool `long:"version" short:"v"` Command testCommand `command:"cmd"` // Can be a copy, or a pointer. }{} // Commands are, by default, marked TraverseChildren = true - root := newCommandWithArgs(&opts, []string{"-v", "cmd", "-g"}) + root, err := newCommandWithArgs(&opts, []string{"-v", "cmd", "-g"}) cmd, err := root.ExecuteC() test := assert.New(t) test.NotNil(cmd) - test.Nil(err, "Command should have exited successfully") + test.NoError(err, "Command should have exited successfully") test.Equal("cmd", cmd.Name(), "Target command `cmd` should have been found.") test.NotNil(root.Flags().ShorthandLookup("v"), "A flag -v should have been found on the root command") @@ -108,12 +156,12 @@ func TestCommandInlineMulti(t *testing.T) { C2 testCommand `command:"c2"` }{} - root := newCommandWithArgs(&opts, []string{"-v", "c2", "-g"}) + root, err := newCommandWithArgs(&opts, []string{"-v", "c2", "-g"}) cmd, err := root.ExecuteC() test := assert.New(t) test.NotNil(cmd) - test.Nil(err, "Command should have exited successfully") + test.NoError(err, "Command should have exited successfully") test.Equal("c2", cmd.Name(), "Target command `c2` should have been found.") test.NotNil(root.Flags().ShorthandLookup("v"), "A flag -v should have been found on the root command") @@ -129,18 +177,18 @@ func TestCommandFlagOrderFail(t *testing.T) { t.Parallel() opts := struct { - Value bool `short:"v" long:"version"` + Value bool `long:"version" short:"v"` Command testCommand `command:"cmd"` }{} // Commands are, by default, marked TraverseChildren = true - root := newCommandWithArgs(&opts, []string{"-v", "-g", "cmd"}) + root, err := newCommandWithArgs(&opts, []string{"-v", "-g", "cmd"}) cmd, err := root.ExecuteC() pt := assert.New(t) pt.NotNil(cmd) - pt.NotNil(err, "Command should have raised an unknown flag error") - pt.ErrorContains(err, "unknown shorthand flag: \"g\" in -g") + pt.Error(err, "Command should have raised an unknown flag error") + pt.ErrorContains(err, "unknown shorthand flag: 'g' in -g") } // TestCommandFlagOrder checks that flags bound to some commands @@ -149,16 +197,16 @@ func TestCommandFlagOrderSuccess(t *testing.T) { t.Parallel() opts := struct { - Value bool `short:"v" long:"version"` + Value bool `long:"version" short:"v"` Command testCommand `command:"cmd"` }{} - root := newCommandWithArgs(&opts, []string{"-v", "cmd", "-g"}) + root, err := newCommandWithArgs(&opts, []string{"-v", "cmd", "-g"}) cmd, err := root.ExecuteC() pt := assert.New(t) pt.NotNil(cmd) - pt.Nil(err, "Command should have successfully parsed the flags") + pt.NoError(err, "Command should have successfully parsed the flags") } // TestCommandFlagPersistentSuccess checks that flag groups marked @@ -169,19 +217,19 @@ func TestCommandFlagPersistentSuccess(t *testing.T) { cmdData := struct { Opts struct { - Value bool `short:"v" long:"version"` + Value bool `long:"version" short:"v"` } `group:"options" persistent:"true"` Command testCommand `command:"cmd"` }{} - root := newCommandWithArgs(&cmdData, []string{"cmd", "-v", "-g"}) + root, err := newCommandWithArgs(&cmdData, []string{"cmd", "-v", "-g"}) cmd, err := root.ExecuteC() pt := assert.New(t) pt.NotNil(cmd) pt.Equal("cmd", cmd.Name()) - pt.Nil(err, "Command should have successfully parsed the flags") // + pt.NoError(err, "Command should have successfully parsed the flags") // pt.True(cmdData.Opts.Value, "flag -v should be true") } @@ -194,19 +242,19 @@ func TestCommandFlagPersistentFail(t *testing.T) { cmdData := struct { Opts struct { - Value bool `short:"v" long:"version"` + Value bool `long:"version" short:"v"` } `group:"options" persistent:"true"` // We use a tag to mark them. Command testCommand `command:"cmd"` }{} - root := newCommandWithArgs(&cmdData, []string{"-p", "cmd", "-v", "-g"}) + root, err := newCommandWithArgs(&cmdData, []string{"-p", "cmd", "-v", "-g"}) cmd, err := root.ExecuteC() - pt := assert.New(t) + pt := require.New(t) pt.NotNil(cmd) - pt.NotNil(err, "Command should have raised an unknown flag error") - pt.ErrorContains(err, "unknown shorthand flag: \"p\" in -p") + pt.Error(err, "Command should have raised an unknown flag error") + pt.ErrorContains(err, "unknown shorthand flag: 'p' in -p") pt.Equal(cmd.Name(), root.Name()) } @@ -223,13 +271,13 @@ func TestCommandFlagOverrideParent(t *testing.T) { Command root `command:"cmd"` // Has the same -v flag }{} - root := newCommandWithArgs(&opts, []string{"cmd", "-v"}) + root, err := newCommandWithArgs(&opts, []string{"cmd", "-v"}) cmd, err := root.ExecuteC() pt := assert.New(t) pt.NotNil(cmd) pt.Equal("cmd", cmd.Name()) - pt.Nil(err, "Command should have successfully parsed the flags") // + pt.NoError(err, "Command should have successfully parsed the flags") // pt.False(opts.Value, "parent flag -v should be false") pt.True(opts.Command.V, "child flag -v should be true") } @@ -246,33 +294,17 @@ func TestCommandFlagOverrideChild(t *testing.T) { Command root `command:"cmd"` // Has the same -v flag }{} - root := newCommandWithArgs(&opts, []string{"-v", "cmd"}) + root, err := newCommandWithArgs(&opts, []string{"-v", "cmd"}) cmd, err := root.ExecuteC() test := assert.New(t) test.NotNil(cmd) test.Equal("cmd", cmd.Name()) - test.Nil(err, "Command should have successfully parsed the flags") // + test.NoError(err, "Command should have successfully parsed the flags") // test.True(opts.Value, "parent flag -v should be true") test.False(opts.Command.V, "child flag -v should be false") } -// -// Command Execution & Runners ----------------------------------------------------- // -// - -type optionalCommandsRoot struct { - C1 struct { - SC1 testCommand `command:"sc1"` - SC2 testCommand `command:"sc2"` - } `command:"c1" subcommands-optional:"yes"` - - C2 struct { - SC1 testCommand `command:"sc1"` - SC2 testCommand `command:"sc2"` - } `command:"c2"` -} - // TestCommandAdd checks that a command type is correctly scanned and translated // into a cobra command. We don't need to test for this recursively, since we let // cobra itself deal with how it would "merge" them when .AddCommand(). @@ -281,27 +313,27 @@ func TestCommandAdd(t *testing.T) { t.Parallel() rootData := root{} - root := newCommandWithArgs(&rootData, []string{"-v", "c1", "-p", "-g"}) + root, err := newCommandWithArgs(&rootData, []string{"-v", "c1", "-p", "-g"}) // Binding checks test := assert.New(t) test.NotNil(root.RunE) // The command has not SubcommandsOptional true - test.Equal(2, len(root.Commands())) + test.Len(root.Commands(), 3) // Command 1 - cmd1 := root.Commands()[0] + cmd1 := root.Commands()[1] // 1 because 0 is _carapace test.Equal("c1", cmd1.Name()) test.NotNil(cmd1.RunE) // Command 2 - cmd2 := root.Commands()[1] + cmd2 := root.Commands()[2] test.Equal("c2", cmd2.Name()) test.NotNil(cmd2.RunE) resultCmd, err := root.ExecuteC() - test.Nil(err) + test.NoError(err) test.True(rootData.V) - test.Equal(cmd1, resultCmd) + test.Equal(cmd1.Name(), resultCmd.Name()) test.True(rootData.C1.G) } @@ -311,33 +343,146 @@ func TestSubcommandsOptional(t *testing.T) { t.Parallel() rootData := optionalCommandsRoot{} - root := newCommandWithArgs(&rootData, []string{"c1"}) + root, err := newCommandWithArgs(&rootData, []string{"c1"}) test := assert.New(t) test.NotNil(root.RunE) - err := root.Execute() - test.Nil(err) + err = root.Execute() + test.NoError(err) } // TestSubcommandsRequiredUsage checks that a command having required // subcommands (hence not being marked "subcommands-optional"), will -/// return the correct errors (or no errors), depending on the words. +// / return the correct errors (or no errors), depending on the words. func TestSubcommandsRequiredUsage(t *testing.T) { t.Parallel() rootData := optionalCommandsRoot{} - root := newCommandWithArgs(&rootData, []string{"c2"}) + root, err := newCommandWithArgs(&rootData, []string{"c2"}) test := assert.New(t) test.NotNil(root.RunE) // No error since help usage printed does not return an error. - err := root.Execute() - test.Nil(err) + err = root.Execute() + test.NoError(err) // And error since invoked command does not exist root.SetArgs([]string{"c2", "invalid"}) err = root.Execute() - test.NotNil(err) + test.Error(err) +} + +func TestDefaultCommand(t *testing.T) { + t.Parallel() + + // Success case: `default:"withargs"` should execute the default command with args. + t.Run("With args success", func(t *testing.T) { + t.Parallel() + cfg := &defaultCommandRoot{} + cmd, err := newCommandWithArgs(cfg, []string{"--value=foo"}) + require.NoError(t, err) + + err = cmd.Execute() + require.NoError(t, err) + assert.Equal(t, "foo", cfg.Run.Value) + }) + + // Success case: `default:"1"` should execute the default command with no args. + t.Run("Simple default success", func(t *testing.T) { + t.Parallel() + cfg := &simpleDefaultCommandRoot{} + cmd, err := newCommandWithArgs(cfg, []string{}) + require.NoError(t, err) + + err = cmd.Execute() + require.NoError(t, err) + }) + + // Failure case: `default:"1"` should fail if args are provided. + t.Run("Simple default with args fail", func(t *testing.T) { + t.Parallel() + cfg := &simpleDefaultCommandRoot{} + cmd, err := newCommandWithArgs(cfg, []string{"some-arg"}) + require.NoError(t, err) + + err = cmd.Execute() + require.Error(t, err) + assert.Contains(t, err.Error(), "unknown subcommand \"some-arg\"") + }) + + // Failure case: Two default commands should cause an error. + t.Run("Double default fail", func(t *testing.T) { + t.Parallel() + cfg := &invalidDoubleDefaultCommandRoot{} + _, err := Generate(cfg) + require.Error(t, err) + assert.Contains(t, err.Error(), "cannot set 'test' as default command, 'run' is already the default") + }) +} + +// +// Command Execution & Runners ----------------------------------------------------- // +// + +func newCommandWithArgs(data any, args []string) (*cobra.Command, error) { + cmd, err := Generate(data) // Generate the command + if err != nil { + return cmd, err + } + + cmd.SetArgs(args) // And use our args for execution + + // We don't want the errors to be printed to stdout. + cmd.SilenceErrors = true + cmd.SilenceUsage = true + + // by default our root command has name os.Args[1], + // which makes it fail, so only remove it when we + // find it in the args sequence + if strings.Contains(cmd.Name(), "cobra.test") { + cmd.Use = "" + } + + return cmd, nil +} + +// run condenses all CLI/flags parsing steps, and compares +// all structs/errors against their expected state. +func run(t *testing.T, test *testConfig) { + t.Helper() + + // We must parse all struct fields regardless of them being tagged. + parseOptions := parser.ParseAll() + + cmd, err := Generate(test.cfg, parseOptions) + + if test.expErr1 != nil { + require.Error(t, err) + require.Equal(t, test.expErr1, err) + } else { + require.NoError(t, err) + } + + if err != nil { + return + } + + cmd.SetArgs(test.args) + + err = cmd.Execute() + + if test.expErr2 != nil { + assert.Error(t, err) + require.Equal(t, test.expErr2, err) + } else { + require.NoError(t, err) + } + + if err != nil { + return + } + + assert.Equal(t, test.expCfg, test.cfg) } diff --git a/internal/gen/flag.go b/internal/gen/flag.go new file mode 100644 index 0000000..56fd598 --- /dev/null +++ b/internal/gen/flag.go @@ -0,0 +1,129 @@ +package gen + +import ( + "fmt" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/values" +) + +// flagSet describes interface, +// that's implemented by pflag library and required by flags. +type flagSet interface { + VarPF(value pflag.Value, name, shorthand, usage string) *pflag.Flag +} + +var _ flagSet = (*pflag.FlagSet)(nil) + +// generateTo takes a list of parser.Flag, parsed from +// a struct, and adds them to the destination command's flag sets. +func generateTo(src []*parser.Flag, cmd *cobra.Command) { + for _, srcFlag := range src { + val, ok := srcFlag.Value.(pflag.Value) + if !ok { + continue + } + + var dst *pflag.FlagSet + if srcFlag.Persistent { + dst = cmd.PersistentFlags() + } else { + dst = cmd.Flags() + } + + // Register the primary flag. + registerFlag(dst, srcFlag, val) + + // If the flag is negatable, register a hidden negation flag. + if srcFlag.Negatable != nil { + registerNegatableFlag(dst, srcFlag, val) + } + } +} + +// registerFlag handles the creation and configuration of a single primary pflag.Flag. +func registerFlag(dst flagSet, src *parser.Flag, val pflag.Value) { + usage := src.Usage + if src.Placeholder != "" { + usage = fmt.Sprintf("%s (placeholder: %s)", usage, src.Placeholder) + } + + flag := dst.VarPF(val, src.Name, src.Short, usage) + flag.Annotations = map[string][]string{} + flag.NoOptDefVal = strings.Join(src.OptionalValue, " ") + flag.Hidden = src.Hidden + + if boolFlag, ok := src.Value.(values.BoolFlag); ok && boolFlag.IsBoolFlag() { + flag.NoOptDefVal = "true" + } else if src.Required { + flag.Annotations["flags"] = []string{"required"} + } + + if src.Deprecated { + flag.Deprecated = src.Usage + if flag.Deprecated == "" { + flag.Deprecated = "Deprecated" + } + } +} + +// registerNegatableFlag handles the creation of the hidden --no-... variant for a boolean flag. +func registerNegatableFlag(dst flagSet, src *parser.Flag, val pflag.Value) { + var noName string + if *src.Negatable == "" { + noName = "no-" + src.Name // Default behavior + } else { + noName = *src.Negatable // Custom name + } + + noUsage := "negates --" + src.Name + noVal := &values.Inverter{Target: val} + + noFlag := dst.VarPF(noVal, noName, "", noUsage) + noFlag.Hidden = true // The negation variant is usually hidden from help text. + + // By setting NoOptDefVal, we tell pflag that this flag can be used + // without an explicit argument (e.g., `--no-my-flag`). When this + // happens, pflag will pass "true" to the Set method of our Inverter, + // which will then correctly invert it to `false`. + noFlag.NoOptDefVal = "true" +} + +// applyFlagRules iterates over collected flags and applies cross-cutting rules. +func applyFlagRules(ctx *context) error { + // Group flags by their XOR group names. + xorGroups := make(map[string][]string) + for _, flag := range ctx.Flags { + for _, group := range flag.XORGroup { + xorGroups[group] = append(xorGroups[group], flag.Name) + } + } + + // Mark each XOR group as mutually exclusive on the command itself. + for _, flagsInGroup := range xorGroups { + if len(flagsInGroup) > 1 { + ctx.cmd.MarkFlagsMutuallyExclusive(flagsInGroup...) + } + } + + // Group flags by their AND group names. + andGroups := make(map[string][]string) + for _, flag := range ctx.Flags { + for _, group := range flag.ANDGroup { + andGroups[group] = append(andGroups[group], flag.Name) + } + } + + // Mark each AND group as required together. + for _, flagsInGroup := range andGroups { + if len(flagsInGroup) > 1 { + ctx.cmd.MarkFlagsRequiredTogether(flagsInGroup...) + } + } + + return nil +} diff --git a/internal/gen/flag_logic_test.go b/internal/gen/flag_logic_test.go new file mode 100644 index 0000000..9d7be57 --- /dev/null +++ b/internal/gen/flag_logic_test.go @@ -0,0 +1,227 @@ +package gen + +import ( + "errors" + "testing" +) + +// +// "XOR" Group Tests -------------------------------------------------- // +// + +// A sophisticated struct for testing XOR flags. +type xorConfig struct { + // Top-level XOR + Apple bool `long:"apple" short:"a" xor:"fruit"` + Banana bool `long:"banana" short:"b" xor:"fruit"` + + // Nested group with its own XOR + JuiceGroup `group:"juice options"` + + // Embedded struct with XOR flags + EmbeddedXor + + // A flag in multiple XOR groups + Verbose bool `short:"v" xor:"output,verbosity"` + Quiet bool `short:"q" xor:"output"` + Loud bool `short:"l" xor:"verbosity"` +} + +type JuiceGroup struct { + Orange bool `long:"orange" xor:"citrus"` + Lemon bool `long:"lemon" xor:"citrus"` +} + +type EmbeddedXor struct { + Grape bool `long:"grape" xor:"fruit"` // Belongs to the top-level 'fruit' group + Water bool `long:"water" xor:"beverage"` + Milk bool `long:"milk" xor:"beverage"` +} + +// TestXORFlags verifies the behavior of "XOR" groups, +// where all flags in the group cannot be used together. +func TestXORFlags(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + args []string + expErr error + expCfg xorConfig + }{ + // --- VALID CASES --- + { + name: "Valid top-level XOR", + args: []string{"--apple"}, + expCfg: xorConfig{Apple: true}, + }, + { + name: "Valid nested XOR", + args: []string{"--orange"}, + expCfg: xorConfig{ + JuiceGroup: JuiceGroup{ + Orange: true, + }, + }, + }, + { + name: "Valid embedded XOR", + args: []string{"--milk"}, + expCfg: xorConfig{EmbeddedXor: EmbeddedXor{Milk: true}}, + }, + { + name: "Valid multi-group XOR", + args: []string{"-q"}, + expCfg: xorConfig{Quiet: true}, + }, + + // --- INVALID CASES --- + { + name: "Invalid top-level XOR", + args: []string{"--apple", "--banana"}, + expErr: errors.New(`if any flags in the group [apple banana grape] are set none of the others can be; [apple banana] were all set`), + }, + { + name: "Invalid nested XOR", + args: []string{"--orange", "--lemon"}, + expErr: errors.New(`if any flags in the group [orange lemon] are set none of the others can be; [lemon orange] were all set`), + }, + { + name: "Invalid embedded XOR", + args: []string{"--water", "--milk"}, + expErr: errors.New(`if any flags in the group [water milk] are set none of the others can be; [milk water] were all set`), + }, + { + name: "Invalid top-level and embedded XOR", + args: []string{"--apple", "--grape"}, + expErr: errors.New(`if any flags in the group [apple banana grape] are set none of the others can be; [apple grape] were all set`), + }, + { + name: "Invalid multi-group XOR (output group)", + args: []string{"-v", "-q"}, + expErr: errors.New(`if any flags in the group [verbose quiet] are set none of the others can be; [quiet verbose] were all set`), + }, + { + name: "Invalid multi-group XOR (verbosity group)", + args: []string{"-v", "-l"}, + expErr: errors.New(`if any flags in the group [verbose loud] are set none of the others can be; [loud verbose] were all set`), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := &xorConfig{} + test := &testConfig{ + cfg: cfg, + args: tt.args, + expCfg: &tt.expCfg, + expErr2: tt.expErr, + } + run(t, test) + }) + } +} + +// +// "AND" Group Tests -------------------------------------------------- // +// + +type andConfig struct { + First bool `and:"group1" long:"first"` + Second bool `and:"group1" long:"second"` + Third bool `long:"third"` +} + +// TestANDFlags verifies the behavior of "AND" groups, +// where all flags in the group must be used together. +func TestANDFlags(t *testing.T) { + t.Parallel() + + // Success case: Both flags in the AND group are provided. + t.Run("Valid AND group", func(t *testing.T) { + t.Parallel() + cfg := &andConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{"--first", "--second"}, + expCfg: &andConfig{First: true, Second: true}, + } + run(t, test) + }) + + // Failure case: Only one flag in the AND group is provided. + t.Run("Invalid AND group", func(t *testing.T) { + t.Parallel() + cfg := &andConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{"--first"}, + expErr2: errors.New(`if any flags in the group [first second] are set they must all be set; missing [second]`), + } + run(t, test) + }) + + // Success case: No flags from the AND group are provided. + t.Run("No AND group flags", func(t *testing.T) { + t.Parallel() + cfg := &andConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{"--third"}, + expCfg: &andConfig{Third: true}, + } + run(t, test) + }) +} + +// +// Negatable flags Group Tests -------------------------------------------------- // +// + +type customNegatableConfig struct { + Default bool `long:"default" negatable:""` + Custom bool `long:"custom" negatable:"disable-custom"` + WithValue bool `default:"true" long:"with-value" negatable:"disable"` +} + +// TestCustomNegatableFlags verifies the behavior of negatable flags with +// entirely custom names. +func TestCustomNegatableFlags(t *testing.T) { + t.Parallel() + + // Success case: Default negatable flag works. + t.Run("Default negatable", func(t *testing.T) { + t.Parallel() + cfg := &customNegatableConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{"--no-default"}, + expCfg: &customNegatableConfig{Default: false}, + } + run(t, test) + }) + + // Success case: Custom negatable flag works. + t.Run("Custom negatable", func(t *testing.T) { + t.Parallel() + cfg := &customNegatableConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{"--disable-custom"}, + expCfg: &customNegatableConfig{Custom: false}, + } + run(t, test) + }) + + // Success case: Custom negatable flag with default value works. + t.Run("Custom negatable with default", func(t *testing.T) { + t.Parallel() + cfg := &customNegatableConfig{WithValue: true} + test := &testConfig{ + cfg: cfg, + args: []string{"--disable"}, + expCfg: &customNegatableConfig{WithValue: false}, + } + run(t, test) + }) +} diff --git a/internal/gen/flag_test.go b/internal/gen/flag_test.go new file mode 100644 index 0000000..1dc4863 --- /dev/null +++ b/internal/gen/flag_test.go @@ -0,0 +1,528 @@ +package gen + +import ( + "errors" + "fmt" + "net" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + flagerrors "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/values" +) + +// +// Flag structs & test helpers -------------------------------------------------------- // + +// testConfig stores all data needed for a single test. +// This is different from flagsConfig, which is the CLI +// structure to be parsed and used. +type testConfig struct { + cfg any // Initial state of the struct before parsing arguments + expCfg any // Expected state of the struct after parsing arguments. + args []string // Command-line args + expErr1 error // flags Parse error + expErr2 error // pflag Parse error +} + +// flagsConfig is an example structure to be used to produce CLI flags. +type flagsConfig struct { + StringValue1 string + StringValue2 string `flag:"string-value-two s"` + + CounterValue1 values.Counter + + StringSliceValue1 []string + DeprecatedValue1 string `desc:"DEP_MESSAGE" flag:",deprecated"` +} + +// allPflags contains all possible types to be parsed as pflags. +type allPflags struct { + IntValue int + Int8Value int8 + Int32Value int32 + Int64Value int64 + + UintValue uint + Uint8Value uint8 + Uint16Value uint16 + Uint32Value uint32 + Uint64Value uint64 + + Float32Value float32 + Float64Value float64 + + BoolValue bool + StringValue string + DurationValue time.Duration + CountValue values.Counter + + IPValue net.IP + IPNetValue net.IPNet + + StringSliceValue []string + IntSliceValue []int +} + +// TestFlagsBase tests for a simple (old sflags) struct to be parsed. +func TestFlagsBase(t *testing.T) { + t.Parallel() + + // Test setup + test := &testConfig{ + cfg: &flagsConfig{ + StringValue1: "string_value1_value", + StringValue2: "string_value2_value", + + CounterValue1: 1, + + StringSliceValue1: []string{"one", "two"}, + }, + expCfg: &flagsConfig{ + StringValue1: "string_value1_value2", + StringValue2: "string_value2_value2", + + CounterValue1: 3, + + StringSliceValue1: []string{ + "one2", "two2", "three", "4", + }, + }, + args: []string{ + "--string-value1", "string_value1_value2", + "--string-value-two", "string_value2_value2", + "--counter-value1", "--counter-value1", + "--string-slice-value1", "one2", + "--string-slice-value1", "two2", + "--string-slice-value1", "three,4", + }, + } + + run(t, test) +} + +// TestParseNoArgs tests that no arguments +// passed as command-line invocation works. +func TestParseNoArgs(t *testing.T) { + t.Parallel() + + test := &testConfig{ + cfg: &flagsConfig{ + StringValue1: "string_value1_value", + StringValue2: "", + }, + expCfg: &flagsConfig{ + StringValue1: "string_value1_value", + StringValue2: "", + }, + args: []string{}, + } + + run(t, test) +} + +// TestPFlagGetters tests that pflag getter functions like GetInt work as expected. +func TestPFlagGetters(t *testing.T) { + _, ipNet, err := net.ParseCIDR("127.0.0.1/24") + require.NoError(t, err) + + cfg := &allPflags{ + IntValue: 10, + Int8Value: 11, + Int32Value: 12, + Int64Value: 13, + UintValue: 14, + Uint8Value: 15, + Uint16Value: 16, + Uint32Value: 17, + Uint64Value: 18, + + Float32Value: 19.1, + Float64Value: 20.1, + + BoolValue: true, + StringValue: "stringValue", + DurationValue: time.Second * 10, + CountValue: 30, + + IPValue: net.ParseIP("127.0.0.1"), + IPNetValue: *ipNet, + + StringSliceValue: []string{"one", "two"}, + IntSliceValue: []int{10, 20}, + } + + parseOptions := parser.ParseAll() + + cmd, err := Generate(cfg, parseOptions) + flagSet := cmd.Flags() + require.NoError(t, err) + + intValue, err := flagSet.GetInt("int-value") + require.NoError(t, err) + assert.Equal(t, 10, intValue) + + int8Value, err := flagSet.GetInt8("int8-value") + require.NoError(t, err) + assert.Equal(t, int8(11), int8Value) + + int32Value, err := flagSet.GetInt32("int32-value") + require.NoError(t, err) + assert.Equal(t, int32(12), int32Value) + + int64Value, err := flagSet.GetInt64("int64-value") + require.NoError(t, err) + assert.Equal(t, int64(13), int64Value) + + uintValue, err := flagSet.GetUint("uint-value") + require.NoError(t, err) + assert.Equal(t, uint(14), uintValue) + + uint8Value, err := flagSet.GetUint8("uint8-value") + require.NoError(t, err) + assert.Equal(t, uint8(15), uint8Value) + + uint16Value, err := flagSet.GetUint16("uint16-value") + require.NoError(t, err) + assert.Equal(t, uint16(16), uint16Value) + + uint32Value, err := flagSet.GetUint32("uint32-value") + require.NoError(t, err) + assert.Equal(t, uint32(17), uint32Value) + + uint64Value, err := flagSet.GetUint64("uint64-value") + require.NoError(t, err) + assert.Equal(t, uint64(18), uint64Value) + + float32Value, err := flagSet.GetFloat32("float32-value") + require.NoError(t, err) + assert.Equal(t, float32(19.1), float32Value) + + float64Value, err := flagSet.GetFloat64("float64-value") + require.NoError(t, err) + assert.Equal(t, float64(20.1), float64Value) + + boolValue, err := flagSet.GetBool("bool-value") + require.NoError(t, err) + assert.True(t, boolValue) + + countValue, err := flagSet.GetCount("count-value") + require.NoError(t, err) + assert.Equal(t, 30, countValue) + + durationValue, err := flagSet.GetDuration("duration-value") + require.NoError(t, err) + assert.Equal(t, time.Second*10, durationValue) + + stringValue, err := flagSet.GetString("string-value") + require.NoError(t, err) + assert.Equal(t, "stringValue", stringValue) + + ipValue, err := flagSet.GetIP("ip-value") + require.NoError(t, err) + assert.Equal(t, net.ParseIP("127.0.0.1"), ipValue) + + ipNetValue, err := flagSet.GetIPNet("ip-net-value") + require.NoError(t, err) + assert.Equal(t, cfg.IPNetValue, ipNetValue) + + stringSliceValue, err := flagSet.GetStringSlice("string-slice-value") + require.NoError(t, err) + assert.Equal(t, []string{"one", "two"}, stringSliceValue) + + intSliceValue, err := flagSet.GetIntSlice("int-slice-value") + require.NoError(t, err) + assert.Equal(t, []int{10, 20}, intSliceValue) +} + +// TestParseShortOptions checks that flags +// invoked as short options correctly parse. +func TestParseShortOptions(t *testing.T) { + t.Parallel() + + test := &testConfig{ + cfg: &flagsConfig{ + StringValue2: "string_value2_value", + }, + expCfg: &flagsConfig{ + StringValue2: "string_value2_value2", + }, + args: []string{ + "-s=string_value2_value2", + }, + } + + run(t, test) +} + +// TestParseBadOptions checks that flag invoked while not +// existing in the struct will correctly error out. +func TestParseBadOptions(t *testing.T) { + t.Parallel() + + test := &testConfig{ + cfg: &flagsConfig{ + StringValue1: "string_value1_value", + }, + args: []string{ + "--bad-value=string_value1_value2", + }, + expErr2: errors.New("unknown flag: --bad-value"), + } + + run(t, test) +} + +// TestParseNoDefaultValues checks that flags that do NOT specify +// their default values will leave their current state untouched. +func TestParseNoDefaultValues(t *testing.T) { + t.Parallel() + + test := &testConfig{ + cfg: &flagsConfig{}, + expCfg: &flagsConfig{ + StringValue1: "string_value1_value2", + StringValue2: "string_value2_value2", + + CounterValue1: 3, + }, + args: []string{ + "--string-value1", "string_value1_value2", + "--string-value-two", "string_value2_value2", + "--counter-value1=2", "--counter-value1", + }, + } + + run(t, test) +} + +// TestParseBadConfig checks that unsupported types are correctly rejected. +func TestParseBadConfig(t *testing.T) { + t.Parallel() + + pointerErr := fmt.Errorf("%w: %w", flagerrors.ErrParse, flagerrors.ErrNotPointerToStruct) + test := &testConfig{ + cfg: "bad config", + expErr1: pointerErr, + } + + run(t, test) +} + +// +// Exported/unexported Fields Tests -------------------------------------------- // +// + +// TestUnexportedFields verifies that fields that are not exported but have tags are rejected. +func TestUnexportedFields(t *testing.T) { + t.Parallel() + + type unexportedPositional struct { + first string `positional-args:"yes"` + second string + } + + type unexportedCommand struct { + unexportedPositional `command:"pos"` + } + + type unexportedGroup struct { + flag bool `long:"flag"` + } + + tests := []struct { + name string + spec any + expErr string + wantErr bool + }{ + { + name: "unexported flag", + spec: &struct { + unexported bool `long:"unexported"` + }{}, + expErr: "unexported field: field 'unexported' is not exported but has tags: long", + wantErr: true, + }, + { + name: "unexported command", + spec: &struct { + cmd unexportedCommand `command:"cmd"` + }{}, + expErr: "unexported field: field 'cmd' is not exported but has tags: command", + wantErr: true, + }, + { + name: "unexported group", + spec: &struct { + group unexportedGroup `group:"group"` + }{}, + expErr: "unexported field: field 'group' is not exported but has tags: group", + wantErr: true, + }, + { + name: "unexported positional", + spec: &struct { + pos unexportedPositional `positional-args:"true"` + }{}, + expErr: "unexported field: field 'pos' is not exported but has tags: positional-args", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + parseOptions := parser.ParseAll() + _, err := Generate(tt.spec, parseOptions) + + if tt.wantErr { + require.Error(t, err) + assert.Contains(t, err.Error(), tt.expErr) + } else { + require.NoError(t, err) + } + }) + } +} + +// TestInvalidFlagType verifies that a custom flag type that does not +// implement the flags.Value interface returns an error. +func TestInvalidFlagType(t *testing.T) { + t.Parallel() + + type customValue struct { + Value string + } + + type invalidFlagTypeConfig struct { + Invalid customValue `long:"invalid"` + } + + cfg := &invalidFlagTypeConfig{} + _, err := Generate(cfg) + + require.Error(t, err) + assert.Contains(t, err.Error(), "parse error: field marked as flag does not implement flags.Value: field 'Invalid' is a struct but ParseAll is not enabled") +} + +// TestUserDefinedTypes verifies that custom types that do not implement the +// flags.Value interface but are of a kind supported by the reflective +// value wrapper, are correctly accepted and parsed. +func TestUserDefinedTypes(t *testing.T) { + t.Parallel() + + type customString string + type ipList []net.IP + type tcpAddrMap map[string]*net.TCPAddr + + type userDefinedTypesConfig struct { + Custom customString `long:"custom"` + IPs ipList `long:"ips"` + TCPAddrs tcpAddrMap `long:"tcp-addrs"` + PosArgs struct { + Custom customString `positional-arg-name:"custom"` + } `positional-args:"true"` + } + + host1Addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") + require.NoError(t, err) + + host2Addr, err := net.ResolveTCPAddr("tcp", "10.0.0.2:9090") + require.NoError(t, err) + + test := &testConfig{ + cfg: &userDefinedTypesConfig{}, + expCfg: &userDefinedTypesConfig{ + Custom: "mycustomstring", + IPs: ipList{net.ParseIP("192.168.1.1"), net.ParseIP("10.0.0.1")}, + TCPAddrs: tcpAddrMap{ + "host1": host1Addr, + "host2": host2Addr, + }, + PosArgs: struct { + Custom customString `positional-arg-name:"custom"` + }{ + Custom: "anothercustomstring", + }, + }, + args: []string{ + "--custom=mycustomstring", + "--ips=192.168.1.1", + "--ips=10.0.0.1", + "--tcp-addrs=host1:127.0.0.1:8080", + "--tcp-addrs=host2:10.0.0.2:9090", + "anothercustomstring", + }, + } + + run(t, test) +} + +// +// Environment Variable Tests -------------------------------------------------- // +// + +type envConfig struct { + Single string `env:"SINGLE_VAR" long:"single"` + Fallback string `env:"PRIMARY_VAR,SECONDARY_VAR" long:"fallback"` + Override string `env:"OVERRIDE_VAR" long:"override"` + Disabled string `env:"-" long:"disabled"` +} + +// TestEnvVars verifies the behavior of ENV values specified +// in struct tags, or through overrides with flag arguments. +func TestEnvVars(t *testing.T) { + // Success case: A single env var provides the default value. + t.Run("Single env var", func(t *testing.T) { + t.Setenv("SINGLE_VAR", "value_from_env") + cfg := &envConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{}, + expCfg: &envConfig{Single: "value_from_env"}, + } + run(t, test) + }) + + // Success case: The second env var in a fallback list is used. + t.Run("Fallback env var", func(t *testing.T) { + t.Setenv("SECONDARY_VAR", "value_from_fallback") + cfg := &envConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{}, + expCfg: &envConfig{Fallback: "value_from_fallback"}, + } + run(t, test) + }) + + // Success case: A command-line arg overrides the env var. + t.Run("Argument overrides env var", func(t *testing.T) { + t.Setenv("OVERRIDE_VAR", "value_from_env") + cfg := &envConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{"--override", "value_from_arg"}, + expCfg: &envConfig{Override: "value_from_arg"}, + } + run(t, test) + }) + + // Success case: `env:"-"` disables env var lookup. + t.Run("Disabled env var", func(t *testing.T) { + t.Setenv("DISABLED", "value_from_env") + cfg := &envConfig{} + test := &testConfig{ + cfg: cfg, + args: []string{}, + expCfg: &envConfig{}, // Expect the zero value + } + run(t, test) + }) +} diff --git a/gen/flags/flags.go b/internal/gen/flags.go similarity index 54% rename from gen/flags/flags.go rename to internal/gen/flags.go index ef3ef5f..e8531aa 100644 --- a/gen/flags/flags.go +++ b/internal/gen/flags.go @@ -11,73 +11,101 @@ // parsing options from the root one, to use the following import statement: // // import ( -// "github.com/reeflective/flags" -// gen "github.com/reeflective/gen/flags" +// +// "github.com/reeflective/flags" +// gen "github.com/reeflective/gen/flags" +// // ) // // B) Retrocompatiblity // For library users coming from github.com/octago/sflags: // - When parsing structs with no tags (in which case every field is a flag), -// the option `flags.ParseAll()` should be passed to the `Generate()` call. -// +// the option `flags.ParseAll()` should be passed to the `ParseCommands()` call. // // 2 - Valid tags ************************************************************************ // // A) Commands ------------------------------------------------------------------- +// // command: When specified on a struct field, makes the struct -// field a (sub)command with the given name (optional). -// Note that a struct marked as a command does not mandatorily -// have to implement the `flags.Commander` interface. +// +// field a (sub)command with the given name (optional). +// Note that a struct marked as a command does not mandatorily +// have to implement the `flags.Commander` interface. +// // subcommands-optional: When specified on a command struct field, makes -// any subcommands of that command optional (optional) +// +// any subcommands of that command optional (optional) +// // alias: When specified on a command struct field, adds the -// specified name as an alias for the command. Can be -// be specified multiple times to add more than one -// alias (optional) +// +// specified name as an alias for the command. Can be +// specified multiple times to add more than one +// alias (optional) +// // group: If the group name is not nil, this command will be -// grouped under this heading in the help usage. // +// grouped under this heading in the help usage. // // B) Flags ---------------------------------------------------------------------- // // a) github.com/jessevdk/go-flags tag specifications (some have been removed): // // flag: Short and/or long names for the flag, space-separated. -// (ex: `flag:"-v --verbose`). +// +// (ex: `flag:"-v --verbose`). +// // short: The short name of the option (single character) // long: The long name of the option // required: If non empty, makes the option required to appear on the command -// line. If a required option is not present, the parser will -// return ErrRequired (optional) +// +// line. If a required option is not present, the parser will +// return ErrRequired (optional) +// // description: The description of the option (optional) // desc: Same as 'description' // long-description: The long description of the option. Currently only -// displayed in generated man pages (optional) +// +// displayed in generated man pages (optional) +// // no-flag: If non-empty, this field is ignored as an option (optional) // optional: If non-empty, makes the argument of the option optional. When an -// argument is optional it can only be specified using -// --option=argument (optional) +// +// argument is optional it can only be specified using +// --option=argument (optional) +// // optional-value: The value of an optional option when the option occurs -// without an argument. This tag can be specified multiple -// times in the case of maps or slices (optional) +// +// without an argument. This tag can be specified multiple +// times in the case of maps or slices (optional) +// // default: The default value of an option. This tag can be specified -// multiple times in the case of slices or maps (optional) +// +// multiple times in the case of slices or maps (optional) +// // default-mask: When specified, this value will be displayed in the help -// instead of the actual default value. This is useful -// mostly for hiding otherwise sensitive information from -// showing up in the help. If default-mask takes the special -// value "-", then no default value will be shown at all -// (optional) +// +// instead of the actual default value. This is useful +// mostly for hiding otherwise sensitive information from +// showing up in the help. If default-mask takes the special +// value "-", then no default value will be shown at all +// (optional) +// // env: The default value of the option is overridden from the -// specified environment variable, if one has been defined. -// (optional) +// +// specified environment variable, if one has been defined. +// (optional) +// // env-delim: The 'env' default value from environment is split into -// multiple values with the given delimiter string, use with -// slices and maps (optional) +// +// multiple values with the given delimiter string, use with +// slices and maps (optional) +// // choice: Limits the values for an option to a set of values. -// You can either specify multiple values in a single tag -// if they are space-separated, and/or with multiple tags. -// (e.g. `long:"animal" choice:"cat bird" choice:"dog"`) +// +// You can either specify multiple values in a single tag +// if they are space-separated, and/or with multiple tags. +// (e.g. `long:"animal" choice:"cat bird" choice:"dog"`) +// // hidden: If non-empty, the option is not visible in the help or man page. // // b) github.com/octago/sflags tag specification: @@ -89,89 +117,100 @@ // `flag:",hidden"` This field will be removed from generated help text. // `flag:",deprecated"` This field will be marked as deprecated in generated help text // -// // C) Positionals ---------------------------------------------------------------- // // The following tags can/must be specified on the struct containing positional args: // // positional-args: When specified on a field with a struct type, -// uses the fields of that struct to parse remaining -// positional command line arguments into (in order -// of the fields). -// Positional arguments are optional by default, -// unless the "required" tag is specified together -// with the "positional-args" tag. +// +// uses the fields of that struct to parse remaining +// positional command line arguments into (in order +// of the fields). +// Positional arguments are optional by default, +// unless the "required" tag is specified together +// with the "positional-args" tag. // // required: If non empty, will make ALL of the fields in the positional -// struct to be required. However, each field can still specify -// its own quantity requirements/range if its a slice/map. -// If you can, please check at the online documentation for various -// examples of positional declaration and their behavior. +// +// struct to be required. However, each field can still specify +// its own quantity requirements/range if its a slice/map. +// If you can, please check at the online documentation for various +// examples of positional declaration and their behavior. // // The following tags can be specified on each individual field of a positional struct: // // positional-arg-name: used on a field in a positional argument struct; name -// of the positional argument placeholder to be shown in -// the help (optional) +// +// of the positional argument placeholder to be shown in +// the help (optional) // // description: The description of the argument (optional) // // required: The "required" tag can be set on each argument field. -// If it is set on a slice of map field, then its value -// determines the minimum amount of rest arguments that -// needs to be provided (e.g. `required:"2"`). -// You can also specify a range (e.g. `required:"1-3"`). -// When several fields are slices/or arrays, they may still -// each declare ranges (even if overlapping). When that is -// the case, the slices are filled from first to last. -// Ex: -// struct { -// List []string `required:"1-2"` -// Other []string `required:"1-2"` -// Final string `required:"yes"` -// } -// If given ["one", "two", "three", "four"], final will have -// "four", Other will have ["three"], and List will have ["one", "two"]. -// -// When the last field is a slice/map with no maximum, then it -// will hold all excess arguments. On the contrary, and as general -// rule, all arguments not fitting into the struct fields will be -// given as args to the command's `Execute(args []string)` function. -// -// Also, and when a double dash is passed in the arguments, -// all args after the dash will not be parsed into struct fields. -// If those fields' requirements are not satisfied, however, they -// will throw an error. -// Various examples of positional arguments declaration can be found -// on the online documentation. // +// If it is set on a slice of map field, then its value +// determines the minimum amount of rest arguments that +// needs to be provided (e.g. `required:"2"`). +// You can also specify a range (e.g. `required:"1-3"`). +// When several fields are slices/or arrays, they may still +// each declare ranges (even if overlapping). When that is +// the case, the slices are filled from first to last. +// Ex: +// struct { +// List []string `required:"1-2"` +// Other []string `required:"1-2"` +// Final string `required:"yes"` +// } +// If given ["one", "two", "three", "four"], final will have +// "four", Other will have ["three"], and List will have ["one", "two"]. +// +// When the last field is a slice/map with no maximum, then it +// will hold all excess arguments. On the contrary, and as general +// rule, all arguments not fitting into the struct fields will be +// given as args to the command's `Execute(args []string)` function. +// +// Also, and when a double dash is passed in the arguments, +// all args after the dash will not be parsed into struct fields. +// If those fields' requirements are not satisfied, however, they +// will throw an error. +// Various examples of positional arguments declaration can be found +// on the online documentation. // // D) Groups (of flags or commands) ---------------------------------------------- // // group: When specified on a struct field, makes the struct -// field a separate flags group with the given name (optional). +// +// field a separate flags group with the given name (optional). +// // commands: When specified on a struct field containing commands, -// the value of the tag is used as a name to group commands -// together in the help usage. +// +// the value of the tag is used as a name to group commands +// together in the help usage. +// // namespace: When specified on a group struct field, the namespace -// gets prepended to every option's long name and -// subgroup's namespace of this group, separated by -// the parser's namespace delimiter (optional) (flags only) +// +// gets prepended to every option's long name and +// subgroup's namespace of this group, separated by +// the parser's namespace delimiter (optional) (flags only) +// // env-namespace: When specified on a group struct field, the env-namespace -// gets prepended to every option's env key and -// subgroup's env-namespace of this group, separated by -// the parser's env-namespace delimiter (optional) (flags only) +// +// gets prepended to every option's env key and +// subgroup's env-namespace of this group, separated by +// the parser's env-namespace delimiter (optional) (flags only) +// // persistent: If non-empty, all flags belonging to this group will be -// persistent across subcommands. // +// persistent across subcommands. // // D) Completions (flags or positionals) ------------------------------------------- // // a) Tagged completions // // complete: This is the only tag required to provide completions for a given positional -// argument or flag struct field. The following directives and formattings are -// are accepted (all directives can also be written as lowercase): +// +// argument or flag struct field. The following directives and formattings are +// accepted (all directives can also be written as lowercase): // // `FilterExt` only complete files that are part of the given extensions. // ex: `complete:"FilterExt,json,go,yaml"` will only propose JSON/Go/YAML files. @@ -203,12 +242,11 @@ // // Please check https://rsteube.github.io/carapace/carapace.html for library usage information. // -// // E) Validations ------------------------------------------------------------------ // // All positionals and flags struct fields can also declare validations compliant with // "github.com/go-playground/validator/v10" tag specifications, and provided that the -// following parsing option is given to the `Generate()` call: +// following parsing option is given to the `ParseCommands()` call: // // flags.Validator(validator.New()) // @@ -218,5 +256,4 @@ // // Check the documentation for adding other custom validations directly through the // go-validator engine. -// -package flags +package gen diff --git a/internal/gen/gen.go b/internal/gen/gen.go new file mode 100644 index 0000000..aef2f70 --- /dev/null +++ b/internal/gen/gen.go @@ -0,0 +1,124 @@ +package gen + +import ( + "fmt" + "os" + "reflect" + + "github.com/carapace-sh/carapace" + "github.com/spf13/cobra" + + "github.com/reeflective/flags/internal/completions" + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/positional" +) + +// context holds all the necessary information for scanning and building a command. +type context struct { + cmd *cobra.Command + group *cobra.Group + opts *parser.Opts + defaultCommand *cobra.Command + positionals *positional.Args + Flags []*parser.Flag + comps *carapace.Carapace + flagComps map[string]carapace.Action +} + +func (c *context) bindCompletions() { + // Flags + if len(c.flagComps) > 0 { + c.comps.FlagCompletion(carapace.ActionMap(c.flagComps)) + } + + // Positionals + completions.BindPositionals(c.comps, c.positionals, c.opts) +} + +// Generate returns a root cobra Command to be used directly as an entry-point. +// If any error arises in the scanning process, this function will return a nil +// command and the error. +func Generate(data any, opts ...parser.OptFunc) (*cobra.Command, error) { + cmd := &cobra.Command{ + Use: os.Args[0], + Annotations: map[string]string{}, + TraverseChildren: true, + } + + // Scan the struct and bind all commands to this root. + if err := Bind(cmd, data, opts...); err != nil { + return nil, err + } + + return cmd, nil +} + +// Bind uses a virtual root struct to unify the parsing logic for the root command +// and subcommands, ensuring that positionals and run functions are handled consistently. +func Bind(cmd *cobra.Command, data any, opts ...parser.OptFunc) error { + // Create a dynamic struct type: struct { RootCmd any `command:"" ... } + tag := fmt.Sprintf(`command:"%s"`, cmd.Use) + structType := reflect.StructOf([]reflect.StructField{ + { + Name: "RootCmd", + Type: reflect.TypeOf(data), + Tag: reflect.StructTag(tag), + }, + }) + + // Create an instance of the new struct type. + virtualRoot := reflect.New(structType) + virtualRoot.Elem().Field(0).Set(reflect.ValueOf(data)) + + // The context now operates on the root command. + ctx := &context{ + cmd: cmd, + opts: parser.DefOpts().Apply(opts...), + comps: carapace.Gen(cmd), + } + + // Scan the virtual root. The commandV2 function will be triggered for the + // RootCmd field, and it will configure the main `cmd` as the root command. + scanner := newFieldScanner(ctx) + if err := parser.Scan(virtualRoot.Interface(), scanner); err != nil { + return fmt.Errorf("%w: %w", errors.ErrParse, err) + } + + return nil +} + +// newFieldScanner is in charge of building a recursive scanner, working on a given +// struct field at a time, checking for arguments, subcommands and option groups. +func newFieldScanner(ctx *context) parser.Handler { + handler := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { + // Parse the tag or die tryin. We should find one, or we're not interested. + mtag, _, err := parser.GetFieldTag(*sfield) + if err != nil { + return true, fmt.Errorf("%w: %s", errors.ErrInvalidTag, err.Error()) + } + + // If the field is marked as -one or more- positional arguments, we + // return either on a successful scan of them, or with an error doing so. + if found, perr := positionals(ctx, mtag, val); found || perr != nil { + return found, perr + } + + // Else, if the field is marked as a subcommand, we either return on + // a successful scan of the subcommand, or with an error doing so. + if found, cerr := command(ctx, mtag, val); found || cerr != nil { + return found, cerr + } + + // Else, if the field is a struct group of options + if found, ferr := flagsGroup(ctx, val, sfield); found || ferr != nil { + return found, err + } + + // Finally, it might be either a struct container for various flags, + // a field for a single flag, or a field for a single positional. + return flagsOrPositional(ctx)(val, sfield) + } + + return handler +} diff --git a/internal/gen/group.go b/internal/gen/group.go new file mode 100644 index 0000000..cfb13a0 --- /dev/null +++ b/internal/gen/group.go @@ -0,0 +1,184 @@ +package gen + +import ( + "fmt" + "reflect" + + "github.com/carapace-sh/carapace" + "github.com/spf13/cobra" + + "github.com/reeflective/flags/internal/completions" + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/parser" +) + +// flagsGroup finds if a field is marked as a subgroup of options or commands, +// and if so, dispatches to the appropriate handler. +func flagsGroup(ctx *context, val reflect.Value, field *reflect.StructField) (bool, error) { + mtag, skip, err := parser.GetFieldTag(*field) + if err != nil { + return true, fmt.Errorf("%w: %s", errors.ErrParse, err.Error()) + } + if skip { + return false, nil + } + + // Check for a standard flag group first. + if _, isSet := mtag.Get("group"); isSet { + return true, handleFlagGroup(ctx, val, field, mtag) + } + if _, isSet := mtag.Get("options"); isSet { + return true, handleFlagGroup(ctx, val, field, mtag) + } + + // Check for a command group. + if commandGroup, isSet := mtag.Get("commands"); isSet { + return true, handleCommandGroup(ctx, val, commandGroup) + } + + return false, nil +} + +// handleFlagGroup handles the scanning of a struct field that is a group of flags. +// It uses the parser to get a list of flags and then generates them to the command's flag set. +func handleFlagGroup(ctx *context, val reflect.Value, fld *reflect.StructField, tag *parser.Tag) error { + // Let's create a new context for this field + fieldCtx, err := parser.NewFieldContext(val, *fld, ctx.opts) + if err != nil || fieldCtx == nil { + return err + } + + // 1. Call the new parser.ParseGroup to get the list of flags. + flags, _, err := parser.ParseGroup(fieldCtx) + if err != nil { + return err + } + + if persistent, _ := tag.Get("persistent"); persistent != "" { + for _, flag := range flags { + flag.Persistent = true + } + } + + // 2. Collect the parsed flags for post-processing (e.g., XOR). + ctx.Flags = append(ctx.Flags, flags...) + + // 3. Generate the parsed flags into the command's flag set. + generateTo(flags, ctx.cmd) + + // And add their completions to the context. + if len(flags) > 0 { + for _, flag := range flags { + if comp, found := buildFlagCompleter(flag, ctx.opts); found { + ctx.flagComps[flag.Name] = comp + } + } + } + + return nil +} + +// handleCommandGroup handles the scanning of a struct field that is a group of commands. +func handleCommandGroup(ctx *context, val reflect.Value, commandGroup string) error { + ptrval := parser.EnsureAddr(val) + + var group *cobra.Group + if !parser.IsStringFalsy(commandGroup) { + group = &cobra.Group{ + ID: commandGroup, + Title: commandGroup, + } + ctx.cmd.AddGroup(group) + } + + // Parse for commands within the group. + subCtx := &context{ + cmd: ctx.cmd, + group: group, + opts: ctx.opts, + } + scannerCommand := newFieldScanner(subCtx) + + if err := parser.Scan(ptrval.Interface(), scannerCommand); err != nil { + return fmt.Errorf("failed to scan command group: %w", err) + } + + return nil +} + +// flagsOrPositional builds a small struct field handler so that we can scan +// it as a flag, a group of them or a Kong-style positional argument slot. +func flagsOrPositional(ctx *context) parser.Handler { + flagScanner := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { + // Parse a field (which might be a struct container), for either one or + // more flags, or even a struct field (Kong-style) positional argument. + flags, pos, found, err := parser.ParseField(val, *sfield, ctx.opts) + if err != nil { + return true, err + } + if !found { + return false, nil + } + + // Either we found flags, add them to the command. + if len(flags) > 0 { + ctx.Flags = append(ctx.Flags, flags...) + generateTo(flags, ctx.cmd) + + // And add their completions to the context. + for _, flag := range flags { + if comp, found := buildFlagCompleter(flag, ctx.opts); found { + ctx.flagComps[flag.Name] = comp + } + } + } + + // Or a positional argument, and add it + // to the positional arguments manager. + if pos != nil { + ctx.positionals.Add(pos) + } + + return true, nil + } + + return flagScanner +} + +func buildFlagCompleter(flag *parser.Flag, opts *parser.Opts) (carapace.Action, bool) { + // Get the combined completer from the type and the struct tag. + completer, isRepeatable, _ := completions.GetCombinedCompletionAction(flag.RValue, *flag.Tag, opts) + + // Check if the flag has some choices: if yes, we simply overwrite + // the completer implementation with a builtin one. + if choices := completions.ChoiceCompletions(*flag.Tag, flag.RValue); choices != nil { + completer = choices + } + + // We are done if no completer is found whatsoever. + if completer == nil { + return carapace.Action{}, false + } + + action := carapace.ActionCallback(completer) + + // INFO: Map separator (FOR NOW, NOT REALLY NEEDED) + // if flag.RValue.Kind() == reflect.Map && flag.MapSeparator != nil { + // action = action.MultiPartsP + // } + + // Then, and irrespectively of where the completer comes from, + // we adapt it considering the kind of type we're dealing with. + if isRepeatable { + + // List separator + separator := "," + if flag.Separator != nil && *flag.Separator != "none" { + separator = *flag.Separator + } + action = action.UniqueList(separator) + + } + + return action, true +} diff --git a/gen/flags/pointer_test.go b/internal/gen/pointer_test.go similarity index 87% rename from gen/flags/pointer_test.go rename to internal/gen/pointer_test.go index b7fe14c..e335727 100644 --- a/gen/flags/pointer_test.go +++ b/internal/gen/pointer_test.go @@ -1,4 +1,4 @@ -package flags +package gen import ( "testing" @@ -48,6 +48,7 @@ type pointerGroup struct { // types (except structs) correctly parse their command-line values. func TestPointerPrimitiveFlags(t *testing.T) { t.Parallel() + test := assert.New(t) data := pointerRoot{} args := []string{ @@ -62,12 +63,13 @@ func TestPointerPrimitiveFlags(t *testing.T) { "-m", "k1:2", "-m", "k2:-5", } - root := newCommandWithArgs(&data, args) + root, err := newCommandWithArgs(&data, args) + test.NoError(err, "Command should have been generated successfully") + cmd, err := root.ExecuteC() - test := assert.New(t) test.NotNil(cmd) - test.Nil(err, "Command should have exited successfully") + test.NoError(err, "Command should have exited successfully") test.True(*data.Bool, "flag -v should be true") test.Equal("strVal", *data.String) @@ -85,12 +87,12 @@ func TestPointerGroup(t *testing.T) { Group *pointerGroup `group:"Group Options"` }{} - root := newCommandWithArgs(&opts, []string{"-v"}) + root, err := newCommandWithArgs(&opts, []string{"-v"}) cmd, err := root.ExecuteC() test := assert.New(t) test.NotNil(cmd) - test.Nil(err, "Command should have exited successfully") + test.NoError(err, "Command should have exited successfully") test.NotNil(opts.Group) test.True(opts.Group.Value, "flag -v should be true") } @@ -101,12 +103,12 @@ func TestDoNotChangeNonTaggedFields(t *testing.T) { t.Parallel() opts := pointerGroup{} - root := newCommandWithArgs(&opts, []string{"-v"}) + root, err := newCommandWithArgs(&opts, []string{"-v"}) cmd, err := root.ExecuteC() test := assert.New(t) test.NotNil(cmd) - test.Nil(err, "Command should have exited successfully") + test.NoError(err, "Command should have exited successfully") test.Nil(opts.A.Pointer, "expected A.Pointer to be nil") test.Nil(opts.B, "expected B struct to be nil") } diff --git a/internal/gen/positional.go b/internal/gen/positional.go new file mode 100644 index 0000000..01e108d --- /dev/null +++ b/internal/gen/positional.go @@ -0,0 +1,38 @@ +package gen + +import ( + "reflect" + + "github.com/reeflective/flags/internal/parser" + "github.com/reeflective/flags/internal/positional" +) + +// positionals finds a struct tagged as containing positionals arguments and scans them. +func positionals(ctx *context, stag *parser.Tag, val reflect.Value) (bool, error) { + // We need the struct to be marked as such + if pargs, _ := stag.Get("positional-args"); len(pargs) == 0 { + return false, nil + } + + // Scan all the fields on the struct and build the list of arguments + // with their own requirements, and references to their values. + args, err := positional.ParseStruct(val, stag, parser.CopyOpts(ctx.opts)) + if err != nil || args == nil { + return true, err + } + + // Merge the metadata from the temporary manager to the main one. + if args.SoftPassthrough { + ctx.positionals.SoftPassthrough = true + } + if args.AllRequired { + ctx.positionals.AllRequired = true + } + + // Add the scanned arguments to the context's positional manager. + for _, arg := range args.Positionals() { + ctx.positionals.Add(arg) + } + + return true, nil +} diff --git a/internal/gen/positional_kong_test.go b/internal/gen/positional_kong_test.go new file mode 100644 index 0000000..a00cb81 --- /dev/null +++ b/internal/gen/positional_kong_test.go @@ -0,0 +1,252 @@ +package gen + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// +// Test Structs +// + +type kongSinglePositional struct { + Arg1 string `arg:"" required:"true"` +} + +// func (k *kongSinglePositional) Execute(args []string) error { +// return nil +// } + +type kongMultiplePositional struct { + Arg1 string `arg:"" required:"true"` + Arg2 int `arg:"" required:"true"` +} + +// func (k *kongMultiplePositional) Execute(args []string) error { +// return nil +// } + +type kongOptionalPositional struct { + Arg1 string `arg:"" optional:"true"` +} + +// func (k *kongOptionalPositional) Execute(args []string) error { +// return nil +// } + +type kongSlicePositional struct { + Arg1 []string `arg:""` +} + +// func (k *kongSlicePositional) Execute(args []string) error { +// return nil +// } + +type legacyMixed struct { + Arg2 string + Arg3 string +} + +type kongMixedKongFirst struct { + Arg1 string `arg:"" required:"true"` + PositionalArgs legacyMixed `positional-args:"true" required:"true"` +} + +// func (k *kongMixedKongFirst) Execute(args []string) error { +// return nil +// } + +type legacyMixed2 struct { + Arg1 string + Arg2 bool +} + +type kongMixedGoFlagsFirst struct { + PositionalArgs legacyMixed2 `positional-args:"true" required:"true"` + Arg3 int `arg:"" required:"true"` +} + +// func (k *kongMixedGoFlagsFirst) Execute(args []string) error { +// return nil +// } + +type kongPassthrough struct { + Flag bool `long:"flag"` + Passthrough []string `arg:"" passthrough:"true"` +} + +// func (k *kongPassthrough) Execute(args []string) error { +// return nil +// } + +type kongErrorMissing struct { + Arg1 string `arg:"" required:"true"` +} + +// func (k *kongErrorMissing) Execute(args []string) error { +// return nil +// } + +type kongErrorTooMany struct { + Arg1 string `arg:"" required:"true"` +} + +// func (k *kongErrorTooMany) Execute(args []string) error { +// return nil +// } + +// +// Tests +// + +// TestKongSingleRequiredPositional verifies that a single, required positional argument +// is correctly parsed and assigned. +func TestKongSingleRequiredPositional(t *testing.T) { + cfg := &kongSinglePositional{} + test := &testConfig{ + cfg: cfg, + args: []string{"value1"}, + expCfg: &kongSinglePositional{Arg1: "value1"}, + } + run(t, test) +} + +// TestKongMultipleRequiredPositionals checks that multiple required positional arguments +// are parsed in the correct order. +func TestKongMultipleRequiredPositionals(t *testing.T) { + cfg := &kongMultiplePositional{} + test := &testConfig{ + cfg: cfg, + args: []string{"value1", "123"}, + expCfg: &kongMultiplePositional{Arg1: "value1", Arg2: 123}, + } + run(t, test) +} + +// TestKongOptionalPositional ensures that an optional positional argument is correctly +// parsed when provided, and that no error occurs when it is omitted. +func TestKongOptionalPositional(t *testing.T) { + // Case 1: Optional argument is provided. + cfg1 := &kongOptionalPositional{} + test1 := &testConfig{ + cfg: cfg1, + args: []string{"value1"}, + expCfg: &kongOptionalPositional{Arg1: "value1"}, + } + run(t, test1) + + // Case 2: Optional argument is omitted. + cfg2 := &kongOptionalPositional{} + test2 := &testConfig{ + cfg: cfg2, + args: []string{}, + expCfg: &kongOptionalPositional{}, + } + run(t, test2) +} + +// TestKongSlicePositional tests a "greedy" slice (`[]string`) positional argument +// to confirm it captures all remaining arguments. +func TestKongSlicePositional(t *testing.T) { + cfg := &kongSlicePositional{} + test := &testConfig{ + cfg: cfg, + args: []string{"a", "b", "c"}, + expCfg: &kongSlicePositional{Arg1: []string{"a", "b", "c"}}, + } + run(t, test) +} + +// TestMixedPositionalsKongFirst implements a struct with a Kong-style positional +// argument field followed by a legacy `positional-args` struct to ensure they +// are parsed correctly in sequence. +func TestMixedPositionalsKongFirst(t *testing.T) { + cfg := &kongMixedKongFirst{} + test := &testConfig{ + cfg: cfg, + args: []string{"value1", "value2", "true"}, + expCfg: &kongMixedKongFirst{ + Arg1: "value1", + PositionalArgs: legacyMixed{ + Arg2: "value2", + Arg3: "true", + }, + }, + } + run(t, test) +} + +// TestMixedPositionalsGoFlagsFirst implements a struct with a legacy `positional-args` +// struct followed by a Kong-style positional argument field to ensure correct parsing. +func TestMixedPositionalsGoFlagsFirst(t *testing.T) { + cfg := &kongMixedGoFlagsFirst{} + test := &testConfig{ + cfg: cfg, + args: []string{"value1", "true", "123"}, + expCfg: &kongMixedGoFlagsFirst{ + PositionalArgs: legacyMixed2{ + Arg1: "value1", + Arg2: true, + }, + Arg3: 123, + }, + } + run(t, test) +} + +// TestPassthroughPositional ensures that a passthrough argument (`[]string` with +// `passthrough:"true"`) correctly captures all arguments after the flags, +// including those that look like flags (e.g., `-v`). +func TestPassthroughPositional(t *testing.T) { + cfg := &kongPassthrough{} + test := &testConfig{ + cfg: cfg, + args: []string{"--flag", "arg1", "--foo", "-b", "arg2"}, + expCfg: &kongPassthrough{Flag: true, Passthrough: []string{"arg1", "--foo", "-b", "arg2"}}, + } + run(t, test) +} + +// TestPositionalArgumentErrors is a table-driven test to verify that appropriate +// errors are returned for various invalid scenarios. +func TestPositionalArgumentErrors(t *testing.T) { + tests := []struct { + name string + cfg any + args []string + expErr string + }{ + { + name: "Missing required positional", + cfg: &kongErrorMissing{}, + args: []string{}, + expErr: "required argument: `Arg1` was not provided", + }, + { + name: "Too many arguments for non-slice", + cfg: &kongErrorTooMany{}, + args: []string{"val1", "val2"}, + expErr: "too many arguments", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + test := &testConfig{ + cfg: tt.cfg, + args: tt.args, + } + cmd, err := Generate(test.cfg) + require.NoError(t, err) + cmd.SetArgs(test.args) + err = cmd.Execute() + require.Error(t, err) + + if err != nil { + assert.Contains(t, err.Error(), tt.expErr) + } + }) + } +} diff --git a/internal/gen/positional_passthrough_test.go b/internal/gen/positional_passthrough_test.go new file mode 100644 index 0000000..6c309d6 --- /dev/null +++ b/internal/gen/positional_passthrough_test.go @@ -0,0 +1,100 @@ +package gen + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/reeflective/flags/internal/positional" +) + +// +// Test structs for passthrough behavior +// + +// positionalStrict is a command with a fixed number of positional arguments. +// It should error if too many arguments are provided. +type positionalStrict struct { + PositionalArgs struct { + Arg1 string + Arg2 int + } `positional-args:"true" required:"true"` +} + +// positionalSoftPassthrough is a command that allows excess arguments +// to be passed to its Execute method. +type positionalSoftPassthrough struct { + PositionalArgs struct { + Arg1 string + Arg2 int + } `passthrough:"true" positional-args:"true" required:"true"` +} + +// positionalAmbiguousPassthrough has a container-level passthrough +// and a greedy final positional, which is an invalid configuration. +type positionalAmbiguousPassthrough struct { + PositionalArgs struct { + Arg1 string + Greedy2 []string + } `passthrough:"true" positional-args:"true"` +} + +// +// Tests +// + +// TestPositionalStrictArity verifies that a command with a fixed set of +// positional arguments errors out if too many arguments are provided. +func TestPositionalStrictArity(t *testing.T) { + cfg := &positionalStrict{} + test := &testConfig{ + cfg: cfg, + args: []string{"val1", "123", "excess", "args"}, + expErr2: errors.New("too many arguments"), + } + run(t, test) +} + +// TestPositionalSoftPassthrough verifies that a command with container-level +// passthrough enabled does not error on excess arguments and that those +// arguments are correctly captured as remaining args. +func TestPositionalSoftPassthrough(t *testing.T) { + cfg := &positionalSoftPassthrough{} + test := &testConfig{ + cfg: cfg, + args: []string{"val1", "123", "excess", "args"}, + expCfg: &positionalSoftPassthrough{ + PositionalArgs: struct { + Arg1 string + Arg2 int + }{"val1", 123}, + }, + } + + // We need a custom run to check the remaining args. + cmd, err := Generate(test.cfg) + require.NoError(t, err) + + cmd.SetArgs(test.args) + err = cmd.Execute() + require.NoError(t, err) + + assert.Equal(t, test.expCfg, test.cfg) + + // Check that the remaining arguments were passed correctly. + remaining := positional.GetRemainingArgs(cmd) + assert.Equal(t, []string{"excess", "args"}, remaining) +} + +// TestPositionalAmbiguousPassthroughError verifies that command generation +// fails if a container has passthrough enabled but also contains a greedy +// positional argument. +func TestPositionalAmbiguousPassthroughError(t *testing.T) { + cfg := &positionalAmbiguousPassthrough{} + _, err := Generate(cfg) + + require.Error(t, err) + assert.Contains(t, err.Error(), "ambiguous configuration") +} diff --git a/internal/gen/positional_test.go b/internal/gen/positional_test.go new file mode 100644 index 0000000..8f05fce --- /dev/null +++ b/internal/gen/positional_test.go @@ -0,0 +1,652 @@ +package gen + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Tests partially ported from github.com/jessevdk/go-flags/arg_test.go, +// either enhanced and simplified where needed. To these have been added +// a few ones, with more complex positional argument patterns/setups. + +// +// Tests ported from jessevdk/go-flags --------------------------------------- // +// + +// TestPositionalAllOptional is the most simple test for positional arguments, +// since none of them is required to have something. The result, however, should +// be identical to TestPositionalAllRequired. +func TestAllOptional(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Command int // 1 minimum + Filename string // 1 minimum + Rest []string // All others here + } `positional-args:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"10", "arg_test.go", "a", "b"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Execute() + test.NoErrorf(err, "Unexpected error: %v", err) + + test.Equal(10, opts.Positional.Command, "Expected opts.Positional.Command to match") + test.Equal("arg_test.go", opts.Positional.Filename, "Expected opts.Positional.Filename to match") + test.Equal([]string{"a", "b"}, opts.Positional.Rest, "Expected opts.Positional.Rest to match") +} + +// TestStructRequiredWithRestFail checks positionals without per-field tag minimum +// requirements specified, but with the struct having one. This makes all positional +// fields required with at least one word each, except the last it it's a slice. +func TestAllRequired(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Command int + Filename string + Rest []string + } `positional-args:"yes" required:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"10"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{"10"}) + + test.ErrorContains(err, "required argument: `Filename` and `Rest (at least 1 argument)` were not provided") +} + +// TestRequiredRestUndefinedFail checks that fields marked with a non-numeric +// (and non-nil, or "not falsy"), will correctly error out. +func TestRequiredRestUndefinedFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Rest []string `required:"yes"` + } `positional-args:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{}) + + test.ErrorContains(err, + "`Rest (at least 1 argument)` was not provided") +} + +// TestRequiredRestUndefinedPass checks that fields marked with a non-numeric +// (and non-nil, or "not falsy"), will accept and parse only one argument word. +func TestRequiredRestUndefinedPass(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Rest []string `required:"yes"` + } `positional-args:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"rest1"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{"rest1"}) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal("rest1", opts.Positional.Rest[0], + "Expected opts.Positional.Rest[0] to match") +} + +// TestRequiredRestQuantityPass cheks that slice/map fields marked with a numeric +// quantity - and at the last position in the positionals struct - will correctly +// fail if they are not given the minimum words they want. +func TestRequiredRestQuantityFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Rest []string `required:"2"` + } `positional-args:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"rest1"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{"rest1"}) + + test.ErrorContains(err, + "`Rest (at least 2 arguments, but got only 1)` was not provided") +} + +// TestRequiredRestQuantityPass cheks that slice/map fields marked with a numeric +// quantity will accept and parse at minimum the specified number. +func TestRequiredRestQuantityPass(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Rest []string `required:"2"` + } `positional-args:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"rest1", "rest2", "rest3"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{"rest1", "rest2", "rest3"}) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal("rest1", opts.Positional.Rest[0]) + test.Equal("rest2", opts.Positional.Rest[1]) + test.Equal("rest3", opts.Positional.Rest[2]) +} + +// TestRequiredRestRangeFail checks that the last positional field +// will correctly error out if there are words left after they have +// consumed some, up to their maximum allowed. +func TestRequiredRestRangeFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Rest []string `required:"1-2"` + } `positional-args:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"rest1", "rest2", "rest3"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{"rest1", "rest2", "rest3"}) + + test.ErrorContains(err, + "`Rest (at most 2 arguments, but got 3)`") +} + +// TestRequiredRestRangeEmptyFail checks that an incorrectly specified 0-0 range +// will actually throw an error BEFORE executing the command, not AFTER and with +// using the rest words as lambda parameters passed to the command implementation. +// +// In essence this function is just a check that internal code will not +// misinterpret some tag values in relation to all the positionals, so +// an invalid 0-0 is a good test case candidate for this. +func TestRequiredRestRangeEmptyFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + Rest []string `required:"1-0"` + } `positional-args:"yes"` + }{} + + _, err := newCommandWithArgs(&opts, []string{"some", "thing"}) + test.ErrorContains(err, "parse error: maximum number of arguments cannot be 0") +} + +// +// Added Tests (more complex cases) --------------------------------------- // +// + +// TestOptionalNonRestRangeMinimumPass checks that a slice of positionals +// that is not the last positional struct field will parse only one argument. +func TestOptionalNonRestRangeMinimumPass(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + NonRest []string + Second string + Third string + } `positional-args:"yes" required:"yes"` + }{} + + cmd, err := newCommandWithArgs(&opts, []string{"first", "second", "third"}) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, []string{"first", "second", "third"}) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal([]string{"first"}, opts.Positional.NonRest) + test.Equal("second", opts.Positional.Second) + test.Equal("third", opts.Positional.Third) +} + +// TestRequiredNonRestRangeExcessPass checks that a slice of positionals +// that is not the last positional struct field, will accept: +// - Only up to its specified maximum number. +// This is only slightly different from TestOptionalNonRestRange, +// since, we are not here trying to feed just the bare mininum of +// words to satisfy our requirements. +func TestRequiredNonRestRangeExcessPass(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + NonRest []string `required:"0-2"` + Second string + Third string + } `positional-args:"yes" required:"yes"` + }{} + + args := []string{"nonrest1", "nonrest2", "second", "third", "lambda"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.Equal([]string{"nonrest1", "nonrest2"}, opts.Positional.NonRest) + test.Equal("second", opts.Positional.Second) + test.Equal("third", opts.Positional.Third) + test.ErrorContains(err, "too many arguments") +} + +// TestRequiredNonRestRangeFail checks that a slice of positionals +// that is not the last positional struct field, after parsing words +// according to their minimum requirements, will correctly cause one +// or more of the next positional fields to raise an error. +func TestRequiredNonRestRangeFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + NonRest []string `required:"2-3"` + Second string + Third string // Third will fail + } `positional-args:"yes" required:"yes"` + }{} + + args := []string{"nonrest1", "nonrest2", "second"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.ErrorContains(err, "`Third` was not provided") +} + +// TestMixedSlicesMaximumPass checks that a struct containing +// at least two slices specifying their minimum/maximum range +// will correctly be scanned and will correctly pass their arguments. +func TestMixedSlicesMaximumPass(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + FirstList []string `required:"2-2"` + SecondList []string `required:"2-2"` + Third string + } `positional-args:"yes" required:"yes"` + }{} + + args := []string{"first1", "first2", "second1", "second2", "third"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal([]string{"first1", "first2"}, opts.Positional.FirstList) + test.Equal([]string{"second1", "second2"}, opts.Positional.SecondList) + test.Equal("third", opts.Positional.Third) +} + +// TestMixedSlicesNonRestPass checks that two slices of positionals +// will correctly parse according to their minimum/maximum number of +// words accepted, leaving the other words for next arguments. +// This test only provides the minimum valid number of argument words. +func TestMixedSlicesMinimumNonRestPass(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + FirstList []string `required:"2-3"` + SecondList []string `required:"1-2"` + Third string + } `positional-args:"yes" required:"yes"` + }{} + + args := []string{"first1", "first2", "second1", "third"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal([]string{"first1", "first2"}, opts.Positional.FirstList) + test.Equal([]string{"second1"}, opts.Positional.SecondList) + test.Equal("third", opts.Positional.Third) +} + +// TestMixedSlicesNonRestFail checks that two slices of positionals, +// after parsing words according to their minimum requirements, will +// correctly cause one or more of the next positional fields to raise +// an error. +func TestMixedSlicesMinimumNonRestFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + FirstList []string `required:"2-3"` + SecondList []string `required:"1-2"` + Third string + } `positional-args:"yes" required:"yes"` + }{} + + args := []string{"first1", "first2", "second1"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.ErrorContains(err, "`Third` was not provided") +} + +// TestMixedSlicesLastHasPriority checks that 2 slices of positionals, +// when being given less words than what their combined maximum allows, +// will: +// - Fill the slices according to their ordering in the struct: the +// fist one is being fed words until max, and then passes the words +// up to the next slice. +// - Will still respect the minimum requirements of the following fields. +// +// The function is therefore passed a number of words that is higher +// than the total minimum required, but less than the "max". +func TestMixedSlicesLastHasPriority(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + FirstList []string `required:"2-3"` + SecondList []string `required:"1-2"` + ThirdList []string `required:"1-2"` + Third string + } `positional-args:"yes" required:"yes"` + }{} + + args := []string{"first1", "first2", "second1", "third1", "third2", "single"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal([]string{"first1", "first2", "second1"}, opts.Positional.FirstList) + test.Equal([]string{"third1"}, opts.Positional.SecondList) + test.Equal([]string{"third2"}, opts.Positional.ThirdList) + test.Equal("single", opts.Positional.Third) +} + +// TestRequiredRestRangeHasPriority checks that the last slice of positional +// is always correctly filled before the first one in the struct. +func TestRequiredRestRangeHasPriority(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + First []string + Second []string `required:"2-2"` + } `positional-args:"yes"` + }{} + + args := []string{"first1", "first2", "second1", "second2"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + err = cmd.Args(cmd, args) + + test.NoErrorf(err, "Unexpected error: %v", err) + test.Equal([]string{"first1", "first2"}, opts.Positional.First) + test.Equal([]string{"second1", "second2"}, opts.Positional.Second) +} + +// TestTwoInfiniteSlicesExplicitFail checks that if a struct containing +// at least two slices that are explicitly marked infinite (no maximum), +// will return an error next to the cobra command being returned. +func TestTwoInfiniteSlicesExplicitFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Value bool `short:"v"` + + Positional struct { + FirstList []string + SecondList []string + ThirdList []string `required:"1-2"` + Third string + } `positional-args:"yes" required:"yes"` + }{} + + _, err := newCommandWithArgs(&opts, []string{}) + test.EqualError(err, "parse error: positional argument shadows subsequent arguments: positional `FirstList` is shadowed by `SecondList`, which is a greedy slice", "Error mismatch") +} + +// +// Double dash positionals (more complex cases) --------------------------------------- // +// + +type doubleDashCommand struct { + Value bool `short:"v"` + + Positional struct { + FirstList []string `required:"2-3"` + SecondList []string `required:"1-2"` + Third string + } `positional-args:"yes" required:"yes"` +} + +// Execute - The double dash command errors out when it does +// not receive some unparsed positional arguments. +func (d *doubleDashCommand) Execute(args []string) error { + if len(args) == 0 { + return errors.New("Did not receive retargs") + } + + return nil +} + +// TestPositionalDoubleDashSuccess checks that a command being fed the correct +// number of required arguments will correctly parse them into their slots, and +// that all remaining arguments after the double dash will be used as retargs. +func TestPositionalDoubleDashSuccess(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Double doubleDashCommand `command:"double-dash"` + }{} + + args := []string{"double-dash", "first1", "first2", "second1", "third1", "--", "third2", "single"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + _, err = cmd.ExecuteC() + + test.Equal([]string{"first1", "first2"}, opts.Double.Positional.FirstList) + test.Equal([]string{"second1"}, opts.Double.Positional.SecondList) + test.Equal("third1", opts.Double.Positional.Third) + test.NoErrorf(err, "The command returned a retargs error: %v", err) +} + +// TestPositionalDoubleDashFail checks that a command being fed a sufficient +// number of positional arguments but with the double dash positioned such +// that required slots cannot be fulfilled, will indeed fail. +func TestPositionalDoubleDashFail(t *testing.T) { + t.Parallel() + test := require.New(t) + + opts := struct { + Double doubleDashCommand `command:"double-dash"` + }{} + + args := []string{"double-dash", "first1", "first2", "--", "second1", "third1", "third2", "single"} + cmd, err := newCommandWithArgs(&opts, args) + test.NoErrorf(err, "Unexpected error: %v", err) + + _, err = cmd.ExecuteC() + + test.ErrorContains(err, "`SecondList (at least 1 argument)` and `Third` were not provided") +} + +// +// Passthrough Arguments Tests -------------------------------------------------- // +// + +// A valid struct for testing passthrough arguments. +type PassthroughConfig struct { + Positional struct { + First string `positional-arg-name:"first" required:"1"` + Second []string `passthrough:""` + } `positional-args:"true"` +} + +func (c *PassthroughConfig) Execute(args []string) error { + return nil +} + +// An invalid struct where the passthrough field is not a slice of strings. +type invalidPassthroughTypeConfig struct { + Positional struct { + First string `positional-arg-name:"first"` + Second string `passthrough:""` + } `positional-args:"true"` +} + +// An invalid struct where the passthrough field is not the last argument. +type invalidPassthroughPositionConfig struct { + Positional struct { + First []string `passthrough:""` + Second string `positional-arg-name:"second"` + } `positional-args:"true"` +} + +func TestPassthroughArgs(t *testing.T) { + t.Parallel() + + // Success case: Valid passthrough argument captures remaining args. + t.Run("Valid passthrough", func(t *testing.T) { + t.Parallel() + cfg := &PassthroughConfig{} + cmd, err := newCommandWithArgs(cfg, []string{"first-arg", "second-arg", "--third-arg", "fourth-arg"}) + require.NoError(t, err) + + err = cmd.Execute() + require.NoError(t, err) + + require.Equal(t, "first-arg", cfg.Positional.First) + require.Equal(t, []string{"second-arg", "--third-arg", "fourth-arg"}, cfg.Positional.Second) + }) + + // Failure case: Passthrough argument is not a []string. + t.Run("Invalid type", func(t *testing.T) { + t.Parallel() + cfg := &invalidPassthroughTypeConfig{} + _, err := Generate(cfg) + require.Error(t, err) + require.Contains(t, err.Error(), "passthrough argument Second must be of type []string") + }) + + // Failure case: Passthrough argument is not the last positional argument. + t.Run("Invalid position", func(t *testing.T) { + t.Parallel() + cfg := &invalidPassthroughPositionConfig{} + _, err := Generate(cfg) + require.Error(t, err) + require.Contains(t, err.Error(), "passthrough argument First must be the last positional argument") + }) +} + +// +// Exported/unexported Fields Tests -------------------------------------------- // +// + +// TestInvalidPositionalType verifies that a custom positional type that does not +// implement the flags.Value interface returns an error. +func TestInvalidPositionalType(t *testing.T) { + t.Parallel() + + type customValue struct { + Value string + } + + t.Run("legacy positional container", func(t *testing.T) { + type positionalContainer struct { + Positional customValue `positional-arg-name:"pos"` + } + + type invalidPositionalTypeConfig struct { + Args positionalContainer `positional-args:"true"` + } + + cfg := &invalidPositionalTypeConfig{} + _, err := Generate(cfg) + + require.Error(t, err) + assert.Contains(t, err.Error(), "field 'Positional' has an invalid type for a positional argument") + }) + + t.Run("kong-style positional", func(t *testing.T) { + type invalidKongPositional struct { + Positional customValue `arg:""` + } + + cfg := &invalidKongPositional{} + _, err := Generate(cfg) + + require.Error(t, err) + assert.Contains(t, err.Error(), "field 'Positional' has an invalid type for a positional argument") + }) +} diff --git a/internal/interfaces/command.go b/internal/interfaces/command.go new file mode 100644 index 0000000..9393d9a --- /dev/null +++ b/internal/interfaces/command.go @@ -0,0 +1,55 @@ +package interfaces + +import "reflect" + +// PreRunner is the equivalent of cobra cmd.PreRun(cmd *cobra.Command, args []string). +type PreRunner interface { + PreRun(args []string) +} + +// PreRunnerE is the equivalent of cobra cmd.PreRunE(cmd *cobra.Command, args []string) error. +type PreRunnerE interface { + PreRunE(args []string) error +} + +// Commander is the simplest and smallest interface that a type must +// implement to be a valid, local, client command. +type Commander interface { + Execute(args []string) error +} + +// Runner is the equivalent of cobra cmd.Run(cmd *cobra.Command, args []string). +type Runner interface { + Run(args []string) +} + +// PostRunner is the equivalent of cobra cmd.PostRun(cmd *cobra.Command, args []string). +type PostRunner interface { + PostRun(args []string) +} + +// PostRunnerE is the equivalent of cobra cmd.PostRunE(cmd *cobra.Command, args []string) error. +type PostRunnerE interface { + PostRunE(args []string) error +} + +// IsCommand checks if a value implements the Commander interface. +func IsCommand(val reflect.Value) (reflect.Value, bool, Commander) { + var ptrval reflect.Value + if val.Kind() == reflect.Ptr { + ptrval = val + } else { + ptrval = val.Addr() + } + + cmd, implements := ptrval.Interface().(Commander) + if !implements { + return ptrval, false, nil + } + + if ptrval.IsNil() { + ptrval.Set(reflect.New(ptrval.Type().Elem())) + } + + return ptrval, true, cmd +} diff --git a/internal/interfaces/interfaces.go b/internal/interfaces/interfaces.go new file mode 100644 index 0000000..18eb4aa --- /dev/null +++ b/internal/interfaces/interfaces.go @@ -0,0 +1,27 @@ +package interfaces + +import ( + "github.com/carapace-sh/carapace" +) + +// Completer is the interface for types that can provide their own shell +// completion suggestions. +type Completer interface { + Complete(ctx carapace.Context) carapace.Action +} + +// Marshaler is the interface implemented by types that can marshal themselves +// to a string representation of the flag. Retroported from jessevdk/go-flags. +type Marshaler interface { + // MarshalFlag marshals a flag value to its string representation. + MarshalFlag() (string, error) +} + +// Unmarshaler is the interface implemented by types that can unmarshal a flag +// argument to themselves. The provided value is directly passed from the +// command line. Retroported from jessevdk/go-flags. +type Unmarshaler interface { + // UnmarshalFlag unmarshals a string value representation to the flag + // value (which therefore needs to be a pointer receiver). + UnmarshalFlag(value string) error +} diff --git a/internal/parser/camelcase.go b/internal/parser/camelcase.go new file mode 100644 index 0000000..1f631b9 --- /dev/null +++ b/internal/parser/camelcase.go @@ -0,0 +1,54 @@ +package parser + +import ( + "unicode" + "unicode/utf8" +) + +const ( + classLower = 1 + classUpper = 2 + classDigit = 3 + classOther = 4 +) + +func split(src string) (entries []string) { + if !utf8.ValidString(src) { + return []string{src} + } + entries = []string{} + var runes [][]rune + var class int + lastClass := 0 + for _, char := range src { + switch { + case unicode.IsLower(char): + class = classLower + case unicode.IsUpper(char): + class = classUpper + case unicode.IsDigit(char): + class = classDigit + default: + class = classOther + } + if lastClass != 0 && (class == lastClass || class == classDigit) { + runes[len(runes)-1] = append(runes[len(runes)-1], char) + } else { + runes = append(runes, []rune{char}) + } + lastClass = class + } + for i := range len(runes) - 1 { + if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) { + runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...) + runes[i] = runes[i][:len(runes[i])-1] + } + } + for _, s := range runes { + if len(s) > 0 { + entries = append(entries, string(s)) + } + } + + return entries +} diff --git a/camelcase_test.go b/internal/parser/camelcase_test.go similarity index 99% rename from camelcase_test.go rename to internal/parser/camelcase_test.go index 97b096b..b6dcc15 100644 --- a/camelcase_test.go +++ b/internal/parser/camelcase_test.go @@ -20,7 +20,7 @@ // 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. -package flags +package parser import ( "testing" @@ -55,4 +55,4 @@ func TestCamelCase(t *testing.T) { for _, test := range tests { assert.Equal(t, test.exp, split(test.src)) } -} +} \ No newline at end of file diff --git a/internal/parser/context.go b/internal/parser/context.go new file mode 100644 index 0000000..8377a0a --- /dev/null +++ b/internal/parser/context.go @@ -0,0 +1,29 @@ +package parser + +import ( + "reflect" +) + +// FieldContext holds all the relevant information about a struct field being parsed. +type FieldContext struct { + Value reflect.Value + Field reflect.StructField + Tag *Tag + Opts *Opts +} + +// NewFieldContext creates and populates a new context for a given field. +// It handles the parsing of the struct tag. +func NewFieldContext(val reflect.Value, fld reflect.StructField, opts *Opts) (*FieldContext, error) { + tag, _, err := GetFieldTag(fld) + if err != nil { + return nil, err + } + + return &FieldContext{ + Value: val, + Field: fld, + Tag: tag, + Opts: opts, + }, nil +} diff --git a/converters_test.go b/internal/parser/converters_test.go similarity index 71% rename from converters_test.go rename to internal/parser/converters_test.go index 559e106..5d021d6 100644 --- a/converters_test.go +++ b/internal/parser/converters_test.go @@ -1,9 +1,8 @@ -package flags +package parser import ( "testing" - "github.com/reeflective/flags/internal/scan" "github.com/stretchr/testify/assert" ) @@ -21,7 +20,7 @@ func TestCamelToFlag(t *testing.T) { {"IP", "ip"}, } for _, d := range data { - assert.Equal(t, d.Exp, camelToFlag(d.Src, scan.DefaultFlagDivider)) + assert.Equal(t, d.Exp, CamelToFlag(d.Src, "-")) } } @@ -34,6 +33,6 @@ func TestFlagToEnv(t *testing.T) { {"value", "VALUE"}, } for _, d := range data { - assert.Equal(t, d.Exp, flagToEnv(d.Src, scan.DefaultFlagDivider, scan.DefaultEnvDivider)) + assert.Equal(t, d.Exp, FlagToEnv(d.Src, "-", "_")) } -} +} \ No newline at end of file diff --git a/internal/parser/flag.go b/internal/parser/flag.go new file mode 100644 index 0000000..a3d9c0b --- /dev/null +++ b/internal/parser/flag.go @@ -0,0 +1,202 @@ +package parser + +import ( + "fmt" + "os" + "reflect" + + "github.com/reeflective/flags/internal/validation" + "github.com/reeflective/flags/internal/values" +) + +// Flag structure might be used by cli/flag libraries for their flag generation. +type Flag struct { + Name string // name as it appears on command line + Short string // optional short name + EnvNames []string // OS Environment-based names + Usage string // help message + Placeholder string // placeholder for the flag's value + Value values.Value // value as set + RValue reflect.Value // Type value to use for completions + DefValue []string // default value (as text); for usage message + Hidden bool // Flag hidden from descriptions/completions + Deprecated bool // Not in use anymore + Required bool // If true, the option _must_ be specified on the command line. + Persistent bool // If true, the flag is persistent on its command. + Choices []string // If non empty, only a certain set of values is allowed for an option. + OptionalValue []string // The optional value of the option. + Negatable *string // If not nil, a negation flag is generated with the given prefix. + Separator *string // Custom separator for slice values. + MapSeparator *string // Custom separator for map values. + XORGroup []string // Mutually exclusive flag groups. + ANDGroup []string // "AND" flag groups. + Tag *Tag // Field tag +} + +// parseSingleFlag handles the logic for parsing a field that is a single flag. +func parseSingleFlag(ctx *FieldContext) (*Flag, bool, error) { + flag, _, err := newFlag(ctx.Field, ctx.Opts) + if err != nil || flag == nil { + return nil, false, err + } + + if err := setupFlagValue(ctx, flag); err != nil { + return nil, true, err + } + + if flag.Value == nil { + return nil, false, nil + } + + if err := applyDefaults(flag); err != nil { + return nil, true, err + } + + if err := executeFlagFunc(ctx, flag); err != nil { + return flag, true, err + } + + return flag, true, nil +} + +func newFlag(field reflect.StructField, opts *Opts) (*Flag, *Tag, error) { + + flag, tag, err := parseFlag(field, opts) + if flag == nil || err != nil { + return flag, tag, err + } + + flag.EnvNames = parseEnvTag(flag.Name, field, opts) + + return flag, tag, err +} + +// parseFlag parses the struct tag for a given field and returns a Flag object. +func parseFlag(field reflect.StructField, opts *Opts) (*Flag, *Tag, error) { + tag, skip, err := GetFieldTag(field) + if err != nil { + return nil, nil, err + } + + // Check if the field should be skipped. + if shouldSkipField(tag, skip, opts) { + return nil, tag, nil + } + + // Get the flag name and potential short name. + name, short := getFlagName(field, tag, opts) + if name == "" && short == "" { + return nil, tag, nil + } + + // Build the initial flag from tags. + flag := buildFlag(name, short, field, tag, opts) + + // Apply final modifications and expansions. + finalizeFlag(flag, tag, opts) + + return flag, tag, nil +} + +// setupFlagValue creates and configures the value of a flag, including any validators. +func setupFlagValue(ctx *FieldContext, flag *Flag) error { + val, err := newValue(ctx, flag.Separator, flag.MapSeparator) + if err != nil { + return err + } + if val == nil { + return nil + } + + validator := validation.Setup(ctx.Value, ctx.Field, flag.Choices, ctx.Opts.Validator) + if validator != nil { + val = values.NewValidator(val, validator) + } + + flag.Value = val + flag.RValue = ctx.Value + + return nil +} + +// applyDefaults sets the default value of a flag from environment variables if available. +func applyDefaults(flag *Flag) error { + for _, env := range flag.EnvNames { + if envVal, ok := os.LookupEnv(env); ok { + if err := flag.Value.Set(envVal); err != nil { + return fmt.Errorf("failed to set default value from env var %s: %w", env, err) + } + + break // Stop after finding the first one. + } + } + + if flag.Value.String() != "" { + flag.DefValue = append(flag.DefValue, flag.Value.String()) + } + + return nil +} + +// buildFlag constructs the initial Flag struct from parsed tag information. +func buildFlag(name, short string, fld reflect.StructField, tag *Tag, opts *Opts) *Flag { + return &Flag{ + Name: name, + Short: short, + EnvNames: parseEnvTag(name, fld, opts), + Usage: getFlagUsage(tag), + Placeholder: getFlagPlaceholder(tag), + DefValue: getFlagDefault(tag), + Hidden: isSet(tag, "hidden"), + Deprecated: isSet(tag, "deprecated"), + Persistent: isSet(tag, "persistent"), + Choices: getFlagChoices(tag), + OptionalValue: tag.GetMany("optional-value"), + Negatable: getFlagNegatable(fld, tag), + XORGroup: getFlagXOR(tag), + ANDGroup: getFlagAND(tag), + Tag: tag, + } +} + +// finalizeFlag applies variable expansions and final settings to a Flag. +func finalizeFlag(flag *Flag, tag *Tag, opts *Opts) { + // Expand variables in usage, placeholder, default value, and choices. + flag.Usage = expandVar(flag.Usage, opts.Vars) + flag.Placeholder = expandVar(flag.Placeholder, opts.Vars) + flag.DefValue = expandStringSlice(flag.DefValue, opts.Vars) + flag.Choices = expandStringSlice(flag.Choices, opts.Vars) + flag.OptionalValue = expandStringSlice(flag.OptionalValue, opts.Vars) + + // Add separators if they are present. + if sep, ok := tag.Get("sep"); ok { + flag.Separator = &sep + } + if mapsep, ok := tag.Get("mapsep"); ok { + flag.MapSeparator = &mapsep + } + + // Determine if the flag is required. + requiredVal, _ := tag.Get("required") + flag.Required = isSet(tag, "required") && !IsStringFalsy(requiredVal) +} + +// executeFlagFunc runs the custom FlagFunc if it is provided in the options. +func executeFlagFunc(ctx *FieldContext, flag *Flag) error { + if ctx.Opts.FlagFunc == nil { + return nil + } + + var name string + if flag.Name != "" { + name = flag.Name + } else { + name = flag.Short + } + + if err := ctx.Opts.FlagFunc(name, ctx.Tag, ctx.Value); err != nil { + return fmt.Errorf("flag handler error on flag %s: %w", name, err) + } + + return nil +} diff --git a/internal/parser/options.go b/internal/parser/options.go new file mode 100644 index 0000000..ae897cc --- /dev/null +++ b/internal/parser/options.go @@ -0,0 +1,149 @@ +package parser + +import ( + "maps" + "reflect" + + "github.com/carapace-sh/carapace" + "github.com/reeflective/flags/internal/validation" +) + +// FlagFunc is a generic function that can be applied to each +// value that will end up being a flags *Flag, so that users +// can perform more arbitrary operations on each. +type FlagFunc func(flag string, tag *Tag, val reflect.Value) error + +// OptFunc sets values in Opts structure. +type OptFunc func(opt *Opts) + +// Opts specifies different parsing options. +type Opts struct { + // DescTag is the struct tag name for description. + DescTag string + + // FlagTag is the struct tag name for flag. + FlagTag string + + // Delimiter for flags. + FlagDivider string + + // Delimiter for environment variables. + EnvDivider string + + // Prefix for all flags. + Prefix string + + // Prefix for all environment variables. + EnvPrefix string + + // Flatten anonymous structures. + Flatten bool + + // ParseAllFields specifies either to parse all fields or only tagged ones. + ParseAll bool + + // Validator is the validation function for flags. + Validator validation.ValidateFunc + + // FlagFunc is a generic function that can be applied to each flag. + FlagFunc FlagFunc + + // Vars is a map of variables that can be used for expansion. + Vars map[string]string + + // GlobalVars is a map of variables that are applied globally. + GlobalVars map[string]string + + // Completers is a map of custom completer functions. + Completers map[string]carapace.CompletionCallback +} + +// DefOpts returns the default parsing options. +func DefOpts() *Opts { + return &Opts{ + DescTag: "desc", + FlagTag: "flag", + FlagDivider: "-", + EnvDivider: "_", + Flatten: false, + Vars: make(map[string]string), + GlobalVars: make(map[string]string), + Completers: make(map[string]carapace.CompletionCallback), + } +} + +// Apply applies the given options to the current options. +func (o *Opts) Apply(optFuncs ...OptFunc) *Opts { + for _, f := range optFuncs { + (f)(o) + } + + return o +} + +// Copy returns a copy of the options. +func (o *Opts) Copy() *Opts { + cpy := *o + cpy.Vars = make(map[string]string) + maps.Copy(cpy.Vars, o.Vars) + // GlobalVars are not copied, they are global. + return &cpy +} + +// CopyOpts returns a copy of the given options. +func CopyOpts(opts *Opts) OptFunc { + return func(opt *Opts) { + *opt = *opts + } +} + +// DescTag sets custom description tag. It is "desc" by default. +func DescTag(val string) OptFunc { return func(opt *Opts) { opt.DescTag = val } } + +// FlagTag sets custom flag tag. It is "flag" be default. +func FlagTag(val string) OptFunc { return func(opt *Opts) { opt.FlagTag = val } } + +// Prefix sets prefix that will be applied for all flags (if they are not marked as ~). +func Prefix(val string) OptFunc { return func(opt *Opts) { opt.Prefix = val } } + +// EnvPrefix sets prefix that will be applied for all environment variables (if they are not marked as ~). +func EnvPrefix(val string) OptFunc { return func(opt *Opts) { opt.EnvPrefix = val } } + +// FlagDivider sets custom divider for flags. It is dash by default. e.g. "flag-name". +func FlagDivider(val string) OptFunc { return func(opt *Opts) { opt.FlagDivider = val } } + +// EnvDivider sets custom divider for environment variables. +func EnvDivider(val string) OptFunc { return func(opt *Opts) { opt.EnvDivider = val } } + +// Flatten set flatten option. +func Flatten(val bool) OptFunc { return func(opt *Opts) { opt.Flatten = val } } + +// ParseAll orders the parser to generate a flag for all struct fields. +func ParseAll() OptFunc { return func(opt *Opts) { opt.ParseAll = true } } + +// Validator sets validator function for flags. +func Validator(val validation.ValidateFunc) OptFunc { + return func(opt *Opts) { opt.Validator = val } +} + +// FlagHandler sets the handler function for flags. +func FlagHandler(val FlagFunc) OptFunc { + return func(opt *Opts) { opt.FlagFunc = val } +} + +// WithVars adds a map of variables for expansion. +func WithVars(vars map[string]string) OptFunc { + return func(opt *Opts) { + maps.Copy(opt.GlobalVars, vars) + } +} + +// WithCompleter adds a custom completer function to the parser options. +func WithCompleter(name string, completer carapace.CompletionCallback) OptFunc { + return func(opt *Opts) { + if opt.Completers == nil { + opt.Completers = make(map[string]carapace.CompletionCallback) + } + opt.Completers[name] = completer + } +} diff --git a/internal/parser/parser.go b/internal/parser/parser.go new file mode 100644 index 0000000..d41d32e --- /dev/null +++ b/internal/parser/parser.go @@ -0,0 +1,180 @@ +package parser + +import ( + "fmt" + "reflect" + + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/values" +) + +// ParseGroup is the updated version of ParseGroup that returns the new parser.Positional type. +func ParseGroup(ctx *FieldContext) ([]*Flag, []*Positional, error) { + gopts := ctx.Opts.Copy() + tag, _, _ := GetFieldTag(ctx.Field) + + // Prepare variables and namespacing for the group. + gopts.Vars = prepareGroupVars(tag, ctx.Opts) + ctx.Opts = gopts + applyGroupNamespacing(ctx) + + // Scan the group for flags and positionals. + var flags []*Flag + var positionals []*Positional + scanner := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { + fieldFlags, fieldPositional, found, err := ParseField(val, *sfield, gopts) + if err != nil { + return false, err + } + if found { + flags = append(flags, fieldFlags...) + if fieldPositional != nil { + positionals = append(positionals, fieldPositional) + } + } + + return true, nil + } + + ptrVal := EnsureAddr(ctx.Value) + if err := Scan(ptrVal.Interface(), scanner); err != nil { + return nil, nil, err + } + + // Apply post-parsing modifications like XOR prefixing. + applyXORPrefix(flags, ctx.Field, tag, gopts) + + return flags, positionals, nil +} + +// ParseField is the updated version of ParseField that returns the new parser.Positional type. +func ParseField(val reflect.Value, fld reflect.StructField, opts *Opts) ([]*Flag, *Positional, bool, error) { + if val.Kind() == reflect.Func { + return nil, nil, false, nil + } + + // Let's create a new context for this field + ctx, err := NewFieldContext(val, fld, opts) + if err != nil || ctx == nil { + return nil, nil, false, err + } + + if flags, pos, found, err := parseField(ctx); err != nil || found { + return flags, pos, found, err + } + + return nil, nil, false, nil +} + +// parseField is the main dispatcher for parsing a single struct field. +func parseField(ctx *FieldContext) ([]*Flag, *Positional, bool, error) { + // First, check if the field is tagged as a flag but has an invalid type. + if err := validateFlagType(ctx); err != nil { + return nil, nil, true, err + } + + // Either scan the field as a positional argument + if _, isArg := ctx.Tag.Get("arg"); isArg { + pos, err := parsePositional(ctx, false) + if err != nil { + return nil, nil, true, err + } + + return nil, pos, true, nil + } + + // Or scan it as a struct container for a group of flags (named or not) + if ctx.Field.Anonymous || (isOptionGroup(ctx.Value) && ctx.Opts.ParseAll) { + flags, _, err := ParseGroup(ctx) + if err != nil { + return nil, nil, true, err + } + + return flags, nil, true, nil + } + + // Or scan the field as a single flag value. + flag, found, err := parseSingleFlag(ctx) + if err != nil || !found { + return nil, nil, found, err + } + + return []*Flag{flag}, nil, true, nil +} + +// validateFlagType checks if a field that is tagged as a flag has a type that +// can be used as a flag value. +func validateFlagType(ctx *FieldContext) error { + // If the field is not tagged as a flag, we don't need to validate it. + if !isTaggedAsFlag(ctx.Tag) { + return nil + } + + // If the field is a struct and ParseAll is not enabled, it's an error. + if isOptionGroup(ctx.Value) && !ctx.Opts.ParseAll { + return fmt.Errorf("%w: field '%s' is a struct but ParseAll is not enabled", + errors.ErrNotValue, ctx.Field.Name) + } + + // If the field is not a struct, it must be a single value type. + if !isOptionGroup(ctx.Value) && !isSingleValue(ctx.Value) { + return fmt.Errorf("%w: field '%s' has an invalid type for a flag", + errors.ErrNotValue, ctx.Field.Name) + } + + return nil +} + +// isTaggedAsFlag checks if a field is tagged with any of the flag tags. +func isTaggedAsFlag(tag *Tag) bool { + _, isFlag := tag.Get("flag") + _, isShort := tag.Get("short") + _, isLong := tag.Get("long") + + return isFlag || isShort || isLong +} + +// newValue creates a new values.Value for a field and runs initial validation. +func newValue(ctx *FieldContext, sep, mapSep *string) (values.Value, error) { + pvalue := values.NewValue(ctx.Value, sep, mapSep) + + // Check if this field was *supposed* to be a flag but failed to implement a supported interface. + if markedFlagNotImplementing(*ctx.Tag, pvalue) { + return nil, fmt.Errorf("%w: field %s does not implement a supported interface", + errors.ErrNotValue, ctx.Field.Name) + } + + return pvalue, nil +} + +// applyGroupNamespacing modifies the options' +// prefixes based on group structure and tags. +func applyGroupNamespacing(ctx *FieldContext) { + field, tag, opts := ctx.Field, ctx.Tag, ctx.Opts + _, isEmbed := tag.Get("embed") + + // Apply prefixing for nested groups, but not for + // embedded or anonymous structs (unless flattened). + if (!field.Anonymous && !isEmbed) || opts.Flatten { + baseName := CamelToFlag(field.Name, opts.FlagDivider) + opts.Prefix = opts.Prefix + baseName + opts.FlagDivider + } + + // Handle tag-based namespacing, which can override the above. + delim, ok := tag.Get("namespace-delimiter") + if !ok || delim == "" { + delim = "." + } + + if namespace, ok := tag.Get("namespace"); ok { + opts.Prefix = namespace + delim + } else if prefix, ok := tag.Get("prefix"); ok { + opts.Prefix = prefix + delim + } + + if envNamespace, ok := tag.Get("env-namespace"); ok { + opts.EnvPrefix = envNamespace + } else if envPrefix, ok := tag.Get("envprefix"); ok { + opts.EnvPrefix = envPrefix + } +} diff --git a/internal/parser/parser_test.go b/internal/parser/parser_test.go new file mode 100644 index 0000000..c224fb1 --- /dev/null +++ b/internal/parser/parser_test.go @@ -0,0 +1,882 @@ +package parser + +import ( + "errors" + "fmt" + "net" + "reflect" + "regexp" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + flagerrors "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/values" + "github.com/reeflective/flags/types" +) + +// +// Tests ----------------------------------------------------------------------------------- +// + +// TestParseStruct is a table-driven test that checks various struct parsing scenarios. +func TestParseStruct(t *testing.T) { + simpleCfg := NewSimpleCfg() + diffTypesCfg := NewDiffTypesCfg() + nestedCfg := NewNestedCfg() + descCfg := NewDescCfg() + anonymousCfg := NewAnonymousCfg() + + tt := []struct { + name string + + cfg any + optFuncs []OptFunc + expFlagSet []*Flag + expErr error + }{ + { + name: "SimpleCfg test", + cfg: simpleCfg, + optFuncs: []OptFunc{ParseAll()}, + expFlagSet: []*Flag{ + { + Name: "name", + EnvNames: nil, + DefValue: []string{"name_value"}, + Value: values.ParseGenerated(&simpleCfg.Name, nil), + Usage: "name description", + }, + { + Name: "name_two", + Short: "t", + EnvNames: []string{"NAME_TWO"}, + DefValue: []string{"name2_value"}, + Value: values.ParseGenerated(&simpleCfg.Name2, nil), + Hidden: true, + Deprecated: true, + }, + { + Name: "name3", + EnvNames: []string{"NAME_THREE"}, + DefValue: nil, + Value: values.ParseGenerated(&simpleCfg.Name3, nil), + }, + { + Name: "name4", + EnvNames: []string{"NAME4"}, + DefValue: []string{"name_value4"}, + Value: values.ParseGenerated(simpleCfg.Name4, nil), + }, + { + Name: "addr", + EnvNames: []string{"ADDR"}, + DefValue: []string{"127.0.0.1:0"}, + Value: values.ParseGenerated(simpleCfg.Addr, nil), + }, + { + Name: "map", + EnvNames: []string{"MAP"}, + DefValue: []string{"map[test:15]"}, + Value: values.ParseGeneratedMap(&simpleCfg.Map, nil), + }, + }, + }, + { + name: "SimpleCfg test with custom env_prefix and divider", + cfg: simpleCfg, + optFuncs: []OptFunc{EnvPrefix("PP|"), EnvDivider("|"), ParseAll()}, + expFlagSet: []*Flag{ + { + Name: "name", + EnvNames: nil, + DefValue: []string{"name_value"}, + Value: values.ParseGenerated(&simpleCfg.Name, nil), + Usage: "name description", + }, + { + Name: "name_two", + Short: "t", + EnvNames: []string{"PP|NAME_TWO"}, + DefValue: []string{"name2_value"}, + Value: values.ParseGenerated(&simpleCfg.Name2, nil), + Hidden: true, + Deprecated: true, + }, + { + Name: "name3", + EnvNames: []string{"PP|NAME_THREE"}, + DefValue: nil, + Value: values.ParseGenerated(&simpleCfg.Name3, nil), + }, + { + Name: "name4", + EnvNames: []string{"PP|NAME4"}, + DefValue: []string{"name_value4"}, + Value: values.ParseGenerated(simpleCfg.Name4, nil), + }, + { + Name: "addr", + EnvNames: []string{"PP|ADDR"}, + DefValue: []string{"127.0.0.1:0"}, + Value: values.ParseGenerated(simpleCfg.Addr, nil), + }, + { + Name: "map", + EnvNames: []string{"PP|MAP"}, + DefValue: []string{"map[test:15]"}, + Value: values.ParseGeneratedMap(&simpleCfg.Map, nil), + }, + }, + expErr: nil, + }, + { + name: "DifferentTypesCfg", + cfg: diffTypesCfg, + optFuncs: []OptFunc{ParseAll()}, + expFlagSet: []*Flag{ + { + Name: "string-value", + EnvNames: []string{"STRING_VALUE"}, + DefValue: []string{"string"}, + Value: values.ParseGenerated(&diffTypesCfg.StringValue, nil), + Usage: "", + }, + { + Name: "byte-value", + EnvNames: []string{"BYTE_VALUE"}, + DefValue: []string{"10"}, + Value: values.ParseGenerated(&diffTypesCfg.ByteValue, nil), + Usage: "", + }, + { + Name: "string-slice-value", + EnvNames: []string{"STRING_SLICE_VALUE"}, + DefValue: []string{"[]"}, + Value: values.ParseGenerated(&diffTypesCfg.StringSliceValue, nil), + Usage: "", + }, + { + Name: "bool-slice-value", + EnvNames: []string{"BOOL_SLICE_VALUE"}, + DefValue: []string{"[]"}, + Value: values.ParseGenerated(&diffTypesCfg.BoolSliceValue, nil), + Usage: "", + }, + { + Name: "counter-value", + EnvNames: []string{"COUNTER_VALUE"}, + DefValue: []string{"10"}, + Value: &diffTypesCfg.CounterValue, + Usage: "", + }, + { + Name: "regexp-value", + EnvNames: []string{"REGEXP_VALUE"}, + Value: values.ParseGeneratedPtrs(&diffTypesCfg.RegexpValue), + Usage: "", + }, + { + Name: "map-int8-bool", + EnvNames: []string{"MAP_INT8_BOOL"}, + Value: values.ParseGeneratedMap(&diffTypesCfg.MapInt8Bool, nil), + }, + { + Name: "map-int16-int8", + EnvNames: []string{"MAP_INT16_INT8"}, + Value: values.ParseGeneratedMap(&diffTypesCfg.MapInt16Int8, nil), + }, + { + Name: "map-string-int64", + EnvNames: []string{"MAP_STRING_INT64"}, + DefValue: []string{"map[test:888]"}, + Value: values.ParseGeneratedMap(&diffTypesCfg.MapStringInt64, nil), + }, + { + Name: "map-string-string", + EnvNames: []string{"MAP_STRING_STRING"}, + DefValue: []string{"map[test:test-val]"}, + Value: values.ParseGeneratedMap(&diffTypesCfg.MapStringString, nil), + }, + }, + }, + { + name: "NestedCfg", + cfg: nestedCfg, + optFuncs: []OptFunc{ParseAll()}, + expFlagSet: []*Flag{ + { + Name: "sub-name", + EnvNames: []string{"SUB_NAME"}, + DefValue: []string{"name_value"}, + Value: values.ParseGenerated(&nestedCfg.Sub.Name, nil), + Usage: "name description", + }, + { + Name: "sub-name2", + EnvNames: []string{"SUB_NAME_TWO"}, + DefValue: []string{"name2_value"}, + Value: values.ParseGenerated(&nestedCfg.Sub.Name2, nil), + }, + { + Name: "name3", + EnvNames: []string{"NAME_THREE"}, + Value: values.ParseGenerated(&nestedCfg.Sub.Name3, nil), + }, + { + Name: "sub-sub2-name4", + EnvNames: []string{"SUB_SUB2_NAME4"}, + DefValue: []string{"name4_value"}, + Value: values.ParseGenerated(&nestedCfg.Sub.SUB2.Name4, nil), + }, + { + Name: "sub-sub2-name5", + EnvNames: []string{"SUB_SUB2_name_five"}, + Value: values.ParseGenerated(&nestedCfg.Sub.SUB2.Name5, nil), + }, + }, + expErr: nil, + }, + { + name: "DescCfg with custom desc tag", + cfg: descCfg, + optFuncs: []OptFunc{DescTag("description")}, + expFlagSet: []*Flag{ + { + Name: "name", + EnvNames: []string{"NAME"}, + Value: values.ParseGenerated(&descCfg.Name, nil), + Usage: "name description", + }, + { + Name: "name2", + EnvNames: []string{"NAME2"}, + Value: values.ParseGenerated(&descCfg.Name2, nil), + Usage: "name2 description", + }, + }, + }, + { + name: "Anonymous cfg with disabled flatten", + cfg: anonymousCfg, + optFuncs: []OptFunc{Flatten(false), ParseAll()}, + expFlagSet: []*Flag{ + { + Name: "name1", + EnvNames: []string{"NAME1"}, + Value: values.ParseGenerated(&anonymousCfg.Name1, nil), + }, + { + Name: "name", + EnvNames: []string{"NAME"}, + DefValue: []string{"name_value"}, + Value: values.ParseGenerated(&anonymousCfg.Name, nil), + }, + }, + }, + { + name: "Anonymous cfg with enabled flatten", + cfg: anonymousCfg, + optFuncs: []OptFunc{Flatten(true), ParseAll()}, + expFlagSet: []*Flag{ + { + Name: "name1", + EnvNames: []string{"NAME1"}, + Value: values.ParseGenerated(&anonymousCfg.Name1, nil), + }, + { + Name: "simple-name", + EnvNames: []string{"SIMPLE_NAME"}, + DefValue: []string{"name_value"}, + Value: values.ParseGenerated(&anonymousCfg.Name, nil), + }, + }, + }, + { + name: "We need pointer to structure", + cfg: struct{}{}, + expErr: errors.New("object must be a pointer to struct or interface"), + }, + { + name: "We need pointer to structure 2", + cfg: strP("something"), + expErr: errors.New("object must be a pointer to struct or interface"), + }, + { + name: "We need non nil object", + cfg: nil, + expErr: errors.New("object cannot be nil"), + }, + { + name: "We need non nil value", + cfg: (*Simple)(nil), + expErr: errors.New("object cannot be nil"), + }, + } + for _, test := range tt { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + flagSet, err := parse(test.cfg, test.optFuncs...) + if test.expErr == nil { + require.NoError(t, err) + } else { + require.Equal(t, test.expErr, err) + } + compareFlagSets(t, test.expFlagSet, flagSet) + }) + } +} + +// TestParseStruct_Separators tests that `sep` and `mapsep` tags are correctly parsed. +func TestParseStruct_Separators(t *testing.T) { + t.Parallel() + + cfg := &struct { + Slice []string `long:"slice" sep:" "` + Map map[string]int `long:"map" mapsep:"|"` + NoSplitSlice []string `long:"no-split-slice" sep:"none"` + }{} + + flags, err := parse(cfg) + require.NoError(t, err) + require.Len(t, flags, 3) + + // Assertions + assert.NotNil(t, flags[0].Separator, "Slice separator should not be nil") + assert.Equal(t, " ", *flags[0].Separator, "Slice separator should be a space") + assert.Nil(t, flags[0].MapSeparator, "Slice should not have a map separator") + + assert.NotNil(t, flags[1].MapSeparator, "Map separator should not be nil") + assert.Equal(t, "|", *flags[1].MapSeparator, "Map separator should be a pipe") + assert.Nil(t, flags[1].Separator, "Map should not have a slice separator") + + assert.NotNil(t, flags[2].Separator, "NoSplitSlice separator should not be nil") + assert.Equal(t, "none", *flags[2].Separator, "NoSplitSlice separator should be 'none'") +} + +// TestParseStruct_NilValue tests that nil pointers in a struct are correctly initialized. +func TestParseStruct_NilValue(t *testing.T) { + t.Parallel() + name2Value := "name2_value" + cfg := struct { + Name1 *string + Name2 *string + Regexp *regexp.Regexp + }{ + Name2: &name2Value, + } + assert.Nil(t, cfg.Name1) + assert.Nil(t, cfg.Regexp) + assert.NotNil(t, cfg.Name2) + + flags, err := parse(&cfg, ParseAll()) + require.NoError(t, err) + require.Len(t, flags, 3) + assert.NotNil(t, cfg.Name1) + assert.NotNil(t, cfg.Name2) + assert.NotNil(t, cfg.Regexp) + assert.Equal(t, name2Value, flags[1].Value.(values.Getter).Get()) + + err = flags[0].Value.Set("name1value") + require.NoError(t, err) + assert.Equal(t, "name1value", *cfg.Name1) + + err = flags[2].Value.Set("aabbcc") + require.NoError(t, err) + assert.Equal(t, "aabbcc", cfg.Regexp.String()) +} + +// TestParseStruct_WithValidator tests that a custom validator is correctly called. +func TestParseStruct_WithValidator(t *testing.T) { + t.Parallel() + var cfg Simple + + testErr := fmt.Errorf("%w: %w", flagerrors.ErrInvalidValue, errors.New("validator test error")) + + validator := Validator(func(val string, field reflect.StructField, obj any) error { + return errors.New("validator test error") + }) + + flags, err := parse(&cfg, validator, ParseAll()) + require.NoError(t, err) + require.Len(t, flags, 1) + assert.NotNil(t, cfg.Name) + + err = flags[0].Value.Set("aabbcc") + require.Error(t, err) + assert.Equal(t, testErr, err) +} + +// TestFlagDivider tests that the FlagDivider option is correctly applied. +func TestFlagDivider(t *testing.T) { + t.Parallel() + opt := Opts{ + FlagDivider: "-", + } + FlagDivider("_")(&opt) + assert.Equal(t, "_", opt.FlagDivider) +} + +// TestFlagTag tests that the FlagTag option is correctly applied. +func TestFlagTag(t *testing.T) { + t.Parallel() + opt := Opts{ + FlagTag: "flags", + } + FlagTag("superflag")(&opt) + assert.Equal(t, "superflag", opt.FlagTag) +} + +// TestValidator tests that the Validator option is correctly applied. +func TestValidator(t *testing.T) { + t.Parallel() + opt := Opts{ + Validator: nil, + } + Validator(func(string, reflect.StructField, any) error { + return nil + })(&opt) + assert.NotNil(t, opt.Validator) +} + +// TestFlatten tests that the Flatten option is correctly applied. +func TestFlatten(t *testing.T) { + t.Parallel() + opt := Opts{ + Flatten: true, + } + Flatten(false)(&opt) + assert.False(t, opt.Flatten) +} + +func TestParseFlagTag(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + tag string + expected Flag + }{ + { + name: "Simple long name", + tag: `long:"my-flag"`, + expected: Flag{ + Name: "my-flag", + EnvNames: []string{"MY_FLAG"}, + }, + }, + { + name: "Long and short name", + tag: `long:"my-flag" short:"f"`, + expected: Flag{ + Name: "my-flag", + Short: "f", + EnvNames: []string{"MY_FLAG"}, + }, + }, + { + name: "Comma-separated env vars", + tag: `long:"my-flag" env:"MY_VAR,OLD_VAR"`, + expected: Flag{ + Name: "my-flag", + EnvNames: []string{"MY_VAR", "OLD_VAR"}, + }, + }, + { + name: "Comma-separated xor groups", + tag: `long:"my-flag" xor:"one,two"`, + expected: Flag{ + Name: "my-flag", + EnvNames: []string{"MY_FLAG"}, + XORGroup: []string{"one", "two"}, + }, + }, + { + name: "Comma-separated and groups", + tag: `long:"my-flag" and:"one,two"`, + expected: Flag{ + Name: "my-flag", + EnvNames: []string{"MY_FLAG"}, + ANDGroup: []string{"one", "two"}, + }, + }, + { + name: "All together", + tag: `long:"my-flag" short:"f" env:"MY_VAR" xor:"a,b" and:"c,d"`, + expected: Flag{ + Name: "my-flag", + Short: "f", + EnvNames: []string{"MY_VAR"}, + XORGroup: []string{"a", "b"}, + ANDGroup: []string{"c", "d"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + field := reflect.StructField{ + Name: "MyField", + Tag: reflect.StructTag(tt.tag), + Type: reflect.TypeOf(""), + } + + opts := DefOpts() + flag, _, err := parseFlag(field, opts) + require.NoError(t, err) + + // We only check the fields we care about for this test. + assert.Equal(t, tt.expected.Name, flag.Name) + assert.Equal(t, tt.expected.Short, flag.Short) + assert.Equal(t, tt.expected.EnvNames, flag.EnvNames) + assert.Equal(t, tt.expected.XORGroup, flag.XORGroup) + assert.Equal(t, tt.expected.ANDGroup, flag.ANDGroup) + }) + } +} + +// TestVariableExpansion checks that variables set with +// `set:""` tags are correctly expanded in other tags. +func TestVariableExpansion(t *testing.T) { + t.Parallel() + + // Test case for variables set via `set` tag. + t.Run("Tag-based variables", func(t *testing.T) { + t.Parallel() + cfg := &varExpansionConfig{} + flags, err := parse(cfg, ParseAll()) + require.NoError(t, err) + require.Len(t, flags, 6) + + // Assertions for the main group with variables + assert.Equal(t, "default", flags[0].DefValue[0]) + assert.Equal(t, "placeholder", flags[1].Placeholder) + assert.Equal(t, "Usage is usage", flags[2].Usage) + assert.Equal(t, []string{"A", "B"}, flags[3].Choices) + assert.Equal(t, []string{"default"}, flags[4].OptionalValue) + + // Assertion for the sibling group to ensure no variable leakage + assert.Equal(t, "${default_var}", flags[5].DefValue[0]) + }) + + // New test case for variables set via functional option. + t.Run("Option-based variables", func(t *testing.T) { + t.Parallel() + cfg := &varExpansionConfig{} + vars := map[string]string{ + "default_var": "from_option", + "placeholder_var": "from_option", + "usage_var": "from_option", + "choice1": "C", + "choice2": "D", + } + flags, err := parse(cfg, ParseAll(), WithVars(vars)) + require.NoError(t, err) + require.Len(t, flags, 6) + + // Assertions for the main group with variables + assert.Equal(t, "from_option", flags[0].DefValue[0]) + assert.Equal(t, "from_option", flags[1].Placeholder) + assert.Equal(t, "Usage is from_option", flags[2].Usage) + assert.Equal(t, []string{"C", "D"}, flags[3].Choices) + assert.Equal(t, []string{"from_option"}, flags[4].OptionalValue) + }) +} + +// TestEmbedTag verifies that the `embed:""` tag correctly +// embeds a struct's fields without prefixing. +func TestEmbedTag(t *testing.T) { + t.Parallel() + + cfg := &embedConfig{} + flags, err := parse(cfg, ParseAll()) + require.NoError(t, err) + require.Len(t, flags, 2) + + // Assert that the embedded flag has no prefix. + assert.Equal(t, "flag1", flags[0].Name) + + // Assert that the normal group flag has a prefix. + assert.Equal(t, "normal-flag2", flags[1].Name) +} + +type xorPrefixConfig struct { + Group struct { + XORFlag bool `long:"xor-flag" xor:"group1"` + OtherFlag bool `long:"other-flag"` + } `group:"group options" xorprefix:"my-prefix"` +} + +// TestXORPrefix checks that the `xorprefix:""` tag +// correctly applies a prefix to flags within an XOR group. +func TestXORPrefix(t *testing.T) { + t.Parallel() + + cfg := &xorPrefixConfig{} + flags, err := parse(cfg, ParseAll()) + require.NoError(t, err) + require.Len(t, flags, 2) + + // Assert that the XOR flag has the prefix. + assert.Equal(t, "my-prefix-xor-flag", flags[0].Name) + + // Assert that the other flag does NOT have the prefix. + assert.Equal(t, "group-other-flag", flags[1].Name) +} + +// +// Data ------------------------------------------------------------------------------------ +// + +// NewSimpleCfg returns a test configuration for simple struct parsing. +func NewSimpleCfg() *struct { + Name string `desc:"name description" env:"-"` + Name2 string `flag:"name_two t,hidden,deprecated"` + Name3 string `env:"NAME_THREE"` + Name4 *string + Name5 string `flag:"-"` + Name6 string `kong:"-"` + name7 string + + Addr *net.TCPAddr + + Map map[string]int +} { + return &struct { + Name string `desc:"name description" env:"-"` + Name2 string `flag:"name_two t,hidden,deprecated"` + Name3 string `env:"NAME_THREE"` + Name4 *string + Name5 string `flag:"-"` + Name6 string `kong:"-"` + name7 string + + Addr *net.TCPAddr + + Map map[string]int + }{ + Name: "name_value", + Name2: "name2_value", + Name4: strP("name_value4"), + Addr: &net.TCPAddr{ + IP: net.ParseIP("127.0.0.1"), + }, + name7: "name7_value", + Map: map[string]int{"test": 15}, + } +} + +// NewDiffTypesCfg returns a test configuration for different types parsing. +func NewDiffTypesCfg() *struct { + StringValue string + ByteValue byte + StringSliceValue []string + BoolSliceValue []bool + CounterValue types.Counter + RegexpValue *regexp.Regexp + FuncValue func() // will be ignored + MapInt8Bool map[int8]bool + MapInt16Int8 map[int16]int8 + MapStringInt64 map[string]int64 + MapStringString map[string]string +} { + return &struct { + StringValue string + ByteValue byte + StringSliceValue []string + BoolSliceValue []bool + CounterValue types.Counter + RegexpValue *regexp.Regexp + FuncValue func() // will be ignored + MapInt8Bool map[int8]bool + MapInt16Int8 map[int16]int8 + MapStringInt64 map[string]int64 + MapStringString map[string]string + }{ + StringValue: "string", + ByteValue: 10, + StringSliceValue: []string{}, + BoolSliceValue: []bool{}, + CounterValue: 10, + RegexpValue: ®exp.Regexp{}, + MapStringInt64: map[string]int64{"test": 888}, + MapStringString: map[string]string{"test": "test-val"}, + } +} + +// NewNestedCfg returns a test configuration for nested structs parsing. +func NewNestedCfg() *NestedCfg { + return &NestedCfg{ + Sub: Sub{ + Name: "name_value", + Name2: "name2_value", + SUB2: &struct { + Name4 string + Name5 string `env:"name_five"` + }{ + Name4: "name4_value", + }, + }, + } +} + +// NewDescCfg returns a test configuration for description tags. +func NewDescCfg() *struct { + Name string `desc:"name description"` + Name2 string `description:"name2 description"` +} { + return &struct { + Name string `desc:"name description"` + Name2 string `description:"name2 description"` + }{} +} + +// NewAnonymousCfg returns a test configuration for anonymous structs. +func NewAnonymousCfg() *struct { + Name1 string + Simple +} { + return &struct { + Name1 string + Simple + }{ + Simple: Simple{ + Name: "name_value", + }, + } +} + +type NestedCfg struct { + Sub Sub +} + +type Sub struct { + Name string `desc:"name description"` + Name2 string `env:"NAME_TWO"` + Name3 string `env:"~NAME_THREE" flag:"~name3"` + SUB2 *struct { + Name4 string + Name5 string `env:"name_five"` + } +} + +type Simple struct { + Name string +} + +type varExpansionConfig struct { + Group struct { + Default string `default:"${default_var}" long:"default"` + Placeholder string `long:"placeholder" placeholder:"${placeholder_var}"` + Usage string `help:"Usage is ${usage_var}" long:"usage"` + Choices string `enum:"${choice1},${choice2}" long:"choices"` + OptionalValue string `long:"optional" optional-value:"${default_var}"` + } `group:"group" set:"default_var=default" set:"placeholder_var=placeholder" set:"usage_var=usage" set:"choice1=A" set:"choice2=B"` + + SiblingGroup struct { + Default string `default:"${default_var}" long:"default"` // Should not be expanded + } `group:"sibling"` +} + +type embedConfig struct { + Embedded struct { + Flag1 string `long:"flag1"` + } `embed:""` + Normal struct { + Flag2 string `long:"flag2"` + } `group:"normal"` +} + +func strP(value string) *string { + return &value +} + +// +// Helpers ------------------------------------------------------------------------------------ +// + +// parse is the single, intelligent entry point for parsing a struct into flags. +// It uses a unified recursive approach to correctly handle nested groups and +// avoid the double-parsing of anonymous fields that plagued the previous implementation. +func parse(cfg any, optFuncs ...OptFunc) ([]*Flag, error) { + if cfg == nil { + return nil, flagerrors.ErrNilObject + } + v := reflect.ValueOf(cfg) + if v.Kind() != reflect.Ptr { + return nil, flagerrors.ErrNotPointerToStruct + } + if v.IsNil() { + return nil, flagerrors.ErrNilObject + } + e := v.Elem() + if e.Kind() != reflect.Struct { + return nil, flagerrors.ErrNotPointerToStruct + } + + opts := DefOpts().Apply(optFuncs...) + + var flags []*Flag + scanner := func(val reflect.Value, sfield *reflect.StructField) (bool, error) { + fieldFlags, _, found, err := ParseField(val, *sfield, opts) + if err != nil { + return false, err + } + if found { + flags = append(flags, fieldFlags...) + } + + return true, nil + } + + if err := Scan(cfg, scanner); err != nil { + return nil, err + } + + return flags, nil +} + +// compareFlagSets compares two slices of Flag pointers, ignoring the Tag and Value fields. +func compareFlagSets(t *testing.T, expected, actual []*Flag) { + require.Len(t, actual, len(expected), "Number of flags mismatch") + + for i := range expected { + exp := expected[i] + act := actual[i] + + assert.Equal(t, exp.Name, act.Name, "Flag Name mismatch at index %d", i) + assert.Equal(t, exp.Short, act.Short, "Flag Short mismatch at index %d", i) + assert.Equal(t, exp.Name, act.Name, "Flag Long mismatch at index %d", i) + assert.Equal(t, exp.Usage, act.Usage, "Flag Usage mismatch at index %d", i) + assert.Equal(t, exp.DefValue, act.DefValue, "Flag DefValue mismatch at index %d", i) + assert.Equal(t, exp.Placeholder, act.Placeholder, "Flag Placeholder mismatch at index %d", i) + // assert.Equal(t, exp.NoOptDefVal, act.NoOptDefVal, "Flag NoOptDefVal mismatch at index %d", i) + assert.Equal(t, exp.Deprecated, act.Deprecated, "Flag Deprecated mismatch at index %d", i) + assert.Equal(t, exp.Hidden, act.Hidden, "Flag Hidden mismatch at index %d", i) + assert.Equal(t, exp.Required, act.Required, "Flag Required mismatch at index %d", i) + // assert.Equal(t, exp.Persistent, act.Persistent, "Flag Persistent mismatch at index %d", i) + // assert.Equal(t, exp.ToggleGroup, act.ToggleGroup, "Flag ToggleGroup mismatch at index %d", i) + assert.Equal(t, exp.EnvNames, act.EnvNames, "Flag EnvNames mismatch at index %d", i) + assert.Equal(t, exp.XORGroup, act.XORGroup, "Flag XORGroup mismatch at index %d", i) + assert.Equal(t, exp.ANDGroup, act.ANDGroup, "Flag ANDGroup mismatch at index %d", i) + assert.Equal(t, exp.Choices, act.Choices, "Flag Choices mismatch at index %d", i) + + // For Value, we can compare the underlying value if it implements values.Getter + if exp.Value != nil && act.Value != nil { + expGetter, expOk := exp.Value.(values.Getter) + actGetter, actOk := act.Value.(values.Getter) + if expOk && actOk { + assert.Equal(t, expGetter.Get(), actGetter.Get(), "Flag Value mismatch at index %d", i) + } else { + // Fallback to comparing string representation or type if not Getter + assert.Equal(t, fmt.Sprintf("%v", exp.Value), fmt.Sprintf("%v", act.Value), "Flag Value (non-Getter) mismatch at index %d", i) + } + } else { + assert.Nil(t, act.Value, "Actual Flag Value should be nil at index %d", i) + } + + // Tag field is ignored for comparison + } +} diff --git a/internal/parser/positional.go b/internal/parser/positional.go new file mode 100644 index 0000000..d2ae144 --- /dev/null +++ b/internal/parser/positional.go @@ -0,0 +1,229 @@ +package parser + +import ( + "fmt" + "math" + "reflect" + "strconv" + "strings" + + flagerrors "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/validation" + "github.com/reeflective/flags/internal/values" +) + +// Positional represents a positional argument defined in a struct field. +type Positional struct { + Name string + Usage string + Value reflect.Value + PValue values.Value + Min int + Max int + Index int // The position in the struct (n'th struct field used as a slot) + StartMin int + StartMax int + Passthrough bool + Tag *Tag + Validator func(val string) error +} + +// ParsePositionalStruct scans a struct value that is tagged as a legacy `positional-args:"true"` +// container and returns a slice of parsed Positional arguments. +func ParsePositionalStruct(val reflect.Value, stag *Tag, opts *Opts) ([]*Positional, error) { + stype := val.Type() + req, _ := stag.Get("required") // this is written on the struct, applies to all + reqAll := len(req) != 0 // Each field will count as one required minimum + + var positionals = make([]*Positional, 0) + + for i := range stype.NumField() { + field := stype.Field(i) + fieldValue := val.Field(i) + + ctx, err := NewFieldContext(fieldValue, field, opts) + if err != nil || ctx == nil { + return nil, err + } + + pos, err := parsePositional(ctx, reqAll) + if err != nil { + return nil, err + } + + pos.Index = len(positionals) + positionals = append(positionals, pos) + } + + return positionals, nil +} + +// parsePositional is the internal helper that parses a field tagged +// as a positional argument and returns a complete Positional struct. +func parsePositional(ctx *FieldContext, reqAll bool) (*Positional, error) { + // First, check if the field has a type that can be used as a positional argument. + if !isSingleValue(ctx.Value) { + return nil, fmt.Errorf("field '%s' has an invalid type for a positional argument", + ctx.Field.Name) + } + + field, value, tag := ctx.Field, ctx.Value, ctx.Tag + + name := getPositionalName(field, tag) + + minWords, maxWords, err := positionalReqs(ctx, reqAll) + if err != nil { + return nil, err + } + + pos := &Positional{ + Name: name, + Usage: getPositionalUsage(tag), + Value: value, + PValue: values.NewValue(value, nil, nil), + Min: minWords, + Max: maxWords, + Tag: tag, + } + + if err := setupPassthrough(pos, field, tag); err != nil { + return nil, err + } + + setupValidator(ctx, pos) + + return pos, nil +} + +// getPositionalName extracts the name of the positional argument from the struct tag or field. +func getPositionalName(fld reflect.StructField, tag *Tag) string { + if name, ok := tag.Get("arg"); ok && name != "" { + return name + } + if name, ok := tag.Get("positional-arg-name"); ok { + return name + } + + return fld.Name +} + +// setupPassthrough configures the passthrough settings for a positional argument. +func setupPassthrough(pos *Positional, fld reflect.StructField, tag *Tag) error { + if _, ok := tag.Get("passthrough"); ok { + if fld.Type.Kind() != reflect.Slice || fld.Type.Elem().Kind() != reflect.String { + return fmt.Errorf("%w: passthrough argument %s must be of type []string", + flagerrors.ErrInvalidTag, fld.Name) + } + pos.Passthrough = true + pos.Max = -1 + } + + return nil +} + +// setupValidator creates and sets up a validator for the positional argument. +func setupValidator(ctx *FieldContext, pos *Positional) { + var choices []string + choiceTags := ctx.Tag.GetMany("choice") + for _, choice := range choiceTags { + choices = append(choices, strings.Split(choice, " ")...) + } + + validator := validation.Setup(pos.Value, ctx.Field, choices, ctx.Opts.Validator) + if validator != nil { + pos.Validator = validator + } +} + +// positionalReqs determines the correct quantity requirements for a positional field, +// depending on its parsed struct tag values, and the underlying type of the field. +func positionalReqs(ctx *FieldContext, all bool) (minWords, maxWords int, err error) { + val, tag := ctx.Value, ctx.Tag + required, maxWords, set, err := parseQuantityRequired(*tag) + if err != nil { + return 0, 0, err + } + + // At least for each requirements are global + if all && required == 0 { + minWords = 1 + } + + // When the argument field is not a slice, we have to adjust for some defaults + isSlice := val.Type().Kind() == reflect.Slice || val.Type().Kind() == reflect.Map + if !isSlice { + maxWords = 1 + } + + switch { + case !isSlice && required > 0: + // Individual fields cannot have more than one required + minWords = 1 + case !set && !isSlice && all: + // If we have a struct of untagged fields, but all required, + // we automatically set min/max to one if the field is individual. + minWords = 1 + case set && isSlice && required > 0: + // If a slice has at least one required, add this minimum + // Increase the total number of positional args wanted. + minWords += required + } + + return minWords, maxWords, err +} + +// parseQuantityRequired sets the minimum/maximum requirements for an argument field. +func parseQuantityRequired(fieldTag Tag) (int, int, bool, error) { + required := 0 + maximum := -1 + + sreq, set := fieldTag.Get("required") + + // If no requirements, -1 means unlimited + if sreq == "" || !set { + return required, maximum, set, nil + } + + required = 1 + + rng := strings.SplitN(sreq, "-", 2) + + if len(rng) > 1 { + if preq, err := strconv.ParseInt(rng[0], 10, 64); err == nil { + if preq > 0 && preq <= math.MaxInt { + required = int(preq) + } + } + if preq, err := strconv.ParseInt(rng[1], 10, 64); err == nil { + if preq > 0 && preq <= math.MaxInt { + maximum = int(preq) + } + } + } else { + if preq, err := strconv.ParseInt(sreq, 10, 64); err == nil { + if preq > 0 && preq <= math.MaxInt { + required = int(preq) + } + } + } + + if maximum == 0 { + return required, maximum, set, flagerrors.ErrInvalidRequiredQuantity + } + + return required, maximum, set, nil +} + +func getPositionalUsage(tag *Tag) string { + if usage, isSet := tag.Get("description"); isSet { + return usage + } + if usage, isSet := tag.Get("desc"); isSet { + return usage + } + if usage, isSet := tag.Get("help"); isSet { // Kong alias + return usage + } + + return "" +} diff --git a/internal/parser/scan.go b/internal/parser/scan.go new file mode 100644 index 0000000..1585203 --- /dev/null +++ b/internal/parser/scan.go @@ -0,0 +1,152 @@ +package parser + +import ( + "fmt" + "reflect" + "strings" + "sync" + + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/interfaces" + "github.com/reeflective/flags/internal/values" +) + +// Handler is a function that can be applied to a struct field. +type Handler func(val reflect.Value, field *reflect.StructField) (bool, error) + +// Scan actually scans the type, recursively if needed. +func Scan(data any, handler Handler) error { + // Get all the public fields in the data struct + ptrval := reflect.ValueOf(data) + + if ptrval.Type().Kind() != reflect.Ptr { + return errors.ErrNotPointerToStruct + } + + stype := ptrval.Type().Elem() + + if stype.Kind() != reflect.Struct { + return errors.ErrNotPointerToStruct + } + + realval := reflect.Indirect(ptrval) + + return scan(realval, handler) +} + +func scan(v reflect.Value, handler Handler) error { + t := v.Type() + for i := range t.NumField() { + field := t.Field(i) + value := v.Field(i) + + // Never scan unexported fields, but only return an error + // right away if they are tagged as a flag/arg/command. + if !field.IsExported() { + if err := checkForDisallowedTags(field); err != nil { + return err + } + + continue + } + + // Otherwise, start the scanning process. + if _, err := handler(value, &field); err != nil { + return err + } + } + + return nil +} + +var disallowedTags = []string{ + "flag", "short", "long", "command", "cmd", + "group", "options", "arg", "positional-args", +} + +func checkForDisallowedTags(field reflect.StructField) error { + tag, skip, _ := GetFieldTag(field) + if skip { + return nil + } + + var foundTags []string + var checks sync.WaitGroup + var mu sync.Mutex + + for _, tagName := range disallowedTags { + checks.Add(1) + go func(t string) { + defer checks.Done() + if _, ok := tag.Get(t); ok { + mu.Lock() + foundTags = append(foundTags, t) + mu.Unlock() + } + }(tagName) + } + + checks.Wait() + + if len(foundTags) > 0 { + return fmt.Errorf("%w: field '%s' is not exported but has tags: %s", + errors.ErrUnexportedField, field.Name, strings.Join(foundTags, ", ")) + } + + return nil +} + +// isSingleValue checks if a reflect.Value can be handled as a single flag value, +// as opposed to a group of flags. This is the case if the type implements +// a value interface, a text unmarshaling interface, or is a known primitive +// type supported by the generated parsers. +func isSingleValue(val reflect.Value) bool { + // 1. Check for direct interface implementations on the value itself or a pointer to it. + if val.CanInterface() { + if _, ok := val.Interface().(values.Value); ok { + return true + } + } + if val.CanAddr() { + ptr := val.Addr().Interface() + if _, ok := ptr.(values.Value); ok { + return true + } + if _, ok := ptr.(interfaces.Unmarshaler); ok { + return true + } + } + + // 2. Check if the type is one of the built-in, generated value types. + if val.CanAddr() { + addr := val.Addr().Interface() + if values.ParseGenerated(addr, nil) != nil { + return true + } + if values.ParseGeneratedPtrs(addr) != nil { + return true + } + if values.ParseGeneratedMap(addr, nil) != nil { + return true + } + } + + // 3. Check for primitive types that can be handled by a reflective value. + if values.IsValidReflectiveKind(val) { + return true + } + + // 4. Handle pointers: if the value is a pointer, check the type it points to. + if val.Kind() == reflect.Ptr { + // If the pointer is nil, we can't check the pointed-to value directly. + // Instead, we create a new zero value of the underlying type and check that. + if val.IsNil() { + return isSingleValue(reflect.New(val.Type().Elem()).Elem()) + } + // If the pointer is not nil, recurse on the element it points to. + return isSingleValue(val.Elem()) + } + + // If none of the above, it's not a type we can handle as a single value. + return false +} diff --git a/internal/parser/tag.go b/internal/parser/tag.go new file mode 100644 index 0000000..c63048f --- /dev/null +++ b/internal/parser/tag.go @@ -0,0 +1,345 @@ +package parser + +import ( + "fmt" + "reflect" + "strings" + + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/values" +) + +const ( + // DefaultTagName is the default struct tag name. + DefaultTagName = "long" + // DefaultShortTagName is the default short struct tag name. + DefaultShortTagName = "short" + // DefaultEnvTag is the default env struct tag name. + DefaultEnvTag = "env" +) + +// +// Tag query/parsing utility functions -----------------------------------------// +// + +// Tag is a map of struct tags. +type Tag map[string][]string + +// GetFieldTag returns the struct tags for a given field. +func GetFieldTag(field reflect.StructField) (*Tag, bool, error) { + tag := Tag{} + if err := tag.parse(string(field.Tag)); err != nil { + return nil, true, err + } + + return &tag, len(tag) == 0, nil +} + +// Get returns the value of a tag. +func (t *Tag) Get(key string) (string, bool) { + if val, ok := (*t)[key]; ok { + return val[0], true + } + + return "", false +} + +// GetMany returns the values of a tag. +func (t *Tag) GetMany(key string) []string { + if val, ok := (*t)[key]; ok { + return val + } + + return nil +} + +func (t *Tag) parse(tag string) error { + for tag != "" { + // Skip leading space. + pos := 0 + for pos < len(tag) && tag[pos] == ' ' { + pos++ + } + tag = tag[pos:] + if tag == "" { + break + } + + // Scan to colon. A space, a quote or a control character is a syntax error. + // Strictly speaking, control chars include the space character. + pos = 0 + for pos < len(tag) && tag[pos] > ' ' && tag[pos] != ':' && tag[pos] != '"' && tag[pos] != 0x7f { + pos++ + } + if pos == 0 || pos+1 >= len(tag) || tag[pos] != ':' || tag[pos+1] != '"' { + return fmt.Errorf("%w: invalid syntax", errors.ErrInvalidTag) + } + name := tag[:pos] + tag = tag[pos+1:] + + // Scan quoted string to find value. + pos = 1 + for pos < len(tag) && tag[pos] != '"' { + if tag[pos] == '\\' { + pos++ + } + pos++ + } + if pos >= len(tag) { + return fmt.Errorf("%w: invalid syntax", errors.ErrInvalidTag) + } + qvalue := tag[:pos+1] + tag = tag[pos+1:] + + value, ok := reflect.StructTag(name + ":" + qvalue).Lookup(name) + if !ok { + return fmt.Errorf("%w: tag value not found", errors.ErrInvalidTag) + } + (*t)[name] = append((*t)[name], value) + } + + return nil +} + +// +// Functions for parsing tag information --------------------------------------// +// + +// shouldSkipField checks if a field should be ignored based on its tags. +func shouldSkipField(tag *Tag, skip bool, opts *Opts) bool { + if val, isSet := tag.Get("kong"); isSet && val == "-" { + return true + } + if val, isSet := tag.Get(opts.FlagTag); isSet && val == "-" { + return true + } + if _, isSet := tag.Get("no-flag"); isSet { + return true + } + + return skip && !opts.ParseAll +} + +func getFlagName(field reflect.StructField, tag *Tag, opts *Opts) (string, string) { + // Start with values from sflags format, which can include the ignore-prefix tilde. + long, short, ignorePrefix := parseSFlag(tag, opts) + + // Layer on Kong's 'name' alias for long name. + if name, isSet := tag.Get("name"); isSet { + long = name + } + + // Layer on standard 'long' and 'short' tags, which take precedence if present. + if l, ok := tag.Get("long"); ok { + long = l + } + if s, ok := tag.Get("short"); ok { + short = s + } + + // If no long name was found in any tag, generate it from the field name. + if long == "" { + long = CamelToFlag(field.Name, opts.FlagDivider) + } + + // Apply the namespace prefix if it's not being ignored. + long = applyPrefix(long, tag, opts, ignorePrefix) + + return long, short +} + +// parseSFlag handles the specific parsing of sflags-style `flag:"..."` tags. +// It returns the long name, short name, and a boolean indicating if the namespace prefix should be ignored. +func parseSFlag(tag *Tag, opts *Opts) (long, short string, ignorePrefix bool) { + names, isSet := tag.Get(opts.FlagTag) + if !isSet { + return + } + + // Check for the ignore-prefix tilde. + if strings.HasPrefix(names, "~") { + ignorePrefix = true + names = names[1:] // Remove the tilde for further parsing. + } + + values := strings.Split(names, ",") + parts := strings.Split(values[0], " ") + if len(parts) > 1 { + long = parts[0] + short = parts[1] + } else { + long = parts[0] + } + + return +} + +// applyPrefix conditionally applies the namespace prefix to a flag's long name. +func applyPrefix(longName string, tag *Tag, opts *Opts, ignorePrefix bool) string { + if ignorePrefix { + return longName + } + + prefix, hasPrefixTag := tag.Get("prefix") // Kong alias for namespace + + if opts.Prefix != "" { + return opts.Prefix + longName + } else if hasPrefixTag { + return prefix + opts.FlagDivider + longName + } + + return longName +} + +// applyXORPrefix adds a prefix to the names of flags within an XOR group. +func applyXORPrefix(flags []*Flag, field reflect.StructField, tag *Tag, opts *Opts) { + if xorPrefix, ok := tag.Get("xorprefix"); ok { + fieldPrefix := CamelToFlag(field.Name, opts.FlagDivider) + opts.FlagDivider + for _, flag := range flags { + if len(flag.XORGroup) > 0 { + flag.Name = strings.TrimPrefix(flag.Name, fieldPrefix) + flag.Name = xorPrefix + opts.FlagDivider + flag.Name + } + } + } +} + +func getFlagUsage(tag *Tag) string { + if usage, isSet := tag.Get("description"); isSet { + return usage + } + if usage, isSet := tag.Get("desc"); isSet { + return usage + } + if usage, isSet := tag.Get("help"); isSet { // Kong alias + return usage + } + + return "" +} + +func getFlagPlaceholder(tag *Tag) string { + if placeholder, isSet := tag.Get("placeholder"); isSet { + return placeholder + } + + return "" +} + +func getFlagChoices(tag *Tag) []string { + var choices []string + + choiceTags := tag.GetMany("choice") + for _, choice := range choiceTags { + choices = append(choices, strings.Split(choice, " ")...) + } + + // Kong alias + enumTags := tag.GetMany("enum") + for _, enum := range enumTags { + choices = append(choices, strings.Split(enum, ",")...) + } + + return choices +} + +func getFlagXOR(tag *Tag) []string { + var xorGroups []string + + xorTags := tag.GetMany("xor") + for _, xor := range xorTags { + xorGroups = append(xorGroups, strings.Split(xor, ",")...) + } + + return xorGroups +} + +func getFlagAND(tag *Tag) []string { + var andGroups []string + + andTags := tag.GetMany("and") + for _, and := range andTags { + andGroups = append(andGroups, strings.Split(and, ",")...) + } + + return andGroups +} + +func getFlagNegatable(field reflect.StructField, tag *Tag) *string { + if !isBool(field.Type) { + return nil + } + + negatable, ok := tag.Get("negatable") + if !ok { + return nil + } + + return &negatable +} + +func getFlagDefault(tag *Tag) []string { + val, ok := tag.Get("default") + if !ok { + return nil + } + + return []string{val} +} + +func parseEnvTag(flagName string, field reflect.StructField, options *Opts) []string { + envTag := field.Tag.Get(DefaultEnvTag) + if envTag == "" { + // If no tag, generate a default name. + envVar := FlagToEnv(flagName, options.FlagDivider, options.EnvDivider) + if options.EnvPrefix != "" { + envVar = options.EnvPrefix + envVar + } + + return []string{envVar} + } + + if envTag == "-" { + return nil // `env:"-"` disables env var lookup entirely. + } + + var envNames []string + envVars := strings.Split(envTag, ",") + + for _, envName := range envVars { + envName = strings.TrimSpace(envName) + if envName == "" { + // If the tag is `env:""`, generate from the flag name. + envName = FlagToEnv(flagName, options.FlagDivider, options.EnvDivider) + } + + ignorePrefixes := false + if strings.HasPrefix(envName, "~") { + envName = envName[1:] + ignorePrefixes = true + } + + // Apply prefixes only if they are not being ignored. + if !ignorePrefixes { + // First, the struct-level flag prefix. + if options.Prefix != "" { + envName = FlagToEnv(options.Prefix, options.FlagDivider, options.EnvDivider) + envName + } + // Then, the global env prefix. + if options.EnvPrefix != "" { + envName = options.EnvPrefix + envName + } + } + envNames = append(envNames, envName) + } + + return envNames +} + +func markedFlagNotImplementing(tag Tag, val values.Value) bool { + _, flagOld := tag.Get("flag") + _, short := tag.Get("short") + _, long := tag.Get("long") + + return (flagOld || short || long) && val == nil +} diff --git a/internal/parser/utils.go b/internal/parser/utils.go new file mode 100644 index 0000000..bbbe7d1 --- /dev/null +++ b/internal/parser/utils.go @@ -0,0 +1,120 @@ +package parser + +import ( + "reflect" + "strings" +) + +// EnsureAddr we get the address of a given value. +func EnsureAddr(val reflect.Value) reflect.Value { + // Initialize if needed + var ptrval reflect.Value + + // We just want to get interface, even if nil + if val.Kind() == reflect.Ptr { + ptrval = val + } else { + ptrval = val.Addr() + } + + // Once we're sure it's a command, initialize the field if needed. + if ptrval.IsNil() { + ptrval.Set(reflect.New(ptrval.Type().Elem())) + } + + return ptrval +} + +// CamelToFlag transforms s from CamelCase to flag-case. +func CamelToFlag(s, flagDivider string) string { + splitted := split(s) + + return strings.ToLower(strings.Join(splitted, flagDivider)) +} + +// FlagToEnv transforms s from flag-case to CAMEL_CASE. +func FlagToEnv(s, flagDivider, envDivider string) string { + return strings.ToUpper(strings.ReplaceAll(s, flagDivider, envDivider)) +} + +// IsStringFalsy returns true if a string is considered "falsy" (empty, "false", "no", or "0"). +func IsStringFalsy(s string) bool { + return s == "" || s == "false" || s == "no" || s == "0" +} + +func isOptionGroup(value reflect.Value) bool { + return (value.Kind() == reflect.Struct || + (value.Kind() == reflect.Ptr && value.Type().Elem().Kind() == reflect.Struct)) && + !isSingleValue(value) +} + +func isBool(t reflect.Type) bool { + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + + return t.Kind() == reflect.Bool +} + +func isSet(tag *Tag, key string) bool { + // First, check if the key exists as a standalone tag (e.g., `hidden:"true"`). + // This is the standard go-flags and kong behavior. + if _, ok := tag.Get(key); ok { + return true + } + + // If not, check for sflags-style attributes within the main `flag` tag. + // e.g., `flag:"myflag f,hidden,deprecated"` + if flagTag, ok := tag.Get("flag"); ok { + // The attributes are comma-separated after the name/short-name part. + parts := strings.Split(flagTag, ",") + if len(parts) < 2 { + return false + } + + // Check the attributes list for the key. + attributes := parts[1:] + for _, attr := range attributes { + if strings.TrimSpace(attr) == key { + return true + } + } + } + + return false +} + +// prepareGroupVars merges variables from parent options, group tags, and global variables. +func prepareGroupVars(tag *Tag, parentOpts *Opts) map[string]string { + newVars := make(map[string]string) + for k, v := range parentOpts.Vars { + newVars[k] = v + } + for _, setVal := range tag.GetMany("set") { + parts := strings.SplitN(setVal, "=", 2) + if len(parts) == 2 { + newVars[parts[0]] = parts[1] + } + } + for k, v := range parentOpts.GlobalVars { + newVars[k] = v + } + + return newVars +} + +func expandVar(s string, vars map[string]string) string { + for k, v := range vars { + s = strings.ReplaceAll(s, "${"+k+"}", v) + } + + return s +} + +func expandStringSlice(s []string, vars map[string]string) []string { + for i, v := range s { + s[i] = expandVar(v, vars) + } + + return s +} diff --git a/internal/positional/argument.go b/internal/positional/argument.go index 2bd2977..402469d 100644 --- a/internal/positional/argument.go +++ b/internal/positional/argument.go @@ -4,46 +4,21 @@ import ( "errors" "fmt" "reflect" + "strconv" "strings" "sync" - "github.com/reeflective/flags/internal/convert" - "github.com/reeflective/flags/internal/tag" -) + "github.com/spf13/cobra" -// ErrRequired signals an argument field has not been -// given its minimum amount of positional words to use. -var ErrRequired = errors.New("required argument") + ierrors "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/parser" +) // WordConsumer is a function that has access to the array of positional slots, // giving a few functions to manipulate the list of words we want to parse. // As well, the current positional argument is a parameter, which is the only // positional slot we can access within the function. -type WordConsumer func(args *Args, current *Arg, dash int) error - -// WithWordConsumer allows to set a custom function to loop over -// the command words for a given positional slot. See WordConsumer. -func WithWordConsumer(args *Args, consumer WordConsumer) *Args { - args.consumer = consumer - - return args -} - -// Arg is a type used to store information and value references to -// a struct field we use as positional arg. This type is passed in -// many places, so that we can parse/convert and make informed -// decisions on how to handle those tasks. -type Arg struct { - Index int // The position in the struct (n'th struct field used as a slot) - Name string // name of the argument, either tag name or struct field - Minimum int // minimum number of arguments we want. - Maximum int // Maximum number of args we want (-1: infinite) - StartMin int // Index of first positional word for which we are used - StartMax int // if previous positional slots are full, this replaces startAt - Tag tag.MultiTag // struct tag - Value reflect.Value // A reference to the field value itself - Validator func(val string) error -} +type WordConsumer func(args *Args, current *parser.Positional, dash int) error // Args contains an entire list of positional argument "slots" (struct fields) // along with everything needed to parse a list of words onto them, taking into @@ -51,13 +26,14 @@ type Arg struct { // proper formatting and structure when one of these requirements are not satisfied. type Args struct { // A list of positional struct fields - slots []*Arg + slots []*parser.Positional // Requirements - totalMin int // Total count of required arguments - totalMax int // the maximum number of required arguments - allRequired bool // Are all positional slots required ? - noTags bool // Did we find at least one tag on a positional field ? + totalMin int // Total count of required arguments + totalMax int // the maximum number of required arguments + AllRequired bool // Are all positional slots required ? + noTags bool // Did we find at least one tag on a positional field ? + SoftPassthrough bool // If true, allows unparsed args to be passed to Execute. // Internal word management words []string // The list of arguments remaining to be parsed into their fields @@ -73,6 +49,46 @@ type Args struct { consumer WordConsumer } +// NewArgs creates a new, empty Args manager. +func NewArgs() *Args { + args := &Args{ + noTags: true, + } + args.consumer = args.consumeWords + + return args +} + +// ToCobraArgs converts the list of positional arguments into a cobra.PositionalArgs function. +func (args *Args) ToCobraArgs() cobra.PositionalArgs { + if len(args.slots) == 0 { + return func(cmd *cobra.Command, cargs []string) error { + SetRemainingArgs(cmd, cargs) + + return nil + } + } + + return func(cmd *cobra.Command, cargs []string) error { + // Apply the words on the all/some of the positional fields, + // returning any words that have not been parsed in fields, + // and an error if one of the positionals has failed. + retargs, err := args.Parse(cargs, cmd.ArgsLenAtDash()) + + // Once we have consumed the words we wanted, we update the + // command's return (non-consummed) arguments, to be passed + // later to the Execute(args []string) implementation. + defer SetRemainingArgs(cmd, retargs) + + // Directly return the error, which might be non-nil. + if err != nil { + return err + } + + return nil + } +} + // Parse acceps a list of command-line words to be ALL parsed as positional // arguments of a command. This function will parse each word into its proper // positional struct field (following quantity constraints/requirements), and @@ -84,6 +100,7 @@ func (args *Args) Parse(words []string, dash int) (retargs []string, err error) // Always set the return arguments when exiting. // This is used by command callers needing them + // as lambda parameters to the implementation. defer func() { retargs = args.words }() @@ -94,28 +111,26 @@ func (args *Args) Parse(words []string, dash int) (retargs []string, err error) // The positional slot consumes words as it needs, and only // returns an error when it cannot fulfill its requirements. - err := args.consumeWords(args, arg, dash) + err := args.consumer(args, arg, dash) // Either the positional argument has not had enough words - if errors.Is(err, ErrRequired) { - return retargs, args.positionalRequiredErr(*arg) + if errors.Is(err, ierrors.ErrRequired) { + return retargs, args.positionalRequiredErr(arg) } // Or we have failed to parse the word onto the struct field // value, most probably because it's the wrong type. - if errors.Is(err, convert.ErrConvertion) { - return retargs, err - } - - // Or return the error as is if err != nil { return retargs, err } } // Finally, if we have some return arguments, we verify that - // that the last positional was not a list with a maximum specified: - // This is to keep retrocompatibility with go-flags. Should be moved. + // the last positional was not a list with a maximum specified: + if args.SoftPassthrough { + return retargs, nil + } + return retargs, args.checkRequirementsFinal() } @@ -130,12 +145,12 @@ func (args *Args) ParseConcurrent(words []string) { for _, arg := range args.slots { // Make a copy of our positionals, so that each arg slot can // work on the same word list while doing different things. - argsC := args.copyArgs() + argsC := args.Copy() argsC.words = words workers.Add(1) - go func(arg *Arg) { + go func(arg *parser.Positional) { defer workers.Done() // If we don't have enough words for even @@ -155,20 +170,14 @@ func (args *Args) ParseConcurrent(words []string) { workers.Wait() } -// Positionals returns the list of "slots" that have been -// created when parsing a struct of positionals. -func (args *Args) Positionals() []*Arg { - return args.slots -} - -// copyArgs is used to make several instances of our args +// Copy is used to make several instances of our args // to work on the same list of command words (copies of it). -func (args *Args) copyArgs() *Args { +func (args *Args) Copy() *Args { return &Args{ slots: args.slots, totalMin: args.totalMin, totalMax: args.totalMax, - allRequired: args.allRequired, + AllRequired: args.AllRequired, needed: args.totalMin, noTags: args.noTags, done: 0, @@ -180,18 +189,18 @@ func (args *Args) copyArgs() *Args { // consumePositionals parses one or more words from the current list of positionals into // their struct fields, and returns once its own requirements are satisfied and/or the // next positional arguments require words to be passed along. -func (args *Args) consumeWords(self *Args, arg *Arg, dash int) error { +func (args *Args) consumeWords(self *Args, arg *parser.Positional, dash int) error { // As long as we've got a word, and nothing told us to quit. for !self.Empty() { // If we have reached the maximum number of args we accept. - if (self.parsed == arg.Maximum) && arg.Maximum != -1 { + if (self.parsed == arg.Max) && arg.Max != -1 { return nil } // If we have the minimum required, but there are // "just enough" (we assume it at least) words for // the next arguments, leave them the words. - if self.parsed >= arg.Minimum && self.allRemainingRequired() { + if self.parsed >= arg.Min && self.allRemainingRequired() { return nil } @@ -205,17 +214,10 @@ func (args *Args) consumeWords(self *Args, arg *Arg, dash int) error { // of arguments, we are cleared to consume one. next := args.Pop() - // If the positional slot has a validator function, - // run it before trying to convert the value. - if arg.Validator != nil { - if err := arg.Validator(next); err != nil { - return err - } - } // Parse the string value onto its native type, returning any errors. // We also break this loop immediately if we are not parsing onto a list. - if err := convert.Value(next, arg.Value, arg.Tag); err != nil { - return fmt.Errorf("%w: %s", convert.ErrConvertion, err.Error()) + if err := arg.PValue.Set(next); err != nil { + return fmt.Errorf("invalid value for %s: %w", arg.Name, err) } else if arg.Value.Type().Kind() != reflect.Slice { return nil } @@ -223,8 +225,8 @@ func (args *Args) consumeWords(self *Args, arg *Arg, dash int) error { // If we are still lacking some required words, // but we have exhausted the available ones. - if self.parsed < arg.Minimum { - return ErrRequired + if self.parsed < arg.Min { + return ierrors.ErrRequired } // Or we consumed all the arguments we wanted, without @@ -233,6 +235,36 @@ func (args *Args) consumeWords(self *Args, arg *Arg, dash int) error { return nil } +// SetRemainingArgs takes argument words that have not been parsed on positional struct fields, +// and stores them in the command annotations, to be passed to the command type's Execute() method. +func SetRemainingArgs(cmd *cobra.Command, retargs []string) { + if len(retargs) == 0 || retargs == nil || cmd == nil { + return + } + + if cmd.Annotations == nil { + cmd.Annotations = map[string]string{} + } + // Add these arguments in an annotation to be used + // in our Run implementation, where we pass just the + // unparsed positional arguments to the command Execute(args []string). + cmd.Annotations["flags"] = strings.Join(retargs, " ") +} + +// GetRemainingArgs fetches the unparsed argument words +// to be used in the command's Execute() method. +func GetRemainingArgs(cmd *cobra.Command) []string { + if cmd.Annotations == nil { + return nil + } + + if argString, found := cmd.Annotations["flags"]; found { + return strings.Split(argString, " ") + } + + return nil +} + // // Error check/build/format code ---------------------------------------------------------------------- // @@ -252,11 +284,15 @@ func (args *Args) checkRequirementsFinal() error { // any remaining slot being a list with a specified maximum value // cannot accept more than that, and will error out instead of // silently passing the excess args onto the Execute() parameters. - if isSlice && current.Value.Len() == current.Maximum && len(args.words) > 0 { - overweight := argHasTooMany(*current, len(args.words)) - msgErr := fmt.Sprintf("%s was not provided", overweight) + if isSlice && current.Value.Len() == current.Max && len(args.words) > 0 { + overweight := argHasTooMany(current, len(args.words)) + msgErr := overweight + + return fmt.Errorf("%w: %s", ierrors.ErrRequired, msgErr) + } - return fmt.Errorf("%w: %s", ErrRequired, msgErr) + if len(args.words) > 0 && !args.allRemainingRequired() { + return ierrors.ErrTooManyArguments } return nil @@ -264,25 +300,25 @@ func (args *Args) checkRequirementsFinal() error { // positionalErrorHandler makes a handler to be used in our argument handlers, // when they fail, to compute a precise error message on argument requirements. -func (args *Args) positionalRequiredErr(arg Arg) error { +func (args *Args) positionalRequiredErr(arg *parser.Positional) error { if names := args.getRequiredNames(arg); len(names) > 0 { var msg string if len(names) == 1 { - msg = fmt.Sprintf("%s was not provided", names[0]) + msg = names[0] + " was not provided" } else { msg = fmt.Sprintf("%s and %s were not provided", strings.Join(names[:len(names)-1], ", "), names[len(names)-1]) } - return fmt.Errorf("%w: %s", ErrRequired, msg) + return fmt.Errorf("%w: %s", ierrors.ErrRequired, msg) } return nil } // getRequiredNames is used by an argument handler to build the correct list of arguments we need. -func (args *Args) getRequiredNames(current Arg) (names []string) { +func (args *Args) getRequiredNames(current *parser.Positional) (names []string) { // For each of the EXISTING positional argument fields for index, arg := range args.slots { // Ignore all positional arguments that have not @@ -305,8 +341,8 @@ func (args *Args) getRequiredNames(current Arg) (names []string) { // If we have less words to parse than // the minimum required by this argument. - if arg.Value.Len() < arg.Minimum { - names = append(names, argHasNotEnough(*arg)) + if arg.Value.Len() < arg.Min { + names = append(names, argHasNotEnough(arg)) continue } @@ -316,45 +352,39 @@ func (args *Args) getRequiredNames(current Arg) (names []string) { } // makes a correct sentence when we don't have enough args. -func argHasNotEnough(arg Arg) string { +func argHasNotEnough(arg *parser.Positional) string { var arguments string - if arg.Minimum > 1 { - arguments = "arguments, but got only " + fmt.Sprintf("%d", arg.Value.Len()) + if arg.Min > 1 { + arguments = "arguments, but got only " + strconv.Itoa(arg.Value.Len()) } else { arguments = "argument" } - argRequired := "`" + arg.Name + " (at least " + fmt.Sprintf("%d", - arg.Minimum) + " " + arguments + ")`" + argRequired := "`" + arg.Name + " (at least " + strconv.Itoa(arg.Min) + " " + arguments + ")`" return argRequired } // makes a correct sentence when we have too much args. -func argHasTooMany(arg Arg, added int) string { - // The argument might be explicitly disabled... - if arg.Maximum == 0 { - return "`" + arg.Name + " (zero arguments)`" - } - +func argHasTooMany(arg *parser.Positional, added int) string { // Or just build the list accordingly. var parsed string - if arg.Maximum > 1 { - parsed = "arguments, but got " + fmt.Sprintf("%d", arg.Value.Len()+added) + if arg.Max > 1 { + parsed = "arguments, but got " + strconv.Itoa(arg.Value.Len()+added) } else { parsed = "argument" } - hasTooMany := "`" + arg.Name + " (at most " + fmt.Sprintf("%d", arg.Maximum) + " " + parsed + ")`" + hasTooMany := "`" + arg.Name + " (at most " + strconv.Itoa(arg.Max) + " " + parsed + ")`" return hasTooMany } -func isRequired(p *Arg) bool { - return (p.Value.Type().Kind() != reflect.Slice && (p.Minimum > 0)) || // Both must be true - p.Minimum != -1 || p.Maximum != -1 // And either of these +func isRequired(p *parser.Positional) bool { + return (p.Value.Type().Kind() != reflect.Slice && (p.Min > 0)) || // Both must be true + p.Min != -1 || p.Max != -1 // And either of these } // @@ -371,9 +401,9 @@ func (args *Args) setWords(words []string) { // setNext (re)sets the number of words parsed by // a single positional slot to 0, so that the next // positional using the words can set its own values. -func (args *Args) setNext(arg *Arg) { +func (args *Args) setNext(arg *parser.Positional) { args.parsed = 0 - args.offsetRange = arg.Minimum + args.offsetRange = arg.Min } func (args *Args) Empty() bool { @@ -421,11 +451,3 @@ func (args *Args) Pop() string { return arg } - -func (args *Args) peek() string { - if args.Empty() { - return "" - } - - return args.words[0] -} diff --git a/internal/positional/constants.go b/internal/positional/constants.go deleted file mode 100644 index a3422d4..0000000 --- a/internal/positional/constants.go +++ /dev/null @@ -1,7 +0,0 @@ -package positional - -const ( - baseParseInt = 10 - bitsizeParseInt = 32 - requiredNumParsedValues = 2 -) diff --git a/internal/positional/scan.go b/internal/positional/scan.go index ea8781e..3e31e29 100644 --- a/internal/positional/scan.go +++ b/internal/positional/scan.go @@ -3,274 +3,197 @@ package positional import ( "fmt" "reflect" - "strconv" - "strings" - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - "github.com/reeflective/flags/internal/validation" -) - -// ScanArgs scans an entire value (must be ensured to be a struct) and creates -// a list of positional arguments, along with many required minimum total number -// of arguments we need. Any non-nil error ends the scan, no matter where. -// The Args object returned is fully ready to parse a line of words onto itself. -func ScanArgs(val reflect.Value, stag tag.MultiTag, opts ...scan.OptFunc) (*Args, error) { - stype := val.Type() // Value type of the struct - req, _ := stag.Get("required") // this is written on the struct, applies to all - reqAll := len(req) != 0 // Each field will count as one required minimum - - // Prepare our scan options, some of which might be used on our positionals. - opt := scan.DefOpts().Apply(opts...) - - // Holds our positional slots and manages them - args := &Args{allRequired: reqAll, noTags: true} - - // Each positional field is scanned for its number requirements, - // and underlying value to be used by the command's arg handlers/converters. - for fieldCount := 0; fieldCount < stype.NumField(); fieldCount++ { - field := stype.Field(fieldCount) - fieldValue := val.Field(fieldCount) - - // The args objects stores everything related to this slot - // when parsing is successful, or returns an unrecoverable error. - err := args.scanArg(field, fieldValue, reqAll, opt) - if err != nil { - return nil, err - } - } + "github.com/spf13/cobra" - // Depending on our position and type, we reset the maximum - // number of words allowed for this argument, and update the - // counter that will be used by handlers to sync their use - // of words - if err := args.adjustMaximums(); err != nil { - return args, err - } - - // Last minute internal counters adjustments - args.needed = args.totalMin + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/parser" +) - // By default, the positionals have a consumer made - // to parse a list of command words onto our struct. - args.consumer = args.consumeWords +const ( + baseParseInt = 10 + bitsizeParseInt = 32 + requiredNumParsedValues = 2 +) - return args, nil -} +// ParseStruct scans a legacy `positional-args` struct and returns a populated +// Args argument manager. It acts as a bridge to the new parser-centric logic. +func ParseStruct(val reflect.Value, stag *parser.Tag, opts ...parser.OptFunc) (*Args, error) { + // Prepare our scan options. + opt := parser.DefOpts().Apply(opts...) -// scanArg scans a single struct field as positional argument, and sets everything related to it. -func (args *Args) scanArg(field reflect.StructField, value reflect.Value, reqAll bool, opt scan.Opts) error { - ptag, name, err := parsePositionalTag(field) + // The parser package is now the source of truth for scanning. + positionals, err := parser.ParsePositionalStruct(val, stag, opt) if err != nil { - return err + return nil, err } - if _, isSet := ptag.Get("required"); isSet { - args.noTags = false + // Create a new runtime manager and populate it. + args := NewArgs() + if _, isSet := stag.Get("passthrough"); isSet { + args.SoftPassthrough = true } - - // Set min/max requirements depending on the tag, the overall - // requirement settings (at struct level), also taking into - // account the kind of field we are considering (slice or not) - min, max := positionalReqs(value, ptag, reqAll) - - arg := &Arg{ - Index: len(args.slots), - Name: name, - Minimum: min, - Maximum: max, - Tag: ptag, - StartMin: args.totalMin, - StartMax: args.totalMax, - Value: value, + for _, pos := range positionals { + args.Add(pos) } - args.slots = append(args.slots, arg) - args.totalMin += min // min is never < 0 + return args, nil +} - // The total maximum number of arguments is used - // by completers to know precisely when they should - // start completing for a given positional field slot. - if arg.Maximum != -1 { - args.totalMax += arg.Maximum +// Finalize runs adjustments on the argument list after all arguments have been added. +func (args *Args) Finalize(cmd *cobra.Command) error { + // Validate ambiguous passthrough combinations. + if args.SoftPassthrough && len(args.slots) > 0 { + lastArg := args.slots[len(args.slots)-1] + if lastArg.Max == -1 { + return fmt.Errorf("ambiguous configuration: container-level passthrough cannot be used with a greedy positional argument ('%s')", lastArg.Name) + } } - // Set validators - var choices []string + // Validate field-level passthrough arguments. + for i, arg := range args.slots { + if arg.Passthrough && i < len(args.slots)-1 { + return fmt.Errorf("passthrough argument %s must be the last positional argument", arg.Name) + } + } - choiceTags := ptag.GetMany("choice") + for _, arg := range args.slots { + if arg.Passthrough { + cmd.Flags().SetInterspersed(false) - for _, choice := range choiceTags { - choices = append(choices, strings.Split(choice, " ")...) + break + } } - if validator := validation.Bind(value, field, choices, opt); validator != nil { - arg.Validator = validator + if err := validateGreedySlices(args.slots); err != nil { + return err } + constrainGreedySlicesT(args.slots) + applyDefaultAdjustmentsT(args.slots, args.AllRequired, args.noTags) + args.needed = args.totalMin + return nil } -// parsePositionalTag extracts and fully parses a struct (positional) field tag. -func parsePositionalTag(field reflect.StructField) (tag.MultiTag, string, error) { - tag, _, err := tag.GetFieldTag(field) - if err != nil { - return tag, field.Name, fmt.Errorf("%w: %s", scan.ErrScan, err) - } +// Add adds a new positional argument slot to the manager. +// This function takes care of recomputing total positional +// requirements and updates the positional argument manager. +func (args *Args) Add(arg *parser.Positional) { + args.slots = append(args.slots, arg) - name, _ := tag.Get("positional-arg-name") + // First set the argument itself. + arg.StartMax = args.totalMax - if len(name) == 0 { - name = field.Name + // The total min/max number of arguments is used + // by completers to know precisely when they should + // start completing for a given positional field slot. + args.totalMin += arg.Min // min is never < 0 + + if arg.Max != -1 { + args.totalMax += arg.Max } +} - return tag, name, nil +// Positionals returns the list of "slots" that have been +// created when parsing a struct of positionals. +func (args *Args) Positionals() []*parser.Positional { + return args.slots } -// positionalReqs determines the correct quantity requirements for a positional field, -// depending on its parsed struct tag values, and the underlying type of the field. -func positionalReqs(val reflect.Value, mtag tag.MultiTag, all bool) (min, max int) { - required, max, set := parseArgsNumRequired(mtag) +// WithWordConsumer allows to set a custom function to loop over +// the command words for a given positional slot. See WordConsumer. +func WithWordConsumer(args *Args, consumer WordConsumer) *Args { + args.consumer = consumer - // At least for each requirements are global - if all && required == 0 { - min = 1 - } + return args +} - // When the argument field is not a slice, we have to adjust for some defaults - isSlice := val.Type().Kind() == reflect.Slice || val.Type().Kind() == reflect.Map - if !isSlice { - max = 1 - } +// validateGreedySlices checks for invalid positional argument configurations +// where a "greedy" slice (one with no maximum) is followed by another slice, +// which would be impossible to parse. +func validateGreedySlices(args []*parser.Positional) error { + var greedySliceFound bool + var greedySliceName string + + for _, arg := range args { + isSlice := arg.Value.Type().Kind() == reflect.Slice || arg.Value.Type().Kind() == reflect.Map - switch { - case !isSlice && required > 0: - // Individual fields cannot have more than one required - min = 1 - case !set && !isSlice && all: - // If we have a struct of untagged fields, but all required, - // we automatically set min/max to one if the field is individual. - min = 1 - case set && isSlice && required > 0: - // If a slice has at least one required, add this minimum - // Increase the total number of positional args wanted. - min += required + // If we have already found a greedy slice, and we encounter another + // slice of any kind, it's an error because it's shadowed. + if greedySliceFound && isSlice && arg.Max == -1 { + return errorSliceShadowingT(arg.Name, greedySliceName) + } + + // Check if the current argument is a greedy slice. + if isSlice && arg.Max == -1 { + greedySliceFound = true + greedySliceName = arg.Name + } } - return min, max + return nil } -// parseArgsNumRequired sets the minimum/maximum requirements for an argument field. -func parseArgsNumRequired(fieldTag tag.MultiTag) (required, maximum int, set bool) { - required = 0 - maximum = -1 +// errorSliceShadowing formats an error indicating that a greedy +// positional slice is making a subsequent greedy slice unreachable. +func errorSliceShadowingT(shadowingArgName, shadowedArgName string) error { + details := fmt.Sprintf("positional `%s` is shadowed by `%s`, which is a greedy slice", + shadowedArgName, + shadowingArgName) - sreq, set := fieldTag.Get("required") - - // If no requirements, -1 means unlimited - if sreq == "" || !set { - return - } + return fmt.Errorf("%w: %s", errors.ErrPositionalShadowing, details) +} - required = 1 +// constrainGreedySlices iterates through the positional +// arguments and constrains any greedy slice that is followed +// by another greedy slice by setting its maximum to its minimum. +func constrainGreedySlicesT(args []*parser.Positional) { + for pos, arg := range args { + // We only care about slices that are currently "greedy" (no max set). + isSlice := arg.Value.Type().Kind() == reflect.Slice || arg.Value.Type().Kind() == reflect.Map + if !isSlice || arg.Max != -1 { + continue + } - rng := strings.SplitN(sreq, "-", requiredNumParsedValues) + // Look ahead to see if this greedy slice is followed by ANOTHER greedy slice. + for j := pos + 1; j < len(args); j++ { + nextArg := args[j] + nextIsSlice := nextArg.Value.Type().Kind() == reflect.Slice || nextArg.Value.Type().Kind() == reflect.Map - if len(rng) > 1 { - if preq, err := strconv.ParseInt(rng[0], baseParseInt, bitsizeParseInt); err == nil { - required = int(preq) - } + // If the next slice is ALSO greedy (max == -1), then the current one must be constrained. + if nextIsSlice && nextArg.Max == -1 && nextArg.Min > 0 { + arg.Max = arg.Min - if preq, err := strconv.ParseInt(rng[1], baseParseInt, bitsizeParseInt); err == nil { - maximum = int(preq) - } - } else { - if preq, err := strconv.ParseInt(sreq, baseParseInt, bitsizeParseInt); err == nil { - required = int(preq) + break // The current arg is now constrained, move to the next one in the outer loop. + } } } - - return required, maximum, set } -// adjustMaximums analyzes the position of a positional argument field, -// and adjusts its maximum so that handlers can work on them correctly. -func (args *Args) adjustMaximums() error { - for _, arg := range args.slots { +// applyDefaultAdjustments handles miscellaneous adjustments for positional arguments, +// such as setting default maximums for non-slice fields and handling untagged required slices. +func applyDefaultAdjustmentsT(args []*parser.Positional, allRequired, noTags bool) { + for _, arg := range args { val := arg.Value isSlice := val.Type().Kind() == reflect.Slice || val.Type().Kind() == reflect.Map - // First, the maximum index at which we should start - // parsing words can never be smaller than the minimum one if arg.StartMax < arg.StartMin { arg.StartMax = arg.StartMin } - // The maximum is not left to -1 if the field is unique. - if arg.Maximum == -1 && !isSlice { - arg.Maximum = 1 - - if args.allRequired { - arg.Minimum = 1 + if arg.Max == -1 && !isSlice { + arg.Max = 1 + if allRequired { + arg.Min = 1 } continue } - if isSlice && args.allRequired && args.noTags { - arg.Minimum = 1 + if isSlice && allRequired && noTags { + arg.Min = 1 } } - - return nil -} - -// func (args *Args) adjustMaximums() error { -// // hasSliceNoMax := false -// -// for _, arg := range args.slots { -// val := arg.Value -// isSlice := val.Type().Kind() == reflect.Slice || -// val.Type().Kind() == reflect.Map -// -// // First, the maximum index at which we should start -// // parsing words can never be smaller than the minimum one -// if arg.StartMax < arg.StartMin { -// arg.StartMax = arg.StartMin -// } -// -// // If we have a slice with no maximum before, it's always -// // going to shadow all remaining positional slots. -// // if hasSliceNoMax && args.allRequired { -// // return args.errorSliceShadowing(arg.Name, arg.Index) -// // } -// -// // The maximum is not left to -1 if the field is unique. -// if arg.Maximum == -1 && !isSlice { -// arg.Maximum = 1 -// -// continue -// } -// -// if isSlice && args.allRequired && args.noTags { -// arg.Minimum = 1 -// } -// -// // if isSlice && arg.Maximum == -1 { -// // hasSliceNoMax = true -// // } -// } -// -// return nil -// } - -func (args *Args) errorSliceShadowing(arg string, index int) error { - shadowed := "" - for _, arg := range args.slots[index+1:] { - shadowed += fmt.Sprintf(" `%s`,", arg.Name) - } - shadowed = strings.TrimSuffix(shadowed, ",") - - return fmt.Errorf("Positional `%s` is a slice with no maximum: will shadow%s positionals", arg, shadowed) } diff --git a/internal/scan/opts.go b/internal/scan/opts.go deleted file mode 100644 index 520a368..0000000 --- a/internal/scan/opts.go +++ /dev/null @@ -1,63 +0,0 @@ -package scan - -import ( - "reflect" - - "github.com/reeflective/flags/internal/tag" -) - -const ( - DefaultDescTag = "desc" - DefaultFlagTag = "flag" - DefaultEnvTag = "env" - DefaultFlagDivider = "-" - DefaultEnvDivider = "_" - DefaultFlatten = true -) - -// ValidateFunc describes a validation func, that takes string val for flag from command line, -// field that's associated with this flag in structure cfg. Also works for positional arguments. -// Should return error if validation fails. -type ValidateFunc func(val string, field reflect.StructField, cfg interface{}) error - -// FlagFunc is a generic function that can be applied to each -// value that will end up being a flags *Flag, so that users -// can perform more arbitrary operations on each, such as checking -// for completer implementations, bind to viper configurations, etc. -type FlagFunc func(flag string, tag tag.MultiTag, val reflect.Value) error - -// OptFunc sets values in opts structure. -type OptFunc func(opt *Opts) - -type Opts struct { - DescTag string - FlagTag string - Prefix string - EnvPrefix string - FlagDivider string - EnvDivider string - Flatten bool - ParseAll bool - Validator ValidateFunc - FlagFunc FlagFunc -} - -func (o Opts) Apply(optFuncs ...OptFunc) Opts { - for _, optFunc := range optFuncs { - optFunc(&o) - } - - return o -} - -func CopyOpts(val Opts) OptFunc { return func(opt *Opts) { *opt = val } } - -func DefOpts() Opts { - return Opts{ - DescTag: DefaultDescTag, - FlagTag: DefaultFlagTag, - FlagDivider: DefaultFlagDivider, - EnvDivider: DefaultEnvDivider, - Flatten: DefaultFlatten, - } -} diff --git a/internal/scan/scan.go b/internal/scan/scan.go deleted file mode 100644 index f3b4ead..0000000 --- a/internal/scan/scan.go +++ /dev/null @@ -1,108 +0,0 @@ -package scan - -import ( - "errors" - "fmt" - "reflect" - - "github.com/reeflective/flags/internal/tag" -) - -// ErrNotPointerToStruct indicates that a provided data container is not a pointer -// to a struct. Only pointers to structs are valid data containers for options. -var ErrNotPointerToStruct = errors.New("object must be a pointer to struct or interface") - -// ErrScan indicates an error in scanning struct fields. -var ErrScan = errors.New("scan error") - -// Handler is a generic handler used for scanning both commands and group structs alike. -type Handler func(reflect.Value, *reflect.StructField) (bool, error) - -// Type actually scans the type, recursively if needed. -func Type(data interface{}, handler Handler) error { - // Get all the public fields in the data struct - ptrval := reflect.ValueOf(data) - - if ptrval.Type().Kind() != reflect.Ptr { - return ErrNotPointerToStruct - } - - stype := ptrval.Type().Elem() - - if stype.Kind() != reflect.Struct { - return ErrNotPointerToStruct - } - - realval := reflect.Indirect(ptrval) - - if err := scanStruct(realval, nil, handler); err != nil { - return err - } - - return nil -} - -// scanStruct performs an exhaustive scan of a struct that we found as field (embedded), -// either with the specified scanner, or manually -in which case we will recursively scan -// embedded structs themselves. -func scanStruct(val reflect.Value, sfield *reflect.StructField, scan Handler) error { - stype := val.Type() - - // We are being passed a field only when a have a "root struct" - // already being parsed, a kind of reference point. It can be - // either for scanning for a subcommand, a group of options, - // or even a group of subcommands. - if sfield != nil { - if ok, err := scan(val, sfield); err != nil { - return err - } else if ok { - return nil - } - } - - // But most of the time we end up here, and look each field again. - for fieldCount := 0; fieldCount < stype.NumField(); fieldCount++ { - field := stype.Field(fieldCount) - fieldValue := val.Field(fieldCount) - - // Scan the field for either a subgroup (if the field is a struct) - // or for an option. Any error cancels the scan and is immediately returned. - if err := scanField(fieldValue, field, scan); err != nil { - return err - } - } - - return nil -} - -// scanField attempts to grab a tag on a struct field, and depending on the field's type, -// either scans recursively if the field is an embedded struct/pointer, or attempts to scan -// the field as an option of the group. -func scanField(val reflect.Value, field reflect.StructField, scan Handler) error { - // Get the field tag and return/continue if failed/needed - _, skip, err := tag.GetFieldTag(field) - if err != nil { - return fmt.Errorf("%w: %s", tag.ErrTag, err.Error()) - } else if skip { - return nil - } - - kind := field.Type.Kind() - structPointer := (kind == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct) - - // We are just interested in the actual type of the field to - // be a struct, regardless of it's pointer to one or not. - // Also, we never initialize nil pointers by default, since - // we want to preserve the given struct as much as possible. - if kind == reflect.Struct || structPointer { - return scanStruct(val, &field, scan) - } - - // By default, always try to scan the field as an option. - // If an error is thrown in the process, immediately return it. - if _, err := scan(val, &field); err != nil { - return err - } - - return nil -} diff --git a/internal/validation/errors.go b/internal/validation/errors.go new file mode 100644 index 0000000..b98ccff --- /dev/null +++ b/internal/validation/errors.go @@ -0,0 +1,41 @@ +package validation + +import ( + "fmt" + "regexp" + "strings" +) + +const ( + validTag = "validate" +) + +// invalidVarError wraps an error raised by validator on a struct field, +// and automatically modifies the error string for more efficient ones. +type invalidVarError struct { + fieldName string + fieldValue string // This is the string representation of the value + validatorErr error +} + +// Error implements the Error interface, but replacing some identifiable +// validation errors with more efficient messages, more adapted to CLI. +func (err *invalidVarError) Error() string { + var tagname string + + // Match the part containing the tag name + retag := regexp.MustCompile(`the '.*' tag`) + + matched := retag.FindString(err.validatorErr.Error()) + if matched != "" { + parts := strings.Split(matched, " ") + if len(parts) > 1 { + tagname = strings.Trim(parts[1], "'") + } + + return fmt.Sprintf("`%s` is not a valid %s", err.fieldValue, tagname) + } + + // Or simply replace the empty key with the field name. + return strings.ReplaceAll(err.validatorErr.Error(), "''", fmt.Sprintf("'%s'", err.fieldName)) +} diff --git a/internal/validation/validation.go b/internal/validation/validation.go index b7312bd..62414fb 100644 --- a/internal/validation/validation.go +++ b/internal/validation/validation.go @@ -1,28 +1,71 @@ package validation import ( - "errors" + "fmt" "reflect" + "slices" "strings" - "github.com/reeflective/flags/internal/scan" -) + "github.com/go-playground/validator/v10" -// ErrInvalidChoice indicates that the provided flag argument is not among the valid choices. -var ErrInvalidChoice = errors.New("invalid choice") + "github.com/reeflective/flags/internal/errors" +) // ValueValidator is the interface implemented by types that can validate a // flag argument themselves. The provided value is directly passed from the // command line. This interface has been retroported from jessevdk/go-flags. type ValueValidator interface { - // IsValidValue returns an error if the provided string value is valid for - // the flag. + // IsValidValue returns an error if the provided + // string value is invalid for the flag. IsValidValue(value string) error } -// Bind builds a validation function including all validation routines (builtin or user-defined) available. -func Bind(value reflect.Value, field reflect.StructField, choices []string, opt scan.Opts) func(val string) error { - if opt.Validator == nil && len(choices) == 0 { +// ValidateFunc describes a validation func, that takes string val for flag from command line, +// field that's associated with this flag in structure cfg. Also works for positional arguments. +// Should return error if validation fails. +type ValidateFunc func(val string, field reflect.StructField, data any) error + +// validatorFunc is a function signature used to bridge go-playground/validator +// logic and our own struct-field based ValidateFunc signatures. +type validatorFunc func(value any, validationTag string, fieldName string) error + +// NewDefault generates and sets up a default validation engine +// provided by go-playground/validator. The library consumer only +// has to declare "validate" tags for the validation to work. +func NewDefault() ValidateFunc { + v := validator.New() + + validations := func(value any, validationTag string, fieldName string) error { + if err := v.Var(value, validationTag); err != nil { + // We need the string representation of the value for error reporting. + // For now, we'll use fmt.Sprintf, but this might need refinement + // depending on how 'fieldValue' is used in invalidVarError. + return &invalidVarError{fieldName, fmt.Sprintf("%v", value), err} + } + + return nil + } + + return bindValidatorToField(validations) +} + +// NewWith returns a ValidateFunc that uses a custom go-playground/validator instance, +// on which the user can prealably register any custom validation routines. +func NewWith(custom *validator.Validate) ValidateFunc { + validator := func(value any, validationTag string, fieldName string) error { + if err := custom.Var(value, validationTag); err != nil { + return &invalidVarError{fieldName, fmt.Sprintf("%v", value), err} + } + + return nil + } + + return bindValidatorToField(validator) +} + +// Setup builds a validation function including all validation routines (builtin or user-defined) available. +func Setup(val reflect.Value, fld reflect.StructField, choices []string, validator ValidateFunc) func(val string) error { + if validator == nil && len(choices) == 0 { return nil } @@ -30,24 +73,26 @@ func Bind(value reflect.Value, field reflect.StructField, choices []string, opt allValues := strings.Split(argValue, ",") // The validation is performed on each individual item of a (potential) array - for _, val := range allValues { + for _, word := range allValues { if len(choices) > 0 { - if err := validateChoice(val, choices); err != nil { + if err := validateChoice(word, choices); err != nil { + return err } } // If choice is valid or arbitrary, run custom validator. - if opt.Validator != nil { - if err := opt.Validator(val, field, value.Interface()); err != nil { - return err + if validator != nil { + if err := validator(word, fld, val.Interface()); err != nil { + + return fmt.Errorf("%w: %w", errors.ErrInvalidValue, err) } } // Retroporting from jessevdk/go-flags - if validator, implemented := value.Interface().(ValueValidator); implemented { - if err := validator.IsValidValue(val); err != nil { - return err + if validator, implemented := val.Interface().(ValueValidator); implemented { + if err := validator.IsValidValue(word); err != nil { + return fmt.Errorf("%w: %w", errors.ErrInvalidValue, err) } } } @@ -58,25 +103,36 @@ func Bind(value reflect.Value, field reflect.StructField, choices []string, opt return validation } +// bindValidatorToField is a helper function for the parser. +// It takes a ValidateFunc (the simplified one) and returns a function +// that matches the parser's expected signature for a validator. +// This function extracts the necessary information from reflect.StructField +// and passes it to the simplified ValidateFunc. +// This function is intended to be used by the parser package. +func bindValidatorToField(validator validatorFunc) ValidateFunc { + if validator == nil { + return nil + } + + return func(valStr string, field reflect.StructField, _ any) error { + validationTag := field.Tag.Get(validTag) + // if validationTag == "" { + // return nil // No validation tag, nothing to validate + // } + + return validator(valStr, validationTag, field.Name) + } +} + // validateChoice checks the given value(s) is among valid choices. func validateChoice(val string, choices []string) error { values := strings.Split(val, ",") for _, value := range values { - if !stringInSlice(value, choices) { - return ErrInvalidChoice + if !slices.Contains(choices, value) { + return errors.ErrInvalidChoice } } return nil } - -func stringInSlice(a string, list []string) bool { - for _, b := range list { - if b == a { - return true - } - } - - return false -} diff --git a/cmd/genvalues/main.go b/internal/values/genvalues/main.go similarity index 79% rename from cmd/genvalues/main.go rename to internal/values/genvalues/main.go index 83d3a61..a73b5e8 100644 --- a/cmd/genvalues/main.go +++ b/internal/values/genvalues/main.go @@ -18,7 +18,7 @@ import ( ) const ( - tmpl = `package flags + tmpl = `package values // This file is autogenerated by "go generate .". Do not modify. @@ -29,13 +29,14 @@ import ( {{$mapKeyTypes := .MapKeysTypes}} -// MapAllowedKinds stores list of kinds allowed for map keys. -var MapAllowedKinds = []reflect.Kind{ \nn +// mapAllowedKinds stores list of kinds allowed for map keys. +var mapAllowedKinds = []reflect.Kind{ \nn {{range $mapKeyTypes}} reflect.{{. | Title}},{{end}} } -func parseGenerated(value interface{}) Value { +// ParseGenerated generates a flag with underlying interface type. +func ParseGenerated(value any, sep *string) Value { switch value.(type) { {{range .Values}}{{ if eq (.|InterfereType) (.Type) }}\nn case *{{.Type}}: @@ -43,31 +44,33 @@ func parseGenerated(value interface{}) Value { {{ end }}{{ end }}\nn {{range .Values}}{{ if not .NoSlice }}\nn case *[]{{.Type}}: - return new{{.|Plural}}Value(value.(*[]{{.Type}})) - {{end}}{{end}}\nn + return new{{.|Plural}}Value(value.(*[]{{.Type}}), sep) + {{end}}{{end}} default: return nil } } -func parseGeneratedPtrs(value interface{}) Value { +// ParseGenerated generates a flag with underlying ptr type. +func ParseGeneratedPtrs(value any) Value { switch value.(type) { - {{range .Values}}{{ if ne (.|InterfereType) (.Type) }}\nn + {{range .Values}}{{ if ne (.|InterfereType) (.Type) }} case *{{.Type}}: return new{{.|Name}}Value(value.(*{{.Type}})) - {{end}}{{end}}\nn + {{end}}{{end}} default: return nil } } -func parseGeneratedMap(value interface{}) Value { +// ParseGenerated generates a flag with underlying map type. +func ParseGeneratedMap(value any, sep *string) Value { switch value.(type) { - {{range .Values}}{{ if not .NoMap }}\nn - {{ $value := . }}{{range $mapKeyTypes}}\nn + {{range .Values}}{{ if not .NoMap }} + {{ $value := . }}{{range $mapKeyTypes}} case *map[{{.}}]{{$value.Type}}: - return new{{MapValueName $value . | Title}}(value.(*map[{{.}}]{{$value.Type}})) - {{end}}{{end}}{{end}}\nn + return new{{MapValueName $value . | Title}}(value.(*map[{{.}}]{{$value.Type}}), sep) + {{end}}{{end}}{{end}} default: return nil } @@ -88,26 +91,26 @@ func new{{.|Name}}Value(p *{{.Type}}) *{{.|ValueName}} { } func (v *{{.|ValueName}}) Set(s string) error { - {{if .Parser }}\nn + {{if .Parser }} parsed, err := {{.Parser}} if err == nil { - {{if .Convert}}\nn + {{if .Convert}} *v.value = ({{.Type}})(parsed) - {{else}}\nn + {{else}} *v.value = parsed - {{end}}\nn + {{end}} return nil } return err - {{ else }}\nn + {{ else }} *v.value = s return nil - {{end}}\nn + {{end}} } -func (v *{{.|ValueName}}) Get() interface{} { +func (v *{{.|ValueName}}) Get() any { if v != nil && v.value != nil { -{{/* flag package create zero Value and compares it to actual Value */}}\nn +{{/* flag package create zero Value and compares it to actual Value */}} return *v.value } return nil @@ -115,7 +118,7 @@ func (v *{{.|ValueName}}) Get() interface{} { func (v *{{.|ValueName}}) String() string { if v != nil && v.value != nil { -{{/* flag package create zero Value and compares it to actual Value */}}\nn +{{/* flag package create zero Value and compares it to actual Value */}} return {{.|Format}} } return "" @@ -127,8 +130,9 @@ func (v *{{.|ValueName}}) Type() string { return "{{.|Type}}" } // -- {{.Type}}Slice Value type {{.|SliceValueName}} struct{ - value *[]{{.Type}} - changed bool + value *[]{{.Type}} + changed bool + separator string } var _ RepeatableFlag = (*{{.|SliceValueName}})(nil) @@ -136,14 +140,29 @@ var _ Value = (*{{.|SliceValueName}})(nil) var _ Getter = (*{{.|SliceValueName}})(nil) -func new{{.|Name}}SliceValue(slice *[]{{.Type}}) *{{.|SliceValueName}} { - return &{{.|SliceValueName}}{ +func new{{.|Name}}SliceValue(slice *[]{{.Type}}, sep *string) *{{.|SliceValueName}} { + s := &{{.|SliceValueName}}{ value: slice, } + if sep != nil { + s.separator = *sep + } + return s } func (v *{{.|SliceValueName}}) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } + {{if .Parser }} out := make([]{{.Type}}, len(ss)) for i, s := range ss { @@ -151,11 +170,11 @@ func (v *{{.|SliceValueName}}) Set(raw string) error { if err != nil { return err } - {{if .Convert}}\nn + {{if .Convert}} out[i] = ({{.Type}})(parsed) - {{else}}\nn + {{else}} out[i] = parsed - {{end}}\nn + {{end}} } {{ else }}out := ss{{end}} if !v.changed { @@ -167,9 +186,9 @@ func (v *{{.|SliceValueName}}) Set(raw string) error { return nil } -func (v *{{.|SliceValueName}}) Get() interface{} { +func (v *{{.|SliceValueName}}) Get() any { if v != nil && v.value != nil { -{{/* flag package create zero Value and compares it to actual Value */}}\nn +{{/* flag package create zero Value and compares it to actual Value */}} return *v.value } return ([]{{.Type}})(nil) @@ -177,7 +196,7 @@ func (v *{{.|SliceValueName}}) Get() interface{} { func (v *{{.|SliceValueName}}) String() string { if v == nil || v.value == nil { -{{/* flag package create zero Value and compares it to actual Value */}}\nn +{{/* flag package create zero Value and compares it to actual Value */}} return "[]" } out := make([]string, 0, len(*v.value)) @@ -200,7 +219,8 @@ func (v *{{.|SliceValueName}}) IsCumulative() bool { {{range $mapKeyTypes}} // -- {{ MapValueName $value . }} type {{ MapValueName $value . }} struct { - value *map[{{.}}]{{$value.Type}} + value *map[{{.}}]{{$value.Type}} + separator string } var _ RepeatableFlag = (*{{MapValueName $value .}})(nil) @@ -208,14 +228,28 @@ var _ Value = (*{{MapValueName $value .}})(nil) var _ Getter = (*{{MapValueName $value .}})(nil) -func new{{MapValueName $value . | Title}}(m *map[{{.}}]{{$value.Type}}) *{{MapValueName $value .}} { - return &{{MapValueName $value .}}{ +func new{{MapValueName $value . | Title}}(m *map[{{.}}]{{$value.Type}}, sep *string) *{{MapValueName $value .}} { + s := &{{MapValueName $value .}}{ value: m, } + if sep != nil { + s.separator = *sep + } + return s } func (v *{{MapValueName $value .}}) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -227,40 +261,40 @@ func (v *{{MapValueName $value .}}) Set(val string) error { s = ss[0] - {{if $kindVal.Parser }}\nn + {{if $kindVal.Parser }} parsedKey, err := {{$kindVal.Parser}} if err != nil { return err } - {{if $kindVal.Convert}}\nn + {{if $kindVal.Convert}} key := ({{$kindVal.Type}})(parsedKey) - {{else}}\nn + {{else}} key := parsedKey - {{end}}\nn + {{end}} - {{ else }}\nn + {{ else }} key := s - {{end}}\nn + {{end}} s = ss[1] - {{if $value.Parser }}\nn + {{if $value.Parser }} parsedVal, err := {{$value.Parser}} if err != nil { return err } - {{if $value.Convert}}\nn + {{if $value.Convert}} val := ({{$value.Type}})(parsedVal) - {{else}}\nn + {{else}} val := parsedVal - {{end}}\nn + {{end}} - {{ else }}\nn + {{ else }} val := s - {{end}}\nn + {{end}} (*v.value)[key] = val } @@ -268,7 +302,7 @@ func (v *{{MapValueName $value .}}) Set(val string) error { return nil } -func (v *{{MapValueName $value .}}) Get() interface{} { +func (v *{{MapValueName $value .}}) Get() any { if v != nil && v.value != nil { {{/* flag package create zero Value and compares it to actual Value */}}\nn return *v.value @@ -297,7 +331,7 @@ func (v *{{MapValueName $value .}}) IsCumulative() bool { {{end}} ` - testTmpl = `package flags + testTmpl = `package values // This file is autogenerated by "go generate .". Do not modify. @@ -334,11 +368,11 @@ func Test{{.|Name}}Value(t *testing.T) { {{ if ne ($value|InterfereType) ($value.Type) }}\nn a := new({{$value|InterfereType}}) v := new{{$value|Name}}Value(&a) - assert.Equal(t, parseGeneratedPtrs(&a), v) + assert.Equal(t, ParseGeneratedPtrs(&a), v) {{ else }}\nn a := new({{$value.Type}}) v := new{{$value|Name}}Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) {{ end }}\nn err := v.Set("{{.In}}") {{if .Err}}\nn @@ -394,8 +428,8 @@ func Test{{.|Name}}SliceValue(t *testing.T) { t.Parallel() var err error a := new([]{{$value.Type}}) - v := new{{$value|Name}}SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := new{{$value|Name}}SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) {{range .In}}\nn err = v.Set("{{.}}") @@ -422,8 +456,8 @@ func Test{{MapValueName $value $keyType | Title}}(t *testing.T) { t.Parallel() var err error a := make(map[{{$keyType}}]{{$value.Type}}) - v := new{{MapValueName $value $keyType | Title}}(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := new{{MapValueName $value $keyType | Title}}(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) {{range .In}}\nn err = v.Set("{{$keyType | KindTest}}{{.}}") @@ -457,14 +491,14 @@ func Test{{MapValueName $value $keyType | Title}}(t *testing.T) { func TestParseGeneratedMap_NilDefault(t *testing.T) { t.Parallel() a := new(bool) - v := parseGeneratedMap(a) + v := ParseGeneratedMap(a, nil) assert.Nil(t, v) } ` ) -// MapAllowedKinds stores list of kinds allowed for map keys. +// mapAllowedKinds stores list of kinds allowed for map keys. var mapAllowedKinds = []reflect.Kind{ reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, @@ -477,7 +511,7 @@ type test struct { } func (t *test) String() string { - return fmt.Sprintf("in: %s", t.In) + return "in: " + t.In } type sliceTest struct { @@ -589,7 +623,7 @@ func main() { return value{} }, - "KindTest": func(kind string) interface{} { + "KindTest": func(kind string) any { if kind == "string" { return randStr(5) } @@ -680,6 +714,7 @@ func stringifyKinds(kinds []reflect.Kind) []string { func gofmt(path string) { cmd := exec.Command("goimports", "-w", path) + b, err := cmd.CombinedOutput() if err != nil { log.Fatalf("gofmt error: %s\n%s", err, b) @@ -704,37 +739,37 @@ func camelToLower(s string) string { // // Examples // -// "" => [""] -// "lowercase" => ["lowercase"] -// "Class" => ["Class"] -// "MyClass" => ["My", "Class"] -// "MyC" => ["My", "C"] -// "HTML" => ["HTML"] -// "PDFLoader" => ["PDF", "Loader"] -// "AString" => ["A", "String"] -// "SimpleXMLParser" => ["Simple", "XML", "Parser"] -// "vimRPCPlugin" => ["vim", "RPC", "Plugin"] -// "GL11Version" => ["GL", "11", "Version"] -// "99Bottles" => ["99", "Bottles"] -// "May5" => ["May", "5"] -// "BFG9000" => ["BFG", "9000"] -// "BöseÜberraschung" => ["Böse", "Überraschung"] -// "Two spaces" => ["Two", " ", "spaces"] -// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] +// "" => [""] +// "lowercase" => ["lowercase"] +// "Class" => ["Class"] +// "MyClass" => ["My", "Class"] +// "MyC" => ["My", "C"] +// "HTML" => ["HTML"] +// "PDFLoader" => ["PDF", "Loader"] +// "AString" => ["A", "String"] +// "SimpleXMLParser" => ["Simple", "XML", "Parser"] +// "vimRPCPlugin" => ["vim", "RPC", "Plugin"] +// "GL11Version" => ["GL", "11", "Version"] +// "99Bottles" => ["99", "Bottles"] +// "May5" => ["May", "5"] +// "BFG9000" => ["BFG", "9000"] +// "BöseÜberraschung" => ["Böse", "Überraschung"] +// "Two spaces" => ["Two", " ", "spaces"] +// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] // // Splitting rules // -// 1) If string is not valid UTF-8, return it without splitting as +// 1. If string is not valid UTF-8, return it without splitting as // single item array. -// 2) Assign all unicode characters into one of 4 sets: lower case +// 2. Assign all unicode characters into one of 4 sets: lower case // letters, upper case letters, numbers, and all other characters. -// 3) Iterate through characters of string, introducing splits +// 3. Iterate through characters of string, introducing splits // between adjacent characters that belong to different sets. -// 4) Iterate through array of split strings, and if a given string +// 4. Iterate through array of split strings, and if a given string // is upper case: -// if subsequent string is lower case: -// move last character of upper case string to beginning of -// lower case string +// if subsequent string is lower case: +// move last character of upper case string to beginning of +// lower case string func split(src string) (entries []string) { // don't split invalid utf8 if !utf8.ValidString(src) { @@ -742,6 +777,7 @@ func split(src string) (entries []string) { } entries = []string{} + var runes [][]rune lastClass := 0 @@ -770,7 +806,7 @@ func split(src string) (entries []string) { } // handle upper case -> lower case sequences, e.g. // "PDFL", "oader" -> "PDF", "Loader" - for i := 0; i < len(runes)-1; i++ { + for i := range len(runes) - 1 { if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) { runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...) runes[i] = runes[i][:len(runes[i])-1] diff --git a/internal/values/goflags.go b/internal/values/goflags.go new file mode 100644 index 0000000..5e7dbdd --- /dev/null +++ b/internal/values/goflags.go @@ -0,0 +1,56 @@ +package values + +import ( + "fmt" + "reflect" + + "github.com/reeflective/flags/internal/errors" + "github.com/reeflective/flags/internal/interfaces" +) + +// goFlagsValue is a generic Value adapter for any type that implements +// the Unmarshaler and/or Marshaler interfaces from go-flags. +type goFlagsValue struct { + value any // This will hold a pointer to the user's type. +} + +// newGoFlagsValue creates a new value that wraps a type implementing go-flags interfaces. +func newGoFlagsValue(val any) Value { + return &goFlagsValue{value: val} +} + +func (v *goFlagsValue) Set(s string) error { + unmarshaler, ok := v.value.(interfaces.Unmarshaler) + if !ok { + // This should not happen if NewValue is constructed correctly. + return fmt.Errorf("%w: type %T does not implement flags.Unmarshaler", + errors.ErrTypeAssertion, v.value) + } + + if err := unmarshaler.UnmarshalFlag(s); err != nil { + return fmt.Errorf("failed to unmarshal value: %w", err) + } + + return nil +} + +func (v *goFlagsValue) String() string { + // For symmetrical behavior, we check for the Marshaler interface. + if marshaler, ok := v.value.(interfaces.Marshaler); ok { + str, err := marshaler.MarshalFlag() + if err == nil { + return str + } + } + // Fallback to the fmt.Stringer interface. + if stringer, ok := v.value.(fmt.Stringer); ok { + return stringer.String() + } + // Otherwise, return a default representation. + return "" +} + +func (v *goFlagsValue) Type() string { + // Provide the type name for help messages. + return reflect.TypeOf(v.value).Elem().Name() +} diff --git a/internal/values/inverter.go b/internal/values/inverter.go new file mode 100644 index 0000000..bdb5074 --- /dev/null +++ b/internal/values/inverter.go @@ -0,0 +1,42 @@ +package values + +import ( + "strconv" + + "github.com/spf13/pflag" +) + +// Inverter is a pflag.Value that can be used to invert the value of another +// boolean pflag.Value. This is used to implement negatable boolean flags. +type Inverter struct { + // Target is the pflag.Value that will be inverted when this Inverter is set. + Target pflag.Value +} + +// String returns the string representation of the target's value. +func (i *Inverter) String() string { + return i.Target.String() +} + +// IsBoolFlag makes the Inverter satisfy the BoolFlag interface. +// This is necessary so that pflag treats it as a boolean flag that +// does not require an argument. +func (i *Inverter) IsBoolFlag() bool { + return true +} + +// Set parses the input string as a boolean, inverts it, and sets the inverted +// value on the target. +func (i *Inverter) Set(s string) error { + val, err := strconv.ParseBool(s) + if err != nil { + return err + } + // Invert the value before setting it on the target. + return i.Target.Set(strconv.FormatBool(!val)) +} + +// Type returns the type of the target value. +func (i *Inverter) Type() string { + return i.Target.Type() +} diff --git a/internal/values/parser.go b/internal/values/parser.go new file mode 100644 index 0000000..6d7c15a --- /dev/null +++ b/internal/values/parser.go @@ -0,0 +1,106 @@ +package values + +import ( + "reflect" + "slices" + + "github.com/reeflective/flags/internal/interfaces" +) + +// NewValue creates a new value instance for a flag or positional argument +// based on its reflect.Value. It uses a tiered strategy to find the best +// way to handle the type. +func NewValue(val reflect.Value, sep, mapSep *string) Value { + if val.Kind() == reflect.Ptr && val.IsNil() { + val.Set(reflect.New(val.Type().Elem())) + } + + if v := fromDirectInterfaces(val); v != nil { + return v + } + if v := fromGoFlagsInterfaces(val); v != nil { + return v + } + if v := fromGenerated(val, sep); v != nil { // Pass separator + return v + } + if v := fromMap(val, mapSep); v != nil { // Pass map separator + return v + } + + // Dereference pointers if we need to. + if val.Kind() == reflect.Ptr { + return NewValue(val.Elem(), sep, mapSep) + } + + // Fallback to a reflective parser. + return newReflectiveValue(val) +} + +// fromDirectInterfaces checks for direct implementations of the Value interface. +func fromDirectInterfaces(val reflect.Value) Value { + if val.CanInterface() { + if v, ok := val.Interface().(Value); ok { + return v + } + } + if val.CanAddr() && val.Addr().CanInterface() { + if v, ok := val.Addr().Interface().(Value); ok { + return v + } + } + + return nil +} + +// fromGoFlagsInterfaces checks for implementations of go-flags interfaces. +func fromGoFlagsInterfaces(val reflect.Value) Value { + if val.CanAddr() && val.Addr().CanInterface() { + ptr := val.Addr().Interface() + if _, ok := ptr.(interfaces.Unmarshaler); ok { + return newGoFlagsValue(ptr) + } + } + + return nil +} + +// fromGenerated checks for types with auto-generated parsers. +func fromGenerated(val reflect.Value, sep *string) Value { + if val.CanAddr() && val.Addr().CanInterface() { + addr := val.Addr().Interface() + if v := ParseGenerated(addr, sep); v != nil { + return v + } + if v := ParseGeneratedPtrs(addr); v != nil { + return v + } + } + + return nil +} + +// fromMap handles map types. +func fromMap(val reflect.Value, mapSep *string) Value { + if val.Kind() != reflect.Map { + return nil + } + + // Check that the map key is a supported type. + if !slices.Contains(mapAllowedKinds, val.Type().Key().Kind()) { + return nil + } + + if val.IsNil() { + val.Set(reflect.MakeMap(val.Type())) + } + + if val.CanAddr() && val.Addr().CanInterface() { + addr := val.Addr().Interface() + if v := ParseGeneratedMap(addr, mapSep); v != nil { + return v + } + } + + return nil +} diff --git a/internal/values/reflective.go b/internal/values/reflective.go new file mode 100644 index 0000000..bd1af44 --- /dev/null +++ b/internal/values/reflective.go @@ -0,0 +1,161 @@ +package values + +import ( + "fmt" + "reflect" + "strconv" + "strings" + "time" + + "github.com/reeflective/flags/internal/errors" +) + +const ( + // base10 is used for parsing integers. + base10 = 10 + // mapParts is the number of parts a map value is split into. + mapParts = 2 +) + +// reflectiveValue is a fallback parser that uses reflection to handle +// any type based on its Kind, including primitives, slices, and maps. +type reflectiveValue struct { + value reflect.Value +} + +// newReflectiveValue creates a new reflective parser. +func newReflectiveValue(val reflect.Value) Value { + // For maps, we must ensure they are initialized before use. + if val.Kind() == reflect.Map && val.IsNil() { + val.Set(reflect.MakeMap(val.Type())) + } + + return &reflectiveValue{value: val} +} + +func (v *reflectiveValue) Set(s string) error { + switch v.value.Kind() { + case reflect.String: + v.value.SetString(s) + case reflect.Bool: + b, err := strconv.ParseBool(s) + if err != nil { + return fmt.Errorf("invalid boolean value: %w", err) + } + v.value.SetBool(b) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + return setNumeric(v.value, s) + case reflect.Slice: + return setSlice(v.value, s) + case reflect.Map: + return setMap(v.value, s) + default: + return fmt.Errorf("%w: %v", errors.ErrUnsupportedType, v.value.Type()) + } + + return nil +} + +func setNumeric(val reflect.Value, s string) error { + switch val.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + if val.Type() == reflect.TypeOf((*time.Duration)(nil)).Elem() { + d, err := time.ParseDuration(s) + if err != nil { + return fmt.Errorf("%w: %w", errors.ErrInvalidDuration, err) + } + val.SetInt(int64(d)) + + return nil + } + n, err := strconv.ParseInt(s, base10, val.Type().Bits()) + if err != nil { + return fmt.Errorf("%w: %w", errors.ErrInvalidInteger, err) + } + val.SetInt(n) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + n, err := strconv.ParseUint(s, base10, val.Type().Bits()) + if err != nil { + return fmt.Errorf("%w: %w", errors.ErrInvalidUint, err) + } + val.SetUint(n) + case reflect.Float32, reflect.Float64: + n, err := strconv.ParseFloat(s, val.Type().Bits()) + if err != nil { + return fmt.Errorf("%w: %w", errors.ErrInvalidFloat, err) + } + val.SetFloat(n) + } + + return nil +} + +func setSlice(slice reflect.Value, s string) error { + elemType := slice.Type().Elem() + elem := reflect.New(elemType).Elem() + + elemParser := NewValue(elem, nil, nil) + if elemParser == nil { + return fmt.Errorf("%w: slice element type: %v", errors.ErrUnsupportedType, elemType) + } + + if err := elemParser.Set(s); err != nil { + return fmt.Errorf("failed to set slice element: %w", err) + } + slice.Set(reflect.Append(slice, elem)) + + return nil +} + +func setMap(mapVal reflect.Value, s string) error { + parts := strings.SplitN(s, ":", mapParts) + if len(parts) != mapParts { + return fmt.Errorf("map value must be in 'key:value' format, got %q", s) + } + + key := reflect.New(mapVal.Type().Key()).Elem() + val := reflect.New(mapVal.Type().Elem()).Elem() + + keyParser := NewValue(key, nil, nil) + valParser := NewValue(val, nil, nil) + if keyParser == nil || valParser == nil { + return fmt.Errorf("%w: map key or value type", errors.ErrUnsupportedType) + } + + if err := keyParser.Set(parts[0]); err != nil { + return fmt.Errorf("failed to set map key: %w", err) + } + if err := valParser.Set(parts[1]); err != nil { + return fmt.Errorf("failed to set map value: %w", err) + } + mapVal.SetMapIndex(key, val) + + return nil +} + +func (v *reflectiveValue) String() string { + return fmt.Sprintf("%v", v.value.Interface()) +} + +func (v *reflectiveValue) Type() string { + return v.value.Type().String() +} + +// IsValidReflectiveKind checks that the given value can be wrapped +// into a reflective value and function like a builtin values.Value type. +func IsValidReflectiveKind(val reflect.Value) bool { + switch val.Kind() { + case reflect.String, + reflect.Bool, + reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64, + reflect.Slice, + reflect.Map: + return true + default: + return false + } +} diff --git a/values.go b/internal/values/values.go similarity index 92% rename from values.go rename to internal/values/values.go index 6f11407..5d69978 100644 --- a/values.go +++ b/internal/values/values.go @@ -1,6 +1,6 @@ -package flags +package values -//go:generate go run ./cmd/genvalues/main.go +//go:generate go run ./genvalues/main.go import ( "fmt" @@ -18,7 +18,7 @@ import ( // flag. type Value interface { String() string - Set(string) error + Set(val string) error // pflag.Flag require this Type() string @@ -30,7 +30,7 @@ type Value interface { // by this package satisfy the Getter interface. type Getter interface { Value - Get() interface{} + Get() any } // BoolFlag is an optional interface to indicate boolean flags @@ -47,6 +47,14 @@ type RepeatableFlag interface { IsCumulative() bool } +// NewValidator returns a new value that wraps another value and adds a validation function. +func NewValidator(val Value, validator func(string) error) Value { + return &validateValue{ + Value: val, + validateFunc: validator, + } +} + // === Custom values type validateValue struct { @@ -142,7 +150,7 @@ func (v *Counter) Set(s string) error { } // Get method returns inner value for Counter. -func (v Counter) Get() interface{} { return int(v) } +func (v Counter) Get() any { return int(v) } // IsBoolFlag returns true, because Counter might be used without value. func (v Counter) IsBoolFlag() bool { return true } diff --git a/values.json b/internal/values/values.json similarity index 100% rename from values.json rename to internal/values/values.json diff --git a/values_generated.go b/internal/values/values_generated.go similarity index 60% rename from values_generated.go rename to internal/values/values_generated.go index cdd8b29..bf02b59 100644 --- a/values_generated.go +++ b/internal/values/values_generated.go @@ -1,4 +1,4 @@ -package flags +package values // This file is autogenerated by "go generate .". Do not modify. @@ -14,8 +14,8 @@ import ( "time" ) -// MapAllowedKinds stores list of kinds allowed for map keys. -var MapAllowedKinds = []reflect.Kind{ +// mapAllowedKinds stores list of kinds allowed for map keys. +var mapAllowedKinds = []reflect.Kind{ reflect.String, reflect.Int, reflect.Int8, @@ -29,520 +29,736 @@ var MapAllowedKinds = []reflect.Kind{ reflect.Uint64, } -func parseGenerated(value interface{}) Value { - switch value.(type) { +// ParseGenerated generates a flag with underlying interface type. +func ParseGenerated(value any, sep *string) Value { + switch value := value.(type) { case *string: - return newStringValue(value.(*string)) + return newStringValue(value) case *bool: - return newBoolValue(value.(*bool)) + return newBoolValue(value) case *uint: - return newUintValue(value.(*uint)) + return newUintValue(value) case *uint8: - return newUint8Value(value.(*uint8)) + return newUint8Value(value) case *uint16: - return newUint16Value(value.(*uint16)) + return newUint16Value(value) case *uint32: - return newUint32Value(value.(*uint32)) + return newUint32Value(value) case *uint64: - return newUint64Value(value.(*uint64)) + return newUint64Value(value) case *int: - return newIntValue(value.(*int)) + return newIntValue(value) case *int8: - return newInt8Value(value.(*int8)) + return newInt8Value(value) case *int16: - return newInt16Value(value.(*int16)) + return newInt16Value(value) case *int32: - return newInt32Value(value.(*int32)) + return newInt32Value(value) case *int64: - return newInt64Value(value.(*int64)) + return newInt64Value(value) case *float64: - return newFloat64Value(value.(*float64)) + return newFloat64Value(value) case *float32: - return newFloat32Value(value.(*float32)) + return newFloat32Value(value) case *time.Duration: - return newDurationValue(value.(*time.Duration)) + return newDurationValue(value) case *net.IP: - return newIPValue(value.(*net.IP)) + return newIPValue(value) case *HexBytes: - return newHexBytesValue(value.(*HexBytes)) + return newHexBytesValue(value) case *net.TCPAddr: - return newTCPAddrValue(value.(*net.TCPAddr)) + return newTCPAddrValue(value) case *net.IPNet: - return newIPNetValue(value.(*net.IPNet)) + return newIPNetValue(value) case *[]string: - return newStringSliceValue(value.(*[]string)) + return newStringSliceValue(value, sep) case *[]bool: - return newBoolSliceValue(value.(*[]bool)) + return newBoolSliceValue(value, sep) case *[]uint: - return newUintSliceValue(value.(*[]uint)) + return newUintSliceValue(value, sep) case *[]uint8: - return newUint8SliceValue(value.(*[]uint8)) + return newUint8SliceValue(value, sep) case *[]uint16: - return newUint16SliceValue(value.(*[]uint16)) + return newUint16SliceValue(value, sep) case *[]uint32: - return newUint32SliceValue(value.(*[]uint32)) + return newUint32SliceValue(value, sep) case *[]uint64: - return newUint64SliceValue(value.(*[]uint64)) + return newUint64SliceValue(value, sep) case *[]int: - return newIntSliceValue(value.(*[]int)) + return newIntSliceValue(value, sep) case *[]int8: - return newInt8SliceValue(value.(*[]int8)) + return newInt8SliceValue(value, sep) case *[]int16: - return newInt16SliceValue(value.(*[]int16)) + return newInt16SliceValue(value, sep) case *[]int32: - return newInt32SliceValue(value.(*[]int32)) + return newInt32SliceValue(value, sep) case *[]int64: - return newInt64SliceValue(value.(*[]int64)) + return newInt64SliceValue(value, sep) case *[]float64: - return newFloat64SliceValue(value.(*[]float64)) + return newFloat64SliceValue(value, sep) case *[]float32: - return newFloat32SliceValue(value.(*[]float32)) + return newFloat32SliceValue(value, sep) case *[]time.Duration: - return newDurationSliceValue(value.(*[]time.Duration)) + return newDurationSliceValue(value, sep) case *[]net.IP: - return newIPSliceValue(value.(*[]net.IP)) + return newIPSliceValue(value, sep) case *[]HexBytes: - return newHexBytesSliceValue(value.(*[]HexBytes)) + return newHexBytesSliceValue(value, sep) case *[]*regexp.Regexp: - return newRegexpSliceValue(value.(*[]*regexp.Regexp)) + return newRegexpSliceValue(value, sep) case *[]net.TCPAddr: - return newTCPAddrSliceValue(value.(*[]net.TCPAddr)) + return newTCPAddrSliceValue(value, sep) case *[]net.IPNet: - return newIPNetSliceValue(value.(*[]net.IPNet)) + return newIPNetSliceValue(value, sep) + default: return nil } } -func parseGeneratedPtrs(value interface{}) Value { - switch value.(type) { +// ParseGenerated generates a flag with underlying ptr type. +func ParseGeneratedPtrs(value any) Value { + switch value := value.(type) { + case **regexp.Regexp: - return newRegexpValue(value.(**regexp.Regexp)) + return newRegexpValue(value) + default: return nil } } -func parseGeneratedMap(value interface{}) Value { - switch value.(type) { +// ParseGenerated generates a flag with underlying map type. +func ParseGeneratedMap(value any, sep *string) Value { + switch value := value.(type) { + case *map[string]string: - return newStringStringMapValue(value.(*map[string]string)) + return newStringStringMapValue(value, sep) + case *map[int]string: - return newIntStringMapValue(value.(*map[int]string)) + return newIntStringMapValue(value, sep) + case *map[int8]string: - return newInt8StringMapValue(value.(*map[int8]string)) + return newInt8StringMapValue(value, sep) + case *map[int16]string: - return newInt16StringMapValue(value.(*map[int16]string)) + return newInt16StringMapValue(value, sep) + case *map[int32]string: - return newInt32StringMapValue(value.(*map[int32]string)) + return newInt32StringMapValue(value, sep) + case *map[int64]string: - return newInt64StringMapValue(value.(*map[int64]string)) + return newInt64StringMapValue(value, sep) + case *map[uint]string: - return newUintStringMapValue(value.(*map[uint]string)) + return newUintStringMapValue(value, sep) + case *map[uint8]string: - return newUint8StringMapValue(value.(*map[uint8]string)) + return newUint8StringMapValue(value, sep) + case *map[uint16]string: - return newUint16StringMapValue(value.(*map[uint16]string)) + return newUint16StringMapValue(value, sep) + case *map[uint32]string: - return newUint32StringMapValue(value.(*map[uint32]string)) + return newUint32StringMapValue(value, sep) + case *map[uint64]string: - return newUint64StringMapValue(value.(*map[uint64]string)) + return newUint64StringMapValue(value, sep) + case *map[string]bool: - return newStringBoolMapValue(value.(*map[string]bool)) + return newStringBoolMapValue(value, sep) + case *map[int]bool: - return newIntBoolMapValue(value.(*map[int]bool)) + return newIntBoolMapValue(value, sep) + case *map[int8]bool: - return newInt8BoolMapValue(value.(*map[int8]bool)) + return newInt8BoolMapValue(value, sep) + case *map[int16]bool: - return newInt16BoolMapValue(value.(*map[int16]bool)) + return newInt16BoolMapValue(value, sep) + case *map[int32]bool: - return newInt32BoolMapValue(value.(*map[int32]bool)) + return newInt32BoolMapValue(value, sep) + case *map[int64]bool: - return newInt64BoolMapValue(value.(*map[int64]bool)) + return newInt64BoolMapValue(value, sep) + case *map[uint]bool: - return newUintBoolMapValue(value.(*map[uint]bool)) + return newUintBoolMapValue(value, sep) + case *map[uint8]bool: - return newUint8BoolMapValue(value.(*map[uint8]bool)) + return newUint8BoolMapValue(value, sep) + case *map[uint16]bool: - return newUint16BoolMapValue(value.(*map[uint16]bool)) + return newUint16BoolMapValue(value, sep) + case *map[uint32]bool: - return newUint32BoolMapValue(value.(*map[uint32]bool)) + return newUint32BoolMapValue(value, sep) + case *map[uint64]bool: - return newUint64BoolMapValue(value.(*map[uint64]bool)) + return newUint64BoolMapValue(value, sep) + case *map[string]uint: - return newStringUintMapValue(value.(*map[string]uint)) + return newStringUintMapValue(value, sep) + case *map[int]uint: - return newIntUintMapValue(value.(*map[int]uint)) + return newIntUintMapValue(value, sep) + case *map[int8]uint: - return newInt8UintMapValue(value.(*map[int8]uint)) + return newInt8UintMapValue(value, sep) + case *map[int16]uint: - return newInt16UintMapValue(value.(*map[int16]uint)) + return newInt16UintMapValue(value, sep) + case *map[int32]uint: - return newInt32UintMapValue(value.(*map[int32]uint)) + return newInt32UintMapValue(value, sep) + case *map[int64]uint: - return newInt64UintMapValue(value.(*map[int64]uint)) + return newInt64UintMapValue(value, sep) + case *map[uint]uint: - return newUintUintMapValue(value.(*map[uint]uint)) + return newUintUintMapValue(value, sep) + case *map[uint8]uint: - return newUint8UintMapValue(value.(*map[uint8]uint)) + return newUint8UintMapValue(value, sep) + case *map[uint16]uint: - return newUint16UintMapValue(value.(*map[uint16]uint)) + return newUint16UintMapValue(value, sep) + case *map[uint32]uint: - return newUint32UintMapValue(value.(*map[uint32]uint)) + return newUint32UintMapValue(value, sep) + case *map[uint64]uint: - return newUint64UintMapValue(value.(*map[uint64]uint)) + return newUint64UintMapValue(value, sep) + case *map[string]uint8: - return newStringUint8MapValue(value.(*map[string]uint8)) + return newStringUint8MapValue(value, sep) + case *map[int]uint8: - return newIntUint8MapValue(value.(*map[int]uint8)) + return newIntUint8MapValue(value, sep) + case *map[int8]uint8: - return newInt8Uint8MapValue(value.(*map[int8]uint8)) + return newInt8Uint8MapValue(value, sep) + case *map[int16]uint8: - return newInt16Uint8MapValue(value.(*map[int16]uint8)) + return newInt16Uint8MapValue(value, sep) + case *map[int32]uint8: - return newInt32Uint8MapValue(value.(*map[int32]uint8)) + return newInt32Uint8MapValue(value, sep) + case *map[int64]uint8: - return newInt64Uint8MapValue(value.(*map[int64]uint8)) + return newInt64Uint8MapValue(value, sep) + case *map[uint]uint8: - return newUintUint8MapValue(value.(*map[uint]uint8)) + return newUintUint8MapValue(value, sep) + case *map[uint8]uint8: - return newUint8Uint8MapValue(value.(*map[uint8]uint8)) + return newUint8Uint8MapValue(value, sep) + case *map[uint16]uint8: - return newUint16Uint8MapValue(value.(*map[uint16]uint8)) + return newUint16Uint8MapValue(value, sep) + case *map[uint32]uint8: - return newUint32Uint8MapValue(value.(*map[uint32]uint8)) + return newUint32Uint8MapValue(value, sep) + case *map[uint64]uint8: - return newUint64Uint8MapValue(value.(*map[uint64]uint8)) + return newUint64Uint8MapValue(value, sep) + case *map[string]uint16: - return newStringUint16MapValue(value.(*map[string]uint16)) + return newStringUint16MapValue(value, sep) + case *map[int]uint16: - return newIntUint16MapValue(value.(*map[int]uint16)) + return newIntUint16MapValue(value, sep) + case *map[int8]uint16: - return newInt8Uint16MapValue(value.(*map[int8]uint16)) + return newInt8Uint16MapValue(value, sep) + case *map[int16]uint16: - return newInt16Uint16MapValue(value.(*map[int16]uint16)) + return newInt16Uint16MapValue(value, sep) + case *map[int32]uint16: - return newInt32Uint16MapValue(value.(*map[int32]uint16)) + return newInt32Uint16MapValue(value, sep) + case *map[int64]uint16: - return newInt64Uint16MapValue(value.(*map[int64]uint16)) + return newInt64Uint16MapValue(value, sep) + case *map[uint]uint16: - return newUintUint16MapValue(value.(*map[uint]uint16)) + return newUintUint16MapValue(value, sep) + case *map[uint8]uint16: - return newUint8Uint16MapValue(value.(*map[uint8]uint16)) + return newUint8Uint16MapValue(value, sep) + case *map[uint16]uint16: - return newUint16Uint16MapValue(value.(*map[uint16]uint16)) + return newUint16Uint16MapValue(value, sep) + case *map[uint32]uint16: - return newUint32Uint16MapValue(value.(*map[uint32]uint16)) + return newUint32Uint16MapValue(value, sep) + case *map[uint64]uint16: - return newUint64Uint16MapValue(value.(*map[uint64]uint16)) + return newUint64Uint16MapValue(value, sep) + case *map[string]uint32: - return newStringUint32MapValue(value.(*map[string]uint32)) + return newStringUint32MapValue(value, sep) + case *map[int]uint32: - return newIntUint32MapValue(value.(*map[int]uint32)) + return newIntUint32MapValue(value, sep) + case *map[int8]uint32: - return newInt8Uint32MapValue(value.(*map[int8]uint32)) + return newInt8Uint32MapValue(value, sep) + case *map[int16]uint32: - return newInt16Uint32MapValue(value.(*map[int16]uint32)) + return newInt16Uint32MapValue(value, sep) + case *map[int32]uint32: - return newInt32Uint32MapValue(value.(*map[int32]uint32)) + return newInt32Uint32MapValue(value, sep) + case *map[int64]uint32: - return newInt64Uint32MapValue(value.(*map[int64]uint32)) + return newInt64Uint32MapValue(value, sep) + case *map[uint]uint32: - return newUintUint32MapValue(value.(*map[uint]uint32)) + return newUintUint32MapValue(value, sep) + case *map[uint8]uint32: - return newUint8Uint32MapValue(value.(*map[uint8]uint32)) + return newUint8Uint32MapValue(value, sep) + case *map[uint16]uint32: - return newUint16Uint32MapValue(value.(*map[uint16]uint32)) + return newUint16Uint32MapValue(value, sep) + case *map[uint32]uint32: - return newUint32Uint32MapValue(value.(*map[uint32]uint32)) + return newUint32Uint32MapValue(value, sep) + case *map[uint64]uint32: - return newUint64Uint32MapValue(value.(*map[uint64]uint32)) + return newUint64Uint32MapValue(value, sep) + case *map[string]uint64: - return newStringUint64MapValue(value.(*map[string]uint64)) + return newStringUint64MapValue(value, sep) + case *map[int]uint64: - return newIntUint64MapValue(value.(*map[int]uint64)) + return newIntUint64MapValue(value, sep) + case *map[int8]uint64: - return newInt8Uint64MapValue(value.(*map[int8]uint64)) + return newInt8Uint64MapValue(value, sep) + case *map[int16]uint64: - return newInt16Uint64MapValue(value.(*map[int16]uint64)) + return newInt16Uint64MapValue(value, sep) + case *map[int32]uint64: - return newInt32Uint64MapValue(value.(*map[int32]uint64)) + return newInt32Uint64MapValue(value, sep) + case *map[int64]uint64: - return newInt64Uint64MapValue(value.(*map[int64]uint64)) + return newInt64Uint64MapValue(value, sep) + case *map[uint]uint64: - return newUintUint64MapValue(value.(*map[uint]uint64)) + return newUintUint64MapValue(value, sep) + case *map[uint8]uint64: - return newUint8Uint64MapValue(value.(*map[uint8]uint64)) + return newUint8Uint64MapValue(value, sep) + case *map[uint16]uint64: - return newUint16Uint64MapValue(value.(*map[uint16]uint64)) + return newUint16Uint64MapValue(value, sep) + case *map[uint32]uint64: - return newUint32Uint64MapValue(value.(*map[uint32]uint64)) + return newUint32Uint64MapValue(value, sep) + case *map[uint64]uint64: - return newUint64Uint64MapValue(value.(*map[uint64]uint64)) + return newUint64Uint64MapValue(value, sep) + case *map[string]int: - return newStringIntMapValue(value.(*map[string]int)) + return newStringIntMapValue(value, sep) + case *map[int]int: - return newIntIntMapValue(value.(*map[int]int)) + return newIntIntMapValue(value, sep) + case *map[int8]int: - return newInt8IntMapValue(value.(*map[int8]int)) + return newInt8IntMapValue(value, sep) + case *map[int16]int: - return newInt16IntMapValue(value.(*map[int16]int)) + return newInt16IntMapValue(value, sep) + case *map[int32]int: - return newInt32IntMapValue(value.(*map[int32]int)) + return newInt32IntMapValue(value, sep) + case *map[int64]int: - return newInt64IntMapValue(value.(*map[int64]int)) + return newInt64IntMapValue(value, sep) + case *map[uint]int: - return newUintIntMapValue(value.(*map[uint]int)) + return newUintIntMapValue(value, sep) + case *map[uint8]int: - return newUint8IntMapValue(value.(*map[uint8]int)) + return newUint8IntMapValue(value, sep) + case *map[uint16]int: - return newUint16IntMapValue(value.(*map[uint16]int)) + return newUint16IntMapValue(value, sep) + case *map[uint32]int: - return newUint32IntMapValue(value.(*map[uint32]int)) + return newUint32IntMapValue(value, sep) + case *map[uint64]int: - return newUint64IntMapValue(value.(*map[uint64]int)) + return newUint64IntMapValue(value, sep) + case *map[string]int8: - return newStringInt8MapValue(value.(*map[string]int8)) + return newStringInt8MapValue(value, sep) + case *map[int]int8: - return newIntInt8MapValue(value.(*map[int]int8)) + return newIntInt8MapValue(value, sep) + case *map[int8]int8: - return newInt8Int8MapValue(value.(*map[int8]int8)) + return newInt8Int8MapValue(value, sep) + case *map[int16]int8: - return newInt16Int8MapValue(value.(*map[int16]int8)) + return newInt16Int8MapValue(value, sep) + case *map[int32]int8: - return newInt32Int8MapValue(value.(*map[int32]int8)) + return newInt32Int8MapValue(value, sep) + case *map[int64]int8: - return newInt64Int8MapValue(value.(*map[int64]int8)) + return newInt64Int8MapValue(value, sep) + case *map[uint]int8: - return newUintInt8MapValue(value.(*map[uint]int8)) + return newUintInt8MapValue(value, sep) + case *map[uint8]int8: - return newUint8Int8MapValue(value.(*map[uint8]int8)) + return newUint8Int8MapValue(value, sep) + case *map[uint16]int8: - return newUint16Int8MapValue(value.(*map[uint16]int8)) + return newUint16Int8MapValue(value, sep) + case *map[uint32]int8: - return newUint32Int8MapValue(value.(*map[uint32]int8)) + return newUint32Int8MapValue(value, sep) + case *map[uint64]int8: - return newUint64Int8MapValue(value.(*map[uint64]int8)) + return newUint64Int8MapValue(value, sep) + case *map[string]int16: - return newStringInt16MapValue(value.(*map[string]int16)) + return newStringInt16MapValue(value, sep) + case *map[int]int16: - return newIntInt16MapValue(value.(*map[int]int16)) + return newIntInt16MapValue(value, sep) + case *map[int8]int16: - return newInt8Int16MapValue(value.(*map[int8]int16)) + return newInt8Int16MapValue(value, sep) + case *map[int16]int16: - return newInt16Int16MapValue(value.(*map[int16]int16)) + return newInt16Int16MapValue(value, sep) + case *map[int32]int16: - return newInt32Int16MapValue(value.(*map[int32]int16)) + return newInt32Int16MapValue(value, sep) + case *map[int64]int16: - return newInt64Int16MapValue(value.(*map[int64]int16)) + return newInt64Int16MapValue(value, sep) + case *map[uint]int16: - return newUintInt16MapValue(value.(*map[uint]int16)) + return newUintInt16MapValue(value, sep) + case *map[uint8]int16: - return newUint8Int16MapValue(value.(*map[uint8]int16)) + return newUint8Int16MapValue(value, sep) + case *map[uint16]int16: - return newUint16Int16MapValue(value.(*map[uint16]int16)) + return newUint16Int16MapValue(value, sep) + case *map[uint32]int16: - return newUint32Int16MapValue(value.(*map[uint32]int16)) + return newUint32Int16MapValue(value, sep) + case *map[uint64]int16: - return newUint64Int16MapValue(value.(*map[uint64]int16)) + return newUint64Int16MapValue(value, sep) + case *map[string]int32: - return newStringInt32MapValue(value.(*map[string]int32)) + return newStringInt32MapValue(value, sep) + case *map[int]int32: - return newIntInt32MapValue(value.(*map[int]int32)) + return newIntInt32MapValue(value, sep) + case *map[int8]int32: - return newInt8Int32MapValue(value.(*map[int8]int32)) + return newInt8Int32MapValue(value, sep) + case *map[int16]int32: - return newInt16Int32MapValue(value.(*map[int16]int32)) + return newInt16Int32MapValue(value, sep) + case *map[int32]int32: - return newInt32Int32MapValue(value.(*map[int32]int32)) + return newInt32Int32MapValue(value, sep) + case *map[int64]int32: - return newInt64Int32MapValue(value.(*map[int64]int32)) + return newInt64Int32MapValue(value, sep) + case *map[uint]int32: - return newUintInt32MapValue(value.(*map[uint]int32)) + return newUintInt32MapValue(value, sep) + case *map[uint8]int32: - return newUint8Int32MapValue(value.(*map[uint8]int32)) + return newUint8Int32MapValue(value, sep) + case *map[uint16]int32: - return newUint16Int32MapValue(value.(*map[uint16]int32)) + return newUint16Int32MapValue(value, sep) + case *map[uint32]int32: - return newUint32Int32MapValue(value.(*map[uint32]int32)) + return newUint32Int32MapValue(value, sep) + case *map[uint64]int32: - return newUint64Int32MapValue(value.(*map[uint64]int32)) + return newUint64Int32MapValue(value, sep) + case *map[string]int64: - return newStringInt64MapValue(value.(*map[string]int64)) + return newStringInt64MapValue(value, sep) + case *map[int]int64: - return newIntInt64MapValue(value.(*map[int]int64)) + return newIntInt64MapValue(value, sep) + case *map[int8]int64: - return newInt8Int64MapValue(value.(*map[int8]int64)) + return newInt8Int64MapValue(value, sep) + case *map[int16]int64: - return newInt16Int64MapValue(value.(*map[int16]int64)) + return newInt16Int64MapValue(value, sep) + case *map[int32]int64: - return newInt32Int64MapValue(value.(*map[int32]int64)) + return newInt32Int64MapValue(value, sep) + case *map[int64]int64: - return newInt64Int64MapValue(value.(*map[int64]int64)) + return newInt64Int64MapValue(value, sep) + case *map[uint]int64: - return newUintInt64MapValue(value.(*map[uint]int64)) + return newUintInt64MapValue(value, sep) + case *map[uint8]int64: - return newUint8Int64MapValue(value.(*map[uint8]int64)) + return newUint8Int64MapValue(value, sep) + case *map[uint16]int64: - return newUint16Int64MapValue(value.(*map[uint16]int64)) + return newUint16Int64MapValue(value, sep) + case *map[uint32]int64: - return newUint32Int64MapValue(value.(*map[uint32]int64)) + return newUint32Int64MapValue(value, sep) + case *map[uint64]int64: - return newUint64Int64MapValue(value.(*map[uint64]int64)) + return newUint64Int64MapValue(value, sep) + case *map[string]float64: - return newStringFloat64MapValue(value.(*map[string]float64)) + return newStringFloat64MapValue(value, sep) + case *map[int]float64: - return newIntFloat64MapValue(value.(*map[int]float64)) + return newIntFloat64MapValue(value, sep) + case *map[int8]float64: - return newInt8Float64MapValue(value.(*map[int8]float64)) + return newInt8Float64MapValue(value, sep) + case *map[int16]float64: - return newInt16Float64MapValue(value.(*map[int16]float64)) + return newInt16Float64MapValue(value, sep) + case *map[int32]float64: - return newInt32Float64MapValue(value.(*map[int32]float64)) + return newInt32Float64MapValue(value, sep) + case *map[int64]float64: - return newInt64Float64MapValue(value.(*map[int64]float64)) + return newInt64Float64MapValue(value, sep) + case *map[uint]float64: - return newUintFloat64MapValue(value.(*map[uint]float64)) + return newUintFloat64MapValue(value, sep) + case *map[uint8]float64: - return newUint8Float64MapValue(value.(*map[uint8]float64)) + return newUint8Float64MapValue(value, sep) + case *map[uint16]float64: - return newUint16Float64MapValue(value.(*map[uint16]float64)) + return newUint16Float64MapValue(value, sep) + case *map[uint32]float64: - return newUint32Float64MapValue(value.(*map[uint32]float64)) + return newUint32Float64MapValue(value, sep) + case *map[uint64]float64: - return newUint64Float64MapValue(value.(*map[uint64]float64)) + return newUint64Float64MapValue(value, sep) + case *map[string]float32: - return newStringFloat32MapValue(value.(*map[string]float32)) + return newStringFloat32MapValue(value, sep) + case *map[int]float32: - return newIntFloat32MapValue(value.(*map[int]float32)) + return newIntFloat32MapValue(value, sep) + case *map[int8]float32: - return newInt8Float32MapValue(value.(*map[int8]float32)) + return newInt8Float32MapValue(value, sep) + case *map[int16]float32: - return newInt16Float32MapValue(value.(*map[int16]float32)) + return newInt16Float32MapValue(value, sep) + case *map[int32]float32: - return newInt32Float32MapValue(value.(*map[int32]float32)) + return newInt32Float32MapValue(value, sep) + case *map[int64]float32: - return newInt64Float32MapValue(value.(*map[int64]float32)) + return newInt64Float32MapValue(value, sep) + case *map[uint]float32: - return newUintFloat32MapValue(value.(*map[uint]float32)) + return newUintFloat32MapValue(value, sep) + case *map[uint8]float32: - return newUint8Float32MapValue(value.(*map[uint8]float32)) + return newUint8Float32MapValue(value, sep) + case *map[uint16]float32: - return newUint16Float32MapValue(value.(*map[uint16]float32)) + return newUint16Float32MapValue(value, sep) + case *map[uint32]float32: - return newUint32Float32MapValue(value.(*map[uint32]float32)) + return newUint32Float32MapValue(value, sep) + case *map[uint64]float32: - return newUint64Float32MapValue(value.(*map[uint64]float32)) + return newUint64Float32MapValue(value, sep) + case *map[string]time.Duration: - return newStringDurationMapValue(value.(*map[string]time.Duration)) + return newStringDurationMapValue(value, sep) + case *map[int]time.Duration: - return newIntDurationMapValue(value.(*map[int]time.Duration)) + return newIntDurationMapValue(value, sep) + case *map[int8]time.Duration: - return newInt8DurationMapValue(value.(*map[int8]time.Duration)) + return newInt8DurationMapValue(value, sep) + case *map[int16]time.Duration: - return newInt16DurationMapValue(value.(*map[int16]time.Duration)) + return newInt16DurationMapValue(value, sep) + case *map[int32]time.Duration: - return newInt32DurationMapValue(value.(*map[int32]time.Duration)) + return newInt32DurationMapValue(value, sep) + case *map[int64]time.Duration: - return newInt64DurationMapValue(value.(*map[int64]time.Duration)) + return newInt64DurationMapValue(value, sep) + case *map[uint]time.Duration: - return newUintDurationMapValue(value.(*map[uint]time.Duration)) + return newUintDurationMapValue(value, sep) + case *map[uint8]time.Duration: - return newUint8DurationMapValue(value.(*map[uint8]time.Duration)) + return newUint8DurationMapValue(value, sep) + case *map[uint16]time.Duration: - return newUint16DurationMapValue(value.(*map[uint16]time.Duration)) + return newUint16DurationMapValue(value, sep) + case *map[uint32]time.Duration: - return newUint32DurationMapValue(value.(*map[uint32]time.Duration)) + return newUint32DurationMapValue(value, sep) + case *map[uint64]time.Duration: - return newUint64DurationMapValue(value.(*map[uint64]time.Duration)) + return newUint64DurationMapValue(value, sep) + case *map[string]net.IP: - return newStringIPMapValue(value.(*map[string]net.IP)) + return newStringIPMapValue(value, sep) + case *map[int]net.IP: - return newIntIPMapValue(value.(*map[int]net.IP)) + return newIntIPMapValue(value, sep) + case *map[int8]net.IP: - return newInt8IPMapValue(value.(*map[int8]net.IP)) + return newInt8IPMapValue(value, sep) + case *map[int16]net.IP: - return newInt16IPMapValue(value.(*map[int16]net.IP)) + return newInt16IPMapValue(value, sep) + case *map[int32]net.IP: - return newInt32IPMapValue(value.(*map[int32]net.IP)) + return newInt32IPMapValue(value, sep) + case *map[int64]net.IP: - return newInt64IPMapValue(value.(*map[int64]net.IP)) + return newInt64IPMapValue(value, sep) + case *map[uint]net.IP: - return newUintIPMapValue(value.(*map[uint]net.IP)) + return newUintIPMapValue(value, sep) + case *map[uint8]net.IP: - return newUint8IPMapValue(value.(*map[uint8]net.IP)) + return newUint8IPMapValue(value, sep) + case *map[uint16]net.IP: - return newUint16IPMapValue(value.(*map[uint16]net.IP)) + return newUint16IPMapValue(value, sep) + case *map[uint32]net.IP: - return newUint32IPMapValue(value.(*map[uint32]net.IP)) + return newUint32IPMapValue(value, sep) + case *map[uint64]net.IP: - return newUint64IPMapValue(value.(*map[uint64]net.IP)) + return newUint64IPMapValue(value, sep) + case *map[string]HexBytes: - return newStringHexBytesMapValue(value.(*map[string]HexBytes)) + return newStringHexBytesMapValue(value, sep) + case *map[int]HexBytes: - return newIntHexBytesMapValue(value.(*map[int]HexBytes)) + return newIntHexBytesMapValue(value, sep) + case *map[int8]HexBytes: - return newInt8HexBytesMapValue(value.(*map[int8]HexBytes)) + return newInt8HexBytesMapValue(value, sep) + case *map[int16]HexBytes: - return newInt16HexBytesMapValue(value.(*map[int16]HexBytes)) + return newInt16HexBytesMapValue(value, sep) + case *map[int32]HexBytes: - return newInt32HexBytesMapValue(value.(*map[int32]HexBytes)) + return newInt32HexBytesMapValue(value, sep) + case *map[int64]HexBytes: - return newInt64HexBytesMapValue(value.(*map[int64]HexBytes)) + return newInt64HexBytesMapValue(value, sep) + case *map[uint]HexBytes: - return newUintHexBytesMapValue(value.(*map[uint]HexBytes)) + return newUintHexBytesMapValue(value, sep) + case *map[uint8]HexBytes: - return newUint8HexBytesMapValue(value.(*map[uint8]HexBytes)) + return newUint8HexBytesMapValue(value, sep) + case *map[uint16]HexBytes: - return newUint16HexBytesMapValue(value.(*map[uint16]HexBytes)) + return newUint16HexBytesMapValue(value, sep) + case *map[uint32]HexBytes: - return newUint32HexBytesMapValue(value.(*map[uint32]HexBytes)) + return newUint32HexBytesMapValue(value, sep) + case *map[uint64]HexBytes: - return newUint64HexBytesMapValue(value.(*map[uint64]HexBytes)) + return newUint64HexBytesMapValue(value, sep) + case *map[string]*regexp.Regexp: - return newStringRegexpMapValue(value.(*map[string]*regexp.Regexp)) + return newStringRegexpMapValue(value, sep) + case *map[int]*regexp.Regexp: - return newIntRegexpMapValue(value.(*map[int]*regexp.Regexp)) + return newIntRegexpMapValue(value, sep) + case *map[int8]*regexp.Regexp: - return newInt8RegexpMapValue(value.(*map[int8]*regexp.Regexp)) + return newInt8RegexpMapValue(value, sep) + case *map[int16]*regexp.Regexp: - return newInt16RegexpMapValue(value.(*map[int16]*regexp.Regexp)) + return newInt16RegexpMapValue(value, sep) + case *map[int32]*regexp.Regexp: - return newInt32RegexpMapValue(value.(*map[int32]*regexp.Regexp)) + return newInt32RegexpMapValue(value, sep) + case *map[int64]*regexp.Regexp: - return newInt64RegexpMapValue(value.(*map[int64]*regexp.Regexp)) + return newInt64RegexpMapValue(value, sep) + case *map[uint]*regexp.Regexp: - return newUintRegexpMapValue(value.(*map[uint]*regexp.Regexp)) + return newUintRegexpMapValue(value, sep) + case *map[uint8]*regexp.Regexp: - return newUint8RegexpMapValue(value.(*map[uint8]*regexp.Regexp)) + return newUint8RegexpMapValue(value, sep) + case *map[uint16]*regexp.Regexp: - return newUint16RegexpMapValue(value.(*map[uint16]*regexp.Regexp)) + return newUint16RegexpMapValue(value, sep) + case *map[uint32]*regexp.Regexp: - return newUint32RegexpMapValue(value.(*map[uint32]*regexp.Regexp)) + return newUint32RegexpMapValue(value, sep) + case *map[uint64]*regexp.Regexp: - return newUint64RegexpMapValue(value.(*map[uint64]*regexp.Regexp)) + return newUint64RegexpMapValue(value, sep) + case *map[string]net.IPNet: - return newStringIPNetMapValue(value.(*map[string]net.IPNet)) + return newStringIPNetMapValue(value, sep) + case *map[int]net.IPNet: - return newIntIPNetMapValue(value.(*map[int]net.IPNet)) + return newIntIPNetMapValue(value, sep) + case *map[int8]net.IPNet: - return newInt8IPNetMapValue(value.(*map[int8]net.IPNet)) + return newInt8IPNetMapValue(value, sep) + case *map[int16]net.IPNet: - return newInt16IPNetMapValue(value.(*map[int16]net.IPNet)) + return newInt16IPNetMapValue(value, sep) + case *map[int32]net.IPNet: - return newInt32IPNetMapValue(value.(*map[int32]net.IPNet)) + return newInt32IPNetMapValue(value, sep) + case *map[int64]net.IPNet: - return newInt64IPNetMapValue(value.(*map[int64]net.IPNet)) + return newInt64IPNetMapValue(value, sep) + case *map[uint]net.IPNet: - return newUintIPNetMapValue(value.(*map[uint]net.IPNet)) + return newUintIPNetMapValue(value, sep) + case *map[uint8]net.IPNet: - return newUint8IPNetMapValue(value.(*map[uint8]net.IPNet)) + return newUint8IPNetMapValue(value, sep) + case *map[uint16]net.IPNet: - return newUint16IPNetMapValue(value.(*map[uint16]net.IPNet)) + return newUint16IPNetMapValue(value, sep) + case *map[uint32]net.IPNet: - return newUint32IPNetMapValue(value.(*map[uint32]net.IPNet)) + return newUint32IPNetMapValue(value, sep) + case *map[uint64]net.IPNet: - return newUint64IPNetMapValue(value.(*map[uint64]net.IPNet)) + return newUint64IPNetMapValue(value, sep) + default: return nil } @@ -553,31 +769,36 @@ type stringValue struct { value *string } -var ( - _ Value = (*stringValue)(nil) - _ Getter = (*stringValue)(nil) -) +var _ Value = (*stringValue)(nil) +var _ Getter = (*stringValue)(nil) func newStringValue(p *string) *stringValue { return &stringValue{value: p} } func (v *stringValue) Set(s string) error { + *v.value = s + return nil + } -func (v *stringValue) Get() interface{} { +func (v *stringValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *stringValue) String() string { if v != nil && v.value != nil { + return *v.value } + return "" } @@ -586,24 +807,39 @@ func (v *stringValue) Type() string { return "string" } // -- stringSlice Value type stringSliceValue struct { - value *[]string - changed bool + value *[]string + changed bool + separator string } -var ( - _ RepeatableFlag = (*stringSliceValue)(nil) - _ Value = (*stringSliceValue)(nil) - _ Getter = (*stringSliceValue)(nil) -) +var _ RepeatableFlag = (*stringSliceValue)(nil) +var _ Value = (*stringSliceValue)(nil) +var _ Getter = (*stringSliceValue)(nil) -func newStringSliceValue(slice *[]string) *stringSliceValue { - return &stringSliceValue{ +func newStringSliceValue(slice *[]string, sep *string) *stringSliceValue { + s := &stringSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } + out := ss if !v.changed { *v.value = out @@ -611,24 +847,29 @@ func (v *stringSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *stringSliceValue) Get() interface{} { +func (v *stringSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]string)(nil) } func (v *stringSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newStringValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -640,23 +881,37 @@ func (v *stringSliceValue) IsCumulative() bool { // -- stringStringMapValue. type stringStringMapValue struct { - value *map[string]string + value *map[string]string + separator string } -var ( - _ RepeatableFlag = (*stringStringMapValue)(nil) - _ Value = (*stringStringMapValue)(nil) - _ Getter = (*stringStringMapValue)(nil) -) +var _ RepeatableFlag = (*stringStringMapValue)(nil) +var _ Value = (*stringStringMapValue)(nil) +var _ Getter = (*stringStringMapValue)(nil) -func newStringStringMapValue(m *map[string]string) *stringStringMapValue { - return &stringStringMapValue{ +func newStringStringMapValue(m *map[string]string, sep *string) *stringStringMapValue { + s := &stringStringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringStringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -678,10 +933,11 @@ func (v *stringStringMapValue) Set(val string) error { return nil } -func (v *stringStringMapValue) Get() interface{} { +func (v *stringStringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -689,6 +945,7 @@ func (v *stringStringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -700,23 +957,37 @@ func (v *stringStringMapValue) IsCumulative() bool { // -- intStringMapValue. type intStringMapValue struct { - value *map[int]string + value *map[int]string + separator string } -var ( - _ RepeatableFlag = (*intStringMapValue)(nil) - _ Value = (*intStringMapValue)(nil) - _ Getter = (*intStringMapValue)(nil) -) +var _ RepeatableFlag = (*intStringMapValue)(nil) +var _ Value = (*intStringMapValue)(nil) +var _ Getter = (*intStringMapValue)(nil) -func newIntStringMapValue(m *map[int]string) *intStringMapValue { - return &intStringMapValue{ +func newIntStringMapValue(m *map[int]string, sep *string) *intStringMapValue { + s := &intStringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intStringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -743,10 +1014,11 @@ func (v *intStringMapValue) Set(val string) error { return nil } -func (v *intStringMapValue) Get() interface{} { +func (v *intStringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -754,6 +1026,7 @@ func (v *intStringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -765,23 +1038,37 @@ func (v *intStringMapValue) IsCumulative() bool { // -- int8StringMapValue. type int8StringMapValue struct { - value *map[int8]string + value *map[int8]string + separator string } -var ( - _ RepeatableFlag = (*int8StringMapValue)(nil) - _ Value = (*int8StringMapValue)(nil) - _ Getter = (*int8StringMapValue)(nil) -) +var _ RepeatableFlag = (*int8StringMapValue)(nil) +var _ Value = (*int8StringMapValue)(nil) +var _ Getter = (*int8StringMapValue)(nil) -func newInt8StringMapValue(m *map[int8]string) *int8StringMapValue { - return &int8StringMapValue{ +func newInt8StringMapValue(m *map[int8]string, sep *string) *int8StringMapValue { + s := &int8StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -808,10 +1095,11 @@ func (v *int8StringMapValue) Set(val string) error { return nil } -func (v *int8StringMapValue) Get() interface{} { +func (v *int8StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -819,6 +1107,7 @@ func (v *int8StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -830,23 +1119,37 @@ func (v *int8StringMapValue) IsCumulative() bool { // -- int16StringMapValue. type int16StringMapValue struct { - value *map[int16]string + value *map[int16]string + separator string } -var ( - _ RepeatableFlag = (*int16StringMapValue)(nil) - _ Value = (*int16StringMapValue)(nil) - _ Getter = (*int16StringMapValue)(nil) -) +var _ RepeatableFlag = (*int16StringMapValue)(nil) +var _ Value = (*int16StringMapValue)(nil) +var _ Getter = (*int16StringMapValue)(nil) -func newInt16StringMapValue(m *map[int16]string) *int16StringMapValue { - return &int16StringMapValue{ +func newInt16StringMapValue(m *map[int16]string, sep *string) *int16StringMapValue { + s := &int16StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -873,10 +1176,11 @@ func (v *int16StringMapValue) Set(val string) error { return nil } -func (v *int16StringMapValue) Get() interface{} { +func (v *int16StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -884,6 +1188,7 @@ func (v *int16StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -895,23 +1200,37 @@ func (v *int16StringMapValue) IsCumulative() bool { // -- int32StringMapValue. type int32StringMapValue struct { - value *map[int32]string + value *map[int32]string + separator string } -var ( - _ RepeatableFlag = (*int32StringMapValue)(nil) - _ Value = (*int32StringMapValue)(nil) - _ Getter = (*int32StringMapValue)(nil) -) +var _ RepeatableFlag = (*int32StringMapValue)(nil) +var _ Value = (*int32StringMapValue)(nil) +var _ Getter = (*int32StringMapValue)(nil) -func newInt32StringMapValue(m *map[int32]string) *int32StringMapValue { - return &int32StringMapValue{ +func newInt32StringMapValue(m *map[int32]string, sep *string) *int32StringMapValue { + s := &int32StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -938,10 +1257,11 @@ func (v *int32StringMapValue) Set(val string) error { return nil } -func (v *int32StringMapValue) Get() interface{} { +func (v *int32StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -949,6 +1269,7 @@ func (v *int32StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -960,23 +1281,37 @@ func (v *int32StringMapValue) IsCumulative() bool { // -- int64StringMapValue. type int64StringMapValue struct { - value *map[int64]string + value *map[int64]string + separator string } -var ( - _ RepeatableFlag = (*int64StringMapValue)(nil) - _ Value = (*int64StringMapValue)(nil) - _ Getter = (*int64StringMapValue)(nil) -) +var _ RepeatableFlag = (*int64StringMapValue)(nil) +var _ Value = (*int64StringMapValue)(nil) +var _ Getter = (*int64StringMapValue)(nil) -func newInt64StringMapValue(m *map[int64]string) *int64StringMapValue { - return &int64StringMapValue{ +func newInt64StringMapValue(m *map[int64]string, sep *string) *int64StringMapValue { + s := &int64StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1003,10 +1338,11 @@ func (v *int64StringMapValue) Set(val string) error { return nil } -func (v *int64StringMapValue) Get() interface{} { +func (v *int64StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1014,6 +1350,7 @@ func (v *int64StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1025,23 +1362,37 @@ func (v *int64StringMapValue) IsCumulative() bool { // -- uintStringMapValue. type uintStringMapValue struct { - value *map[uint]string + value *map[uint]string + separator string } -var ( - _ RepeatableFlag = (*uintStringMapValue)(nil) - _ Value = (*uintStringMapValue)(nil) - _ Getter = (*uintStringMapValue)(nil) -) +var _ RepeatableFlag = (*uintStringMapValue)(nil) +var _ Value = (*uintStringMapValue)(nil) +var _ Getter = (*uintStringMapValue)(nil) -func newUintStringMapValue(m *map[uint]string) *uintStringMapValue { - return &uintStringMapValue{ +func newUintStringMapValue(m *map[uint]string, sep *string) *uintStringMapValue { + s := &uintStringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintStringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1068,10 +1419,11 @@ func (v *uintStringMapValue) Set(val string) error { return nil } -func (v *uintStringMapValue) Get() interface{} { +func (v *uintStringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1079,6 +1431,7 @@ func (v *uintStringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1090,23 +1443,37 @@ func (v *uintStringMapValue) IsCumulative() bool { // -- uint8StringMapValue. type uint8StringMapValue struct { - value *map[uint8]string + value *map[uint8]string + separator string } -var ( - _ RepeatableFlag = (*uint8StringMapValue)(nil) - _ Value = (*uint8StringMapValue)(nil) - _ Getter = (*uint8StringMapValue)(nil) -) +var _ RepeatableFlag = (*uint8StringMapValue)(nil) +var _ Value = (*uint8StringMapValue)(nil) +var _ Getter = (*uint8StringMapValue)(nil) -func newUint8StringMapValue(m *map[uint8]string) *uint8StringMapValue { - return &uint8StringMapValue{ +func newUint8StringMapValue(m *map[uint8]string, sep *string) *uint8StringMapValue { + s := &uint8StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1133,10 +1500,11 @@ func (v *uint8StringMapValue) Set(val string) error { return nil } -func (v *uint8StringMapValue) Get() interface{} { +func (v *uint8StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1144,6 +1512,7 @@ func (v *uint8StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1155,23 +1524,37 @@ func (v *uint8StringMapValue) IsCumulative() bool { // -- uint16StringMapValue. type uint16StringMapValue struct { - value *map[uint16]string + value *map[uint16]string + separator string } -var ( - _ RepeatableFlag = (*uint16StringMapValue)(nil) - _ Value = (*uint16StringMapValue)(nil) - _ Getter = (*uint16StringMapValue)(nil) -) +var _ RepeatableFlag = (*uint16StringMapValue)(nil) +var _ Value = (*uint16StringMapValue)(nil) +var _ Getter = (*uint16StringMapValue)(nil) -func newUint16StringMapValue(m *map[uint16]string) *uint16StringMapValue { - return &uint16StringMapValue{ +func newUint16StringMapValue(m *map[uint16]string, sep *string) *uint16StringMapValue { + s := &uint16StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1198,10 +1581,11 @@ func (v *uint16StringMapValue) Set(val string) error { return nil } -func (v *uint16StringMapValue) Get() interface{} { +func (v *uint16StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1209,6 +1593,7 @@ func (v *uint16StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1220,23 +1605,37 @@ func (v *uint16StringMapValue) IsCumulative() bool { // -- uint32StringMapValue. type uint32StringMapValue struct { - value *map[uint32]string + value *map[uint32]string + separator string } -var ( - _ RepeatableFlag = (*uint32StringMapValue)(nil) - _ Value = (*uint32StringMapValue)(nil) - _ Getter = (*uint32StringMapValue)(nil) -) +var _ RepeatableFlag = (*uint32StringMapValue)(nil) +var _ Value = (*uint32StringMapValue)(nil) +var _ Getter = (*uint32StringMapValue)(nil) -func newUint32StringMapValue(m *map[uint32]string) *uint32StringMapValue { - return &uint32StringMapValue{ +func newUint32StringMapValue(m *map[uint32]string, sep *string) *uint32StringMapValue { + s := &uint32StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1263,10 +1662,11 @@ func (v *uint32StringMapValue) Set(val string) error { return nil } -func (v *uint32StringMapValue) Get() interface{} { +func (v *uint32StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1274,6 +1674,7 @@ func (v *uint32StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1285,23 +1686,37 @@ func (v *uint32StringMapValue) IsCumulative() bool { // -- uint64StringMapValue. type uint64StringMapValue struct { - value *map[uint64]string + value *map[uint64]string + separator string } -var ( - _ RepeatableFlag = (*uint64StringMapValue)(nil) - _ Value = (*uint64StringMapValue)(nil) - _ Getter = (*uint64StringMapValue)(nil) -) +var _ RepeatableFlag = (*uint64StringMapValue)(nil) +var _ Value = (*uint64StringMapValue)(nil) +var _ Getter = (*uint64StringMapValue)(nil) -func newUint64StringMapValue(m *map[uint64]string) *uint64StringMapValue { - return &uint64StringMapValue{ +func newUint64StringMapValue(m *map[uint64]string, sep *string) *uint64StringMapValue { + s := &uint64StringMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64StringMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1328,10 +1743,11 @@ func (v *uint64StringMapValue) Set(val string) error { return nil } -func (v *uint64StringMapValue) Get() interface{} { +func (v *uint64StringMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1339,6 +1755,7 @@ func (v *uint64StringMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1353,35 +1770,42 @@ type boolValue struct { value *bool } -var ( - _ Value = (*boolValue)(nil) - _ Getter = (*boolValue)(nil) -) +var _ Value = (*boolValue)(nil) +var _ Getter = (*boolValue)(nil) func newBoolValue(p *bool) *boolValue { return &boolValue{value: p} } func (v *boolValue) Set(s string) error { + parsed, err := strconv.ParseBool(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *boolValue) Get() interface{} { +func (v *boolValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *boolValue) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatBool(*v.value) } + return "" } @@ -1390,24 +1814,38 @@ func (v *boolValue) Type() string { return "bool" } // -- boolSlice Value type boolSliceValue struct { - value *[]bool - changed bool + value *[]bool + changed bool + separator string } -var ( - _ RepeatableFlag = (*boolSliceValue)(nil) - _ Value = (*boolSliceValue)(nil) - _ Getter = (*boolSliceValue)(nil) -) +var _ RepeatableFlag = (*boolSliceValue)(nil) +var _ Value = (*boolSliceValue)(nil) +var _ Getter = (*boolSliceValue)(nil) -func newBoolSliceValue(slice *[]bool) *boolSliceValue { - return &boolSliceValue{ +func newBoolSliceValue(slice *[]bool, sep *string) *boolSliceValue { + s := &boolSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *boolSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]bool, len(ss)) for i, s := range ss { @@ -1415,7 +1853,9 @@ func (v *boolSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -1424,24 +1864,29 @@ func (v *boolSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *boolSliceValue) Get() interface{} { +func (v *boolSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]bool)(nil) } func (v *boolSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newBoolValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -1453,23 +1898,37 @@ func (v *boolSliceValue) IsCumulative() bool { // -- stringBoolMapValue. type stringBoolMapValue struct { - value *map[string]bool + value *map[string]bool + separator string } -var ( - _ RepeatableFlag = (*stringBoolMapValue)(nil) - _ Value = (*stringBoolMapValue)(nil) - _ Getter = (*stringBoolMapValue)(nil) -) +var _ RepeatableFlag = (*stringBoolMapValue)(nil) +var _ Value = (*stringBoolMapValue)(nil) +var _ Getter = (*stringBoolMapValue)(nil) -func newStringBoolMapValue(m *map[string]bool) *stringBoolMapValue { - return &stringBoolMapValue{ +func newStringBoolMapValue(m *map[string]bool, sep *string) *stringBoolMapValue { + s := &stringBoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringBoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1496,10 +1955,11 @@ func (v *stringBoolMapValue) Set(val string) error { return nil } -func (v *stringBoolMapValue) Get() interface{} { +func (v *stringBoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1507,6 +1967,7 @@ func (v *stringBoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1518,23 +1979,37 @@ func (v *stringBoolMapValue) IsCumulative() bool { // -- intBoolMapValue. type intBoolMapValue struct { - value *map[int]bool + value *map[int]bool + separator string } -var ( - _ RepeatableFlag = (*intBoolMapValue)(nil) - _ Value = (*intBoolMapValue)(nil) - _ Getter = (*intBoolMapValue)(nil) -) +var _ RepeatableFlag = (*intBoolMapValue)(nil) +var _ Value = (*intBoolMapValue)(nil) +var _ Getter = (*intBoolMapValue)(nil) -func newIntBoolMapValue(m *map[int]bool) *intBoolMapValue { - return &intBoolMapValue{ +func newIntBoolMapValue(m *map[int]bool, sep *string) *intBoolMapValue { + s := &intBoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intBoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1566,10 +2041,11 @@ func (v *intBoolMapValue) Set(val string) error { return nil } -func (v *intBoolMapValue) Get() interface{} { +func (v *intBoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1577,6 +2053,7 @@ func (v *intBoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1588,23 +2065,37 @@ func (v *intBoolMapValue) IsCumulative() bool { // -- int8BoolMapValue. type int8BoolMapValue struct { - value *map[int8]bool + value *map[int8]bool + separator string } -var ( - _ RepeatableFlag = (*int8BoolMapValue)(nil) - _ Value = (*int8BoolMapValue)(nil) - _ Getter = (*int8BoolMapValue)(nil) -) +var _ RepeatableFlag = (*int8BoolMapValue)(nil) +var _ Value = (*int8BoolMapValue)(nil) +var _ Getter = (*int8BoolMapValue)(nil) -func newInt8BoolMapValue(m *map[int8]bool) *int8BoolMapValue { - return &int8BoolMapValue{ +func newInt8BoolMapValue(m *map[int8]bool, sep *string) *int8BoolMapValue { + s := &int8BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1636,10 +2127,11 @@ func (v *int8BoolMapValue) Set(val string) error { return nil } -func (v *int8BoolMapValue) Get() interface{} { +func (v *int8BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1647,6 +2139,7 @@ func (v *int8BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1658,23 +2151,37 @@ func (v *int8BoolMapValue) IsCumulative() bool { // -- int16BoolMapValue. type int16BoolMapValue struct { - value *map[int16]bool + value *map[int16]bool + separator string } -var ( - _ RepeatableFlag = (*int16BoolMapValue)(nil) - _ Value = (*int16BoolMapValue)(nil) - _ Getter = (*int16BoolMapValue)(nil) -) +var _ RepeatableFlag = (*int16BoolMapValue)(nil) +var _ Value = (*int16BoolMapValue)(nil) +var _ Getter = (*int16BoolMapValue)(nil) -func newInt16BoolMapValue(m *map[int16]bool) *int16BoolMapValue { - return &int16BoolMapValue{ +func newInt16BoolMapValue(m *map[int16]bool, sep *string) *int16BoolMapValue { + s := &int16BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1706,10 +2213,11 @@ func (v *int16BoolMapValue) Set(val string) error { return nil } -func (v *int16BoolMapValue) Get() interface{} { +func (v *int16BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1717,6 +2225,7 @@ func (v *int16BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1728,23 +2237,37 @@ func (v *int16BoolMapValue) IsCumulative() bool { // -- int32BoolMapValue. type int32BoolMapValue struct { - value *map[int32]bool + value *map[int32]bool + separator string } -var ( - _ RepeatableFlag = (*int32BoolMapValue)(nil) - _ Value = (*int32BoolMapValue)(nil) - _ Getter = (*int32BoolMapValue)(nil) -) +var _ RepeatableFlag = (*int32BoolMapValue)(nil) +var _ Value = (*int32BoolMapValue)(nil) +var _ Getter = (*int32BoolMapValue)(nil) -func newInt32BoolMapValue(m *map[int32]bool) *int32BoolMapValue { - return &int32BoolMapValue{ +func newInt32BoolMapValue(m *map[int32]bool, sep *string) *int32BoolMapValue { + s := &int32BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1776,10 +2299,11 @@ func (v *int32BoolMapValue) Set(val string) error { return nil } -func (v *int32BoolMapValue) Get() interface{} { +func (v *int32BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1787,6 +2311,7 @@ func (v *int32BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1798,23 +2323,37 @@ func (v *int32BoolMapValue) IsCumulative() bool { // -- int64BoolMapValue. type int64BoolMapValue struct { - value *map[int64]bool + value *map[int64]bool + separator string } -var ( - _ RepeatableFlag = (*int64BoolMapValue)(nil) - _ Value = (*int64BoolMapValue)(nil) - _ Getter = (*int64BoolMapValue)(nil) -) +var _ RepeatableFlag = (*int64BoolMapValue)(nil) +var _ Value = (*int64BoolMapValue)(nil) +var _ Getter = (*int64BoolMapValue)(nil) -func newInt64BoolMapValue(m *map[int64]bool) *int64BoolMapValue { - return &int64BoolMapValue{ +func newInt64BoolMapValue(m *map[int64]bool, sep *string) *int64BoolMapValue { + s := &int64BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1846,10 +2385,11 @@ func (v *int64BoolMapValue) Set(val string) error { return nil } -func (v *int64BoolMapValue) Get() interface{} { +func (v *int64BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1857,6 +2397,7 @@ func (v *int64BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1868,23 +2409,37 @@ func (v *int64BoolMapValue) IsCumulative() bool { // -- uintBoolMapValue. type uintBoolMapValue struct { - value *map[uint]bool + value *map[uint]bool + separator string } -var ( - _ RepeatableFlag = (*uintBoolMapValue)(nil) - _ Value = (*uintBoolMapValue)(nil) - _ Getter = (*uintBoolMapValue)(nil) -) +var _ RepeatableFlag = (*uintBoolMapValue)(nil) +var _ Value = (*uintBoolMapValue)(nil) +var _ Getter = (*uintBoolMapValue)(nil) -func newUintBoolMapValue(m *map[uint]bool) *uintBoolMapValue { - return &uintBoolMapValue{ +func newUintBoolMapValue(m *map[uint]bool, sep *string) *uintBoolMapValue { + s := &uintBoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintBoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1916,10 +2471,11 @@ func (v *uintBoolMapValue) Set(val string) error { return nil } -func (v *uintBoolMapValue) Get() interface{} { +func (v *uintBoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1927,6 +2483,7 @@ func (v *uintBoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -1938,23 +2495,37 @@ func (v *uintBoolMapValue) IsCumulative() bool { // -- uint8BoolMapValue. type uint8BoolMapValue struct { - value *map[uint8]bool + value *map[uint8]bool + separator string } -var ( - _ RepeatableFlag = (*uint8BoolMapValue)(nil) - _ Value = (*uint8BoolMapValue)(nil) - _ Getter = (*uint8BoolMapValue)(nil) -) +var _ RepeatableFlag = (*uint8BoolMapValue)(nil) +var _ Value = (*uint8BoolMapValue)(nil) +var _ Getter = (*uint8BoolMapValue)(nil) -func newUint8BoolMapValue(m *map[uint8]bool) *uint8BoolMapValue { - return &uint8BoolMapValue{ +func newUint8BoolMapValue(m *map[uint8]bool, sep *string) *uint8BoolMapValue { + s := &uint8BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -1986,10 +2557,11 @@ func (v *uint8BoolMapValue) Set(val string) error { return nil } -func (v *uint8BoolMapValue) Get() interface{} { +func (v *uint8BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -1997,6 +2569,7 @@ func (v *uint8BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2008,23 +2581,37 @@ func (v *uint8BoolMapValue) IsCumulative() bool { // -- uint16BoolMapValue. type uint16BoolMapValue struct { - value *map[uint16]bool + value *map[uint16]bool + separator string } -var ( - _ RepeatableFlag = (*uint16BoolMapValue)(nil) - _ Value = (*uint16BoolMapValue)(nil) - _ Getter = (*uint16BoolMapValue)(nil) -) +var _ RepeatableFlag = (*uint16BoolMapValue)(nil) +var _ Value = (*uint16BoolMapValue)(nil) +var _ Getter = (*uint16BoolMapValue)(nil) -func newUint16BoolMapValue(m *map[uint16]bool) *uint16BoolMapValue { - return &uint16BoolMapValue{ +func newUint16BoolMapValue(m *map[uint16]bool, sep *string) *uint16BoolMapValue { + s := &uint16BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2056,10 +2643,11 @@ func (v *uint16BoolMapValue) Set(val string) error { return nil } -func (v *uint16BoolMapValue) Get() interface{} { +func (v *uint16BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2067,6 +2655,7 @@ func (v *uint16BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2078,23 +2667,37 @@ func (v *uint16BoolMapValue) IsCumulative() bool { // -- uint32BoolMapValue. type uint32BoolMapValue struct { - value *map[uint32]bool + value *map[uint32]bool + separator string } -var ( - _ RepeatableFlag = (*uint32BoolMapValue)(nil) - _ Value = (*uint32BoolMapValue)(nil) - _ Getter = (*uint32BoolMapValue)(nil) -) +var _ RepeatableFlag = (*uint32BoolMapValue)(nil) +var _ Value = (*uint32BoolMapValue)(nil) +var _ Getter = (*uint32BoolMapValue)(nil) -func newUint32BoolMapValue(m *map[uint32]bool) *uint32BoolMapValue { - return &uint32BoolMapValue{ +func newUint32BoolMapValue(m *map[uint32]bool, sep *string) *uint32BoolMapValue { + s := &uint32BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2126,10 +2729,11 @@ func (v *uint32BoolMapValue) Set(val string) error { return nil } -func (v *uint32BoolMapValue) Get() interface{} { +func (v *uint32BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2137,6 +2741,7 @@ func (v *uint32BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2148,23 +2753,37 @@ func (v *uint32BoolMapValue) IsCumulative() bool { // -- uint64BoolMapValue. type uint64BoolMapValue struct { - value *map[uint64]bool + value *map[uint64]bool + separator string } -var ( - _ RepeatableFlag = (*uint64BoolMapValue)(nil) - _ Value = (*uint64BoolMapValue)(nil) - _ Getter = (*uint64BoolMapValue)(nil) -) +var _ RepeatableFlag = (*uint64BoolMapValue)(nil) +var _ Value = (*uint64BoolMapValue)(nil) +var _ Getter = (*uint64BoolMapValue)(nil) -func newUint64BoolMapValue(m *map[uint64]bool) *uint64BoolMapValue { - return &uint64BoolMapValue{ +func newUint64BoolMapValue(m *map[uint64]bool, sep *string) *uint64BoolMapValue { + s := &uint64BoolMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64BoolMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2196,10 +2815,11 @@ func (v *uint64BoolMapValue) Set(val string) error { return nil } -func (v *uint64BoolMapValue) Get() interface{} { +func (v *uint64BoolMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2207,6 +2827,7 @@ func (v *uint64BoolMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2221,35 +2842,42 @@ type uintValue struct { value *uint } -var ( - _ Value = (*uintValue)(nil) - _ Getter = (*uintValue)(nil) -) +var _ Value = (*uintValue)(nil) +var _ Getter = (*uintValue)(nil) func newUintValue(p *uint) *uintValue { return &uintValue{value: p} } func (v *uintValue) Set(s string) error { + parsed, err := strconv.ParseUint(s, 0, 64) if err == nil { + *v.value = (uint)(parsed) + return nil } + return err + } -func (v *uintValue) Get() interface{} { +func (v *uintValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *uintValue) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatUint(uint64(*v.value), 10) } + return "" } @@ -2258,24 +2886,38 @@ func (v *uintValue) Type() string { return "uint" } // -- uintSlice Value type uintSliceValue struct { - value *[]uint - changed bool + value *[]uint + changed bool + separator string } -var ( - _ RepeatableFlag = (*uintSliceValue)(nil) - _ Value = (*uintSliceValue)(nil) - _ Getter = (*uintSliceValue)(nil) -) +var _ RepeatableFlag = (*uintSliceValue)(nil) +var _ Value = (*uintSliceValue)(nil) +var _ Getter = (*uintSliceValue)(nil) -func newUintSliceValue(slice *[]uint) *uintSliceValue { - return &uintSliceValue{ +func newUintSliceValue(slice *[]uint, sep *string) *uintSliceValue { + s := &uintSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]uint, len(ss)) for i, s := range ss { @@ -2283,7 +2925,9 @@ func (v *uintSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (uint)(parsed) + } if !v.changed { @@ -2292,24 +2936,29 @@ func (v *uintSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *uintSliceValue) Get() interface{} { +func (v *uintSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]uint)(nil) } func (v *uintSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newUintValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -2321,23 +2970,37 @@ func (v *uintSliceValue) IsCumulative() bool { // -- stringUintMapValue. type stringUintMapValue struct { - value *map[string]uint + value *map[string]uint + separator string } -var ( - _ RepeatableFlag = (*stringUintMapValue)(nil) - _ Value = (*stringUintMapValue)(nil) - _ Getter = (*stringUintMapValue)(nil) -) +var _ RepeatableFlag = (*stringUintMapValue)(nil) +var _ Value = (*stringUintMapValue)(nil) +var _ Getter = (*stringUintMapValue)(nil) -func newStringUintMapValue(m *map[string]uint) *stringUintMapValue { - return &stringUintMapValue{ +func newStringUintMapValue(m *map[string]uint, sep *string) *stringUintMapValue { + s := &stringUintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringUintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2364,10 +3027,11 @@ func (v *stringUintMapValue) Set(val string) error { return nil } -func (v *stringUintMapValue) Get() interface{} { +func (v *stringUintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2375,6 +3039,7 @@ func (v *stringUintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2386,23 +3051,37 @@ func (v *stringUintMapValue) IsCumulative() bool { // -- intUintMapValue. type intUintMapValue struct { - value *map[int]uint + value *map[int]uint + separator string } -var ( - _ RepeatableFlag = (*intUintMapValue)(nil) - _ Value = (*intUintMapValue)(nil) - _ Getter = (*intUintMapValue)(nil) -) +var _ RepeatableFlag = (*intUintMapValue)(nil) +var _ Value = (*intUintMapValue)(nil) +var _ Getter = (*intUintMapValue)(nil) -func newIntUintMapValue(m *map[int]uint) *intUintMapValue { - return &intUintMapValue{ +func newIntUintMapValue(m *map[int]uint, sep *string) *intUintMapValue { + s := &intUintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intUintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2434,10 +3113,11 @@ func (v *intUintMapValue) Set(val string) error { return nil } -func (v *intUintMapValue) Get() interface{} { +func (v *intUintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2445,6 +3125,7 @@ func (v *intUintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2456,23 +3137,37 @@ func (v *intUintMapValue) IsCumulative() bool { // -- int8UintMapValue. type int8UintMapValue struct { - value *map[int8]uint + value *map[int8]uint + separator string } -var ( - _ RepeatableFlag = (*int8UintMapValue)(nil) - _ Value = (*int8UintMapValue)(nil) - _ Getter = (*int8UintMapValue)(nil) -) +var _ RepeatableFlag = (*int8UintMapValue)(nil) +var _ Value = (*int8UintMapValue)(nil) +var _ Getter = (*int8UintMapValue)(nil) -func newInt8UintMapValue(m *map[int8]uint) *int8UintMapValue { - return &int8UintMapValue{ +func newInt8UintMapValue(m *map[int8]uint, sep *string) *int8UintMapValue { + s := &int8UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2504,10 +3199,11 @@ func (v *int8UintMapValue) Set(val string) error { return nil } -func (v *int8UintMapValue) Get() interface{} { +func (v *int8UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2515,6 +3211,7 @@ func (v *int8UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2526,23 +3223,37 @@ func (v *int8UintMapValue) IsCumulative() bool { // -- int16UintMapValue. type int16UintMapValue struct { - value *map[int16]uint + value *map[int16]uint + separator string } -var ( - _ RepeatableFlag = (*int16UintMapValue)(nil) - _ Value = (*int16UintMapValue)(nil) - _ Getter = (*int16UintMapValue)(nil) -) +var _ RepeatableFlag = (*int16UintMapValue)(nil) +var _ Value = (*int16UintMapValue)(nil) +var _ Getter = (*int16UintMapValue)(nil) -func newInt16UintMapValue(m *map[int16]uint) *int16UintMapValue { - return &int16UintMapValue{ +func newInt16UintMapValue(m *map[int16]uint, sep *string) *int16UintMapValue { + s := &int16UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2574,10 +3285,11 @@ func (v *int16UintMapValue) Set(val string) error { return nil } -func (v *int16UintMapValue) Get() interface{} { +func (v *int16UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2585,6 +3297,7 @@ func (v *int16UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2596,23 +3309,37 @@ func (v *int16UintMapValue) IsCumulative() bool { // -- int32UintMapValue. type int32UintMapValue struct { - value *map[int32]uint + value *map[int32]uint + separator string } -var ( - _ RepeatableFlag = (*int32UintMapValue)(nil) - _ Value = (*int32UintMapValue)(nil) - _ Getter = (*int32UintMapValue)(nil) -) +var _ RepeatableFlag = (*int32UintMapValue)(nil) +var _ Value = (*int32UintMapValue)(nil) +var _ Getter = (*int32UintMapValue)(nil) -func newInt32UintMapValue(m *map[int32]uint) *int32UintMapValue { - return &int32UintMapValue{ +func newInt32UintMapValue(m *map[int32]uint, sep *string) *int32UintMapValue { + s := &int32UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2644,10 +3371,11 @@ func (v *int32UintMapValue) Set(val string) error { return nil } -func (v *int32UintMapValue) Get() interface{} { +func (v *int32UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2655,6 +3383,7 @@ func (v *int32UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2666,23 +3395,37 @@ func (v *int32UintMapValue) IsCumulative() bool { // -- int64UintMapValue. type int64UintMapValue struct { - value *map[int64]uint + value *map[int64]uint + separator string } -var ( - _ RepeatableFlag = (*int64UintMapValue)(nil) - _ Value = (*int64UintMapValue)(nil) - _ Getter = (*int64UintMapValue)(nil) -) +var _ RepeatableFlag = (*int64UintMapValue)(nil) +var _ Value = (*int64UintMapValue)(nil) +var _ Getter = (*int64UintMapValue)(nil) -func newInt64UintMapValue(m *map[int64]uint) *int64UintMapValue { - return &int64UintMapValue{ +func newInt64UintMapValue(m *map[int64]uint, sep *string) *int64UintMapValue { + s := &int64UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2714,10 +3457,11 @@ func (v *int64UintMapValue) Set(val string) error { return nil } -func (v *int64UintMapValue) Get() interface{} { +func (v *int64UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2725,6 +3469,7 @@ func (v *int64UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2736,23 +3481,37 @@ func (v *int64UintMapValue) IsCumulative() bool { // -- uintUintMapValue. type uintUintMapValue struct { - value *map[uint]uint + value *map[uint]uint + separator string } -var ( - _ RepeatableFlag = (*uintUintMapValue)(nil) - _ Value = (*uintUintMapValue)(nil) - _ Getter = (*uintUintMapValue)(nil) -) +var _ RepeatableFlag = (*uintUintMapValue)(nil) +var _ Value = (*uintUintMapValue)(nil) +var _ Getter = (*uintUintMapValue)(nil) -func newUintUintMapValue(m *map[uint]uint) *uintUintMapValue { - return &uintUintMapValue{ +func newUintUintMapValue(m *map[uint]uint, sep *string) *uintUintMapValue { + s := &uintUintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintUintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2784,10 +3543,11 @@ func (v *uintUintMapValue) Set(val string) error { return nil } -func (v *uintUintMapValue) Get() interface{} { +func (v *uintUintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2795,6 +3555,7 @@ func (v *uintUintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2806,23 +3567,37 @@ func (v *uintUintMapValue) IsCumulative() bool { // -- uint8UintMapValue. type uint8UintMapValue struct { - value *map[uint8]uint + value *map[uint8]uint + separator string } -var ( - _ RepeatableFlag = (*uint8UintMapValue)(nil) - _ Value = (*uint8UintMapValue)(nil) - _ Getter = (*uint8UintMapValue)(nil) -) +var _ RepeatableFlag = (*uint8UintMapValue)(nil) +var _ Value = (*uint8UintMapValue)(nil) +var _ Getter = (*uint8UintMapValue)(nil) -func newUint8UintMapValue(m *map[uint8]uint) *uint8UintMapValue { - return &uint8UintMapValue{ +func newUint8UintMapValue(m *map[uint8]uint, sep *string) *uint8UintMapValue { + s := &uint8UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2854,10 +3629,11 @@ func (v *uint8UintMapValue) Set(val string) error { return nil } -func (v *uint8UintMapValue) Get() interface{} { +func (v *uint8UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2865,6 +3641,7 @@ func (v *uint8UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2876,23 +3653,37 @@ func (v *uint8UintMapValue) IsCumulative() bool { // -- uint16UintMapValue. type uint16UintMapValue struct { - value *map[uint16]uint + value *map[uint16]uint + separator string } -var ( - _ RepeatableFlag = (*uint16UintMapValue)(nil) - _ Value = (*uint16UintMapValue)(nil) - _ Getter = (*uint16UintMapValue)(nil) -) +var _ RepeatableFlag = (*uint16UintMapValue)(nil) +var _ Value = (*uint16UintMapValue)(nil) +var _ Getter = (*uint16UintMapValue)(nil) -func newUint16UintMapValue(m *map[uint16]uint) *uint16UintMapValue { - return &uint16UintMapValue{ +func newUint16UintMapValue(m *map[uint16]uint, sep *string) *uint16UintMapValue { + s := &uint16UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2924,10 +3715,11 @@ func (v *uint16UintMapValue) Set(val string) error { return nil } -func (v *uint16UintMapValue) Get() interface{} { +func (v *uint16UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -2935,6 +3727,7 @@ func (v *uint16UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -2946,23 +3739,37 @@ func (v *uint16UintMapValue) IsCumulative() bool { // -- uint32UintMapValue. type uint32UintMapValue struct { - value *map[uint32]uint + value *map[uint32]uint + separator string } -var ( - _ RepeatableFlag = (*uint32UintMapValue)(nil) - _ Value = (*uint32UintMapValue)(nil) - _ Getter = (*uint32UintMapValue)(nil) -) +var _ RepeatableFlag = (*uint32UintMapValue)(nil) +var _ Value = (*uint32UintMapValue)(nil) +var _ Getter = (*uint32UintMapValue)(nil) -func newUint32UintMapValue(m *map[uint32]uint) *uint32UintMapValue { - return &uint32UintMapValue{ +func newUint32UintMapValue(m *map[uint32]uint, sep *string) *uint32UintMapValue { + s := &uint32UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -2994,10 +3801,11 @@ func (v *uint32UintMapValue) Set(val string) error { return nil } -func (v *uint32UintMapValue) Get() interface{} { +func (v *uint32UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3005,6 +3813,7 @@ func (v *uint32UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3016,23 +3825,37 @@ func (v *uint32UintMapValue) IsCumulative() bool { // -- uint64UintMapValue. type uint64UintMapValue struct { - value *map[uint64]uint + value *map[uint64]uint + separator string } -var ( - _ RepeatableFlag = (*uint64UintMapValue)(nil) - _ Value = (*uint64UintMapValue)(nil) - _ Getter = (*uint64UintMapValue)(nil) -) +var _ RepeatableFlag = (*uint64UintMapValue)(nil) +var _ Value = (*uint64UintMapValue)(nil) +var _ Getter = (*uint64UintMapValue)(nil) -func newUint64UintMapValue(m *map[uint64]uint) *uint64UintMapValue { - return &uint64UintMapValue{ +func newUint64UintMapValue(m *map[uint64]uint, sep *string) *uint64UintMapValue { + s := &uint64UintMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64UintMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3064,10 +3887,11 @@ func (v *uint64UintMapValue) Set(val string) error { return nil } -func (v *uint64UintMapValue) Get() interface{} { +func (v *uint64UintMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3075,6 +3899,7 @@ func (v *uint64UintMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3089,35 +3914,42 @@ type uint8Value struct { value *uint8 } -var ( - _ Value = (*uint8Value)(nil) - _ Getter = (*uint8Value)(nil) -) +var _ Value = (*uint8Value)(nil) +var _ Getter = (*uint8Value)(nil) func newUint8Value(p *uint8) *uint8Value { return &uint8Value{value: p} } func (v *uint8Value) Set(s string) error { + parsed, err := strconv.ParseUint(s, 0, 8) if err == nil { + *v.value = (uint8)(parsed) + return nil } + return err + } -func (v *uint8Value) Get() interface{} { +func (v *uint8Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *uint8Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatUint(uint64(*v.value), 10) } + return "" } @@ -3126,24 +3958,38 @@ func (v *uint8Value) Type() string { return "uint8" } // -- uint8Slice Value type uint8SliceValue struct { - value *[]uint8 - changed bool + value *[]uint8 + changed bool + separator string } -var ( - _ RepeatableFlag = (*uint8SliceValue)(nil) - _ Value = (*uint8SliceValue)(nil) - _ Getter = (*uint8SliceValue)(nil) -) +var _ RepeatableFlag = (*uint8SliceValue)(nil) +var _ Value = (*uint8SliceValue)(nil) +var _ Getter = (*uint8SliceValue)(nil) -func newUint8SliceValue(slice *[]uint8) *uint8SliceValue { - return &uint8SliceValue{ +func newUint8SliceValue(slice *[]uint8, sep *string) *uint8SliceValue { + s := &uint8SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]uint8, len(ss)) for i, s := range ss { @@ -3151,7 +3997,9 @@ func (v *uint8SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (uint8)(parsed) + } if !v.changed { @@ -3160,24 +4008,29 @@ func (v *uint8SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *uint8SliceValue) Get() interface{} { +func (v *uint8SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]uint8)(nil) } func (v *uint8SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newUint8Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -3189,23 +4042,37 @@ func (v *uint8SliceValue) IsCumulative() bool { // -- stringUint8MapValue. type stringUint8MapValue struct { - value *map[string]uint8 + value *map[string]uint8 + separator string } -var ( - _ RepeatableFlag = (*stringUint8MapValue)(nil) - _ Value = (*stringUint8MapValue)(nil) - _ Getter = (*stringUint8MapValue)(nil) -) +var _ RepeatableFlag = (*stringUint8MapValue)(nil) +var _ Value = (*stringUint8MapValue)(nil) +var _ Getter = (*stringUint8MapValue)(nil) -func newStringUint8MapValue(m *map[string]uint8) *stringUint8MapValue { - return &stringUint8MapValue{ +func newStringUint8MapValue(m *map[string]uint8, sep *string) *stringUint8MapValue { + s := &stringUint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringUint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3232,10 +4099,11 @@ func (v *stringUint8MapValue) Set(val string) error { return nil } -func (v *stringUint8MapValue) Get() interface{} { +func (v *stringUint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3243,6 +4111,7 @@ func (v *stringUint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3254,23 +4123,37 @@ func (v *stringUint8MapValue) IsCumulative() bool { // -- intUint8MapValue. type intUint8MapValue struct { - value *map[int]uint8 + value *map[int]uint8 + separator string } -var ( - _ RepeatableFlag = (*intUint8MapValue)(nil) - _ Value = (*intUint8MapValue)(nil) - _ Getter = (*intUint8MapValue)(nil) -) +var _ RepeatableFlag = (*intUint8MapValue)(nil) +var _ Value = (*intUint8MapValue)(nil) +var _ Getter = (*intUint8MapValue)(nil) -func newIntUint8MapValue(m *map[int]uint8) *intUint8MapValue { - return &intUint8MapValue{ +func newIntUint8MapValue(m *map[int]uint8, sep *string) *intUint8MapValue { + s := &intUint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intUint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3302,10 +4185,11 @@ func (v *intUint8MapValue) Set(val string) error { return nil } -func (v *intUint8MapValue) Get() interface{} { +func (v *intUint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3313,6 +4197,7 @@ func (v *intUint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3324,23 +4209,37 @@ func (v *intUint8MapValue) IsCumulative() bool { // -- int8Uint8MapValue. type int8Uint8MapValue struct { - value *map[int8]uint8 + value *map[int8]uint8 + separator string } -var ( - _ RepeatableFlag = (*int8Uint8MapValue)(nil) - _ Value = (*int8Uint8MapValue)(nil) - _ Getter = (*int8Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*int8Uint8MapValue)(nil) +var _ Value = (*int8Uint8MapValue)(nil) +var _ Getter = (*int8Uint8MapValue)(nil) -func newInt8Uint8MapValue(m *map[int8]uint8) *int8Uint8MapValue { - return &int8Uint8MapValue{ +func newInt8Uint8MapValue(m *map[int8]uint8, sep *string) *int8Uint8MapValue { + s := &int8Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3372,10 +4271,11 @@ func (v *int8Uint8MapValue) Set(val string) error { return nil } -func (v *int8Uint8MapValue) Get() interface{} { +func (v *int8Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3383,6 +4283,7 @@ func (v *int8Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3394,23 +4295,37 @@ func (v *int8Uint8MapValue) IsCumulative() bool { // -- int16Uint8MapValue. type int16Uint8MapValue struct { - value *map[int16]uint8 + value *map[int16]uint8 + separator string } -var ( - _ RepeatableFlag = (*int16Uint8MapValue)(nil) - _ Value = (*int16Uint8MapValue)(nil) - _ Getter = (*int16Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*int16Uint8MapValue)(nil) +var _ Value = (*int16Uint8MapValue)(nil) +var _ Getter = (*int16Uint8MapValue)(nil) -func newInt16Uint8MapValue(m *map[int16]uint8) *int16Uint8MapValue { - return &int16Uint8MapValue{ +func newInt16Uint8MapValue(m *map[int16]uint8, sep *string) *int16Uint8MapValue { + s := &int16Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3442,10 +4357,11 @@ func (v *int16Uint8MapValue) Set(val string) error { return nil } -func (v *int16Uint8MapValue) Get() interface{} { +func (v *int16Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3453,6 +4369,7 @@ func (v *int16Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3464,23 +4381,37 @@ func (v *int16Uint8MapValue) IsCumulative() bool { // -- int32Uint8MapValue. type int32Uint8MapValue struct { - value *map[int32]uint8 + value *map[int32]uint8 + separator string } -var ( - _ RepeatableFlag = (*int32Uint8MapValue)(nil) - _ Value = (*int32Uint8MapValue)(nil) - _ Getter = (*int32Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*int32Uint8MapValue)(nil) +var _ Value = (*int32Uint8MapValue)(nil) +var _ Getter = (*int32Uint8MapValue)(nil) -func newInt32Uint8MapValue(m *map[int32]uint8) *int32Uint8MapValue { - return &int32Uint8MapValue{ +func newInt32Uint8MapValue(m *map[int32]uint8, sep *string) *int32Uint8MapValue { + s := &int32Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3512,10 +4443,11 @@ func (v *int32Uint8MapValue) Set(val string) error { return nil } -func (v *int32Uint8MapValue) Get() interface{} { +func (v *int32Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3523,6 +4455,7 @@ func (v *int32Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3534,23 +4467,37 @@ func (v *int32Uint8MapValue) IsCumulative() bool { // -- int64Uint8MapValue. type int64Uint8MapValue struct { - value *map[int64]uint8 + value *map[int64]uint8 + separator string } -var ( - _ RepeatableFlag = (*int64Uint8MapValue)(nil) - _ Value = (*int64Uint8MapValue)(nil) - _ Getter = (*int64Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*int64Uint8MapValue)(nil) +var _ Value = (*int64Uint8MapValue)(nil) +var _ Getter = (*int64Uint8MapValue)(nil) -func newInt64Uint8MapValue(m *map[int64]uint8) *int64Uint8MapValue { - return &int64Uint8MapValue{ +func newInt64Uint8MapValue(m *map[int64]uint8, sep *string) *int64Uint8MapValue { + s := &int64Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3582,10 +4529,11 @@ func (v *int64Uint8MapValue) Set(val string) error { return nil } -func (v *int64Uint8MapValue) Get() interface{} { +func (v *int64Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3593,6 +4541,7 @@ func (v *int64Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3604,23 +4553,37 @@ func (v *int64Uint8MapValue) IsCumulative() bool { // -- uintUint8MapValue. type uintUint8MapValue struct { - value *map[uint]uint8 + value *map[uint]uint8 + separator string } -var ( - _ RepeatableFlag = (*uintUint8MapValue)(nil) - _ Value = (*uintUint8MapValue)(nil) - _ Getter = (*uintUint8MapValue)(nil) -) +var _ RepeatableFlag = (*uintUint8MapValue)(nil) +var _ Value = (*uintUint8MapValue)(nil) +var _ Getter = (*uintUint8MapValue)(nil) -func newUintUint8MapValue(m *map[uint]uint8) *uintUint8MapValue { - return &uintUint8MapValue{ +func newUintUint8MapValue(m *map[uint]uint8, sep *string) *uintUint8MapValue { + s := &uintUint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintUint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3652,10 +4615,11 @@ func (v *uintUint8MapValue) Set(val string) error { return nil } -func (v *uintUint8MapValue) Get() interface{} { +func (v *uintUint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3663,6 +4627,7 @@ func (v *uintUint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3674,23 +4639,37 @@ func (v *uintUint8MapValue) IsCumulative() bool { // -- uint8Uint8MapValue. type uint8Uint8MapValue struct { - value *map[uint8]uint8 + value *map[uint8]uint8 + separator string } -var ( - _ RepeatableFlag = (*uint8Uint8MapValue)(nil) - _ Value = (*uint8Uint8MapValue)(nil) - _ Getter = (*uint8Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Uint8MapValue)(nil) +var _ Value = (*uint8Uint8MapValue)(nil) +var _ Getter = (*uint8Uint8MapValue)(nil) -func newUint8Uint8MapValue(m *map[uint8]uint8) *uint8Uint8MapValue { - return &uint8Uint8MapValue{ +func newUint8Uint8MapValue(m *map[uint8]uint8, sep *string) *uint8Uint8MapValue { + s := &uint8Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3722,10 +4701,11 @@ func (v *uint8Uint8MapValue) Set(val string) error { return nil } -func (v *uint8Uint8MapValue) Get() interface{} { +func (v *uint8Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3733,6 +4713,7 @@ func (v *uint8Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3744,23 +4725,37 @@ func (v *uint8Uint8MapValue) IsCumulative() bool { // -- uint16Uint8MapValue. type uint16Uint8MapValue struct { - value *map[uint16]uint8 + value *map[uint16]uint8 + separator string } -var ( - _ RepeatableFlag = (*uint16Uint8MapValue)(nil) - _ Value = (*uint16Uint8MapValue)(nil) - _ Getter = (*uint16Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Uint8MapValue)(nil) +var _ Value = (*uint16Uint8MapValue)(nil) +var _ Getter = (*uint16Uint8MapValue)(nil) -func newUint16Uint8MapValue(m *map[uint16]uint8) *uint16Uint8MapValue { - return &uint16Uint8MapValue{ +func newUint16Uint8MapValue(m *map[uint16]uint8, sep *string) *uint16Uint8MapValue { + s := &uint16Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3792,10 +4787,11 @@ func (v *uint16Uint8MapValue) Set(val string) error { return nil } -func (v *uint16Uint8MapValue) Get() interface{} { +func (v *uint16Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3803,6 +4799,7 @@ func (v *uint16Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3814,23 +4811,37 @@ func (v *uint16Uint8MapValue) IsCumulative() bool { // -- uint32Uint8MapValue. type uint32Uint8MapValue struct { - value *map[uint32]uint8 + value *map[uint32]uint8 + separator string } -var ( - _ RepeatableFlag = (*uint32Uint8MapValue)(nil) - _ Value = (*uint32Uint8MapValue)(nil) - _ Getter = (*uint32Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Uint8MapValue)(nil) +var _ Value = (*uint32Uint8MapValue)(nil) +var _ Getter = (*uint32Uint8MapValue)(nil) -func newUint32Uint8MapValue(m *map[uint32]uint8) *uint32Uint8MapValue { - return &uint32Uint8MapValue{ +func newUint32Uint8MapValue(m *map[uint32]uint8, sep *string) *uint32Uint8MapValue { + s := &uint32Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3862,10 +4873,11 @@ func (v *uint32Uint8MapValue) Set(val string) error { return nil } -func (v *uint32Uint8MapValue) Get() interface{} { +func (v *uint32Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3873,6 +4885,7 @@ func (v *uint32Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3884,23 +4897,37 @@ func (v *uint32Uint8MapValue) IsCumulative() bool { // -- uint64Uint8MapValue. type uint64Uint8MapValue struct { - value *map[uint64]uint8 + value *map[uint64]uint8 + separator string } -var ( - _ RepeatableFlag = (*uint64Uint8MapValue)(nil) - _ Value = (*uint64Uint8MapValue)(nil) - _ Getter = (*uint64Uint8MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Uint8MapValue)(nil) +var _ Value = (*uint64Uint8MapValue)(nil) +var _ Getter = (*uint64Uint8MapValue)(nil) -func newUint64Uint8MapValue(m *map[uint64]uint8) *uint64Uint8MapValue { - return &uint64Uint8MapValue{ +func newUint64Uint8MapValue(m *map[uint64]uint8, sep *string) *uint64Uint8MapValue { + s := &uint64Uint8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Uint8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -3932,10 +4959,11 @@ func (v *uint64Uint8MapValue) Set(val string) error { return nil } -func (v *uint64Uint8MapValue) Get() interface{} { +func (v *uint64Uint8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -3943,6 +4971,7 @@ func (v *uint64Uint8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -3957,35 +4986,42 @@ type uint16Value struct { value *uint16 } -var ( - _ Value = (*uint16Value)(nil) - _ Getter = (*uint16Value)(nil) -) +var _ Value = (*uint16Value)(nil) +var _ Getter = (*uint16Value)(nil) func newUint16Value(p *uint16) *uint16Value { return &uint16Value{value: p} } func (v *uint16Value) Set(s string) error { + parsed, err := strconv.ParseUint(s, 0, 16) if err == nil { + *v.value = (uint16)(parsed) + return nil } + return err + } -func (v *uint16Value) Get() interface{} { +func (v *uint16Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *uint16Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatUint(uint64(*v.value), 10) } + return "" } @@ -3994,24 +5030,38 @@ func (v *uint16Value) Type() string { return "uint16" } // -- uint16Slice Value type uint16SliceValue struct { - value *[]uint16 - changed bool + value *[]uint16 + changed bool + separator string } -var ( - _ RepeatableFlag = (*uint16SliceValue)(nil) - _ Value = (*uint16SliceValue)(nil) - _ Getter = (*uint16SliceValue)(nil) -) +var _ RepeatableFlag = (*uint16SliceValue)(nil) +var _ Value = (*uint16SliceValue)(nil) +var _ Getter = (*uint16SliceValue)(nil) -func newUint16SliceValue(slice *[]uint16) *uint16SliceValue { - return &uint16SliceValue{ +func newUint16SliceValue(slice *[]uint16, sep *string) *uint16SliceValue { + s := &uint16SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]uint16, len(ss)) for i, s := range ss { @@ -4019,7 +5069,9 @@ func (v *uint16SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (uint16)(parsed) + } if !v.changed { @@ -4028,24 +5080,29 @@ func (v *uint16SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *uint16SliceValue) Get() interface{} { +func (v *uint16SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]uint16)(nil) } func (v *uint16SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newUint16Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -4057,23 +5114,37 @@ func (v *uint16SliceValue) IsCumulative() bool { // -- stringUint16MapValue. type stringUint16MapValue struct { - value *map[string]uint16 + value *map[string]uint16 + separator string } -var ( - _ RepeatableFlag = (*stringUint16MapValue)(nil) - _ Value = (*stringUint16MapValue)(nil) - _ Getter = (*stringUint16MapValue)(nil) -) +var _ RepeatableFlag = (*stringUint16MapValue)(nil) +var _ Value = (*stringUint16MapValue)(nil) +var _ Getter = (*stringUint16MapValue)(nil) -func newStringUint16MapValue(m *map[string]uint16) *stringUint16MapValue { - return &stringUint16MapValue{ +func newStringUint16MapValue(m *map[string]uint16, sep *string) *stringUint16MapValue { + s := &stringUint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringUint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4100,10 +5171,11 @@ func (v *stringUint16MapValue) Set(val string) error { return nil } -func (v *stringUint16MapValue) Get() interface{} { +func (v *stringUint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4111,6 +5183,7 @@ func (v *stringUint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4122,23 +5195,37 @@ func (v *stringUint16MapValue) IsCumulative() bool { // -- intUint16MapValue. type intUint16MapValue struct { - value *map[int]uint16 + value *map[int]uint16 + separator string } -var ( - _ RepeatableFlag = (*intUint16MapValue)(nil) - _ Value = (*intUint16MapValue)(nil) - _ Getter = (*intUint16MapValue)(nil) -) +var _ RepeatableFlag = (*intUint16MapValue)(nil) +var _ Value = (*intUint16MapValue)(nil) +var _ Getter = (*intUint16MapValue)(nil) -func newIntUint16MapValue(m *map[int]uint16) *intUint16MapValue { - return &intUint16MapValue{ +func newIntUint16MapValue(m *map[int]uint16, sep *string) *intUint16MapValue { + s := &intUint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intUint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4170,10 +5257,11 @@ func (v *intUint16MapValue) Set(val string) error { return nil } -func (v *intUint16MapValue) Get() interface{} { +func (v *intUint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4181,6 +5269,7 @@ func (v *intUint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4192,23 +5281,37 @@ func (v *intUint16MapValue) IsCumulative() bool { // -- int8Uint16MapValue. type int8Uint16MapValue struct { - value *map[int8]uint16 + value *map[int8]uint16 + separator string } -var ( - _ RepeatableFlag = (*int8Uint16MapValue)(nil) - _ Value = (*int8Uint16MapValue)(nil) - _ Getter = (*int8Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*int8Uint16MapValue)(nil) +var _ Value = (*int8Uint16MapValue)(nil) +var _ Getter = (*int8Uint16MapValue)(nil) -func newInt8Uint16MapValue(m *map[int8]uint16) *int8Uint16MapValue { - return &int8Uint16MapValue{ +func newInt8Uint16MapValue(m *map[int8]uint16, sep *string) *int8Uint16MapValue { + s := &int8Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4240,10 +5343,11 @@ func (v *int8Uint16MapValue) Set(val string) error { return nil } -func (v *int8Uint16MapValue) Get() interface{} { +func (v *int8Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4251,6 +5355,7 @@ func (v *int8Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4262,23 +5367,37 @@ func (v *int8Uint16MapValue) IsCumulative() bool { // -- int16Uint16MapValue. type int16Uint16MapValue struct { - value *map[int16]uint16 + value *map[int16]uint16 + separator string } -var ( - _ RepeatableFlag = (*int16Uint16MapValue)(nil) - _ Value = (*int16Uint16MapValue)(nil) - _ Getter = (*int16Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*int16Uint16MapValue)(nil) +var _ Value = (*int16Uint16MapValue)(nil) +var _ Getter = (*int16Uint16MapValue)(nil) -func newInt16Uint16MapValue(m *map[int16]uint16) *int16Uint16MapValue { - return &int16Uint16MapValue{ +func newInt16Uint16MapValue(m *map[int16]uint16, sep *string) *int16Uint16MapValue { + s := &int16Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4310,10 +5429,11 @@ func (v *int16Uint16MapValue) Set(val string) error { return nil } -func (v *int16Uint16MapValue) Get() interface{} { +func (v *int16Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4321,6 +5441,7 @@ func (v *int16Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4332,23 +5453,37 @@ func (v *int16Uint16MapValue) IsCumulative() bool { // -- int32Uint16MapValue. type int32Uint16MapValue struct { - value *map[int32]uint16 + value *map[int32]uint16 + separator string } -var ( - _ RepeatableFlag = (*int32Uint16MapValue)(nil) - _ Value = (*int32Uint16MapValue)(nil) - _ Getter = (*int32Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*int32Uint16MapValue)(nil) +var _ Value = (*int32Uint16MapValue)(nil) +var _ Getter = (*int32Uint16MapValue)(nil) -func newInt32Uint16MapValue(m *map[int32]uint16) *int32Uint16MapValue { - return &int32Uint16MapValue{ +func newInt32Uint16MapValue(m *map[int32]uint16, sep *string) *int32Uint16MapValue { + s := &int32Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4380,10 +5515,11 @@ func (v *int32Uint16MapValue) Set(val string) error { return nil } -func (v *int32Uint16MapValue) Get() interface{} { +func (v *int32Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4391,6 +5527,7 @@ func (v *int32Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4402,23 +5539,37 @@ func (v *int32Uint16MapValue) IsCumulative() bool { // -- int64Uint16MapValue. type int64Uint16MapValue struct { - value *map[int64]uint16 + value *map[int64]uint16 + separator string } -var ( - _ RepeatableFlag = (*int64Uint16MapValue)(nil) - _ Value = (*int64Uint16MapValue)(nil) - _ Getter = (*int64Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*int64Uint16MapValue)(nil) +var _ Value = (*int64Uint16MapValue)(nil) +var _ Getter = (*int64Uint16MapValue)(nil) -func newInt64Uint16MapValue(m *map[int64]uint16) *int64Uint16MapValue { - return &int64Uint16MapValue{ +func newInt64Uint16MapValue(m *map[int64]uint16, sep *string) *int64Uint16MapValue { + s := &int64Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4450,10 +5601,11 @@ func (v *int64Uint16MapValue) Set(val string) error { return nil } -func (v *int64Uint16MapValue) Get() interface{} { +func (v *int64Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4461,6 +5613,7 @@ func (v *int64Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4472,23 +5625,37 @@ func (v *int64Uint16MapValue) IsCumulative() bool { // -- uintUint16MapValue. type uintUint16MapValue struct { - value *map[uint]uint16 + value *map[uint]uint16 + separator string } -var ( - _ RepeatableFlag = (*uintUint16MapValue)(nil) - _ Value = (*uintUint16MapValue)(nil) - _ Getter = (*uintUint16MapValue)(nil) -) +var _ RepeatableFlag = (*uintUint16MapValue)(nil) +var _ Value = (*uintUint16MapValue)(nil) +var _ Getter = (*uintUint16MapValue)(nil) -func newUintUint16MapValue(m *map[uint]uint16) *uintUint16MapValue { - return &uintUint16MapValue{ +func newUintUint16MapValue(m *map[uint]uint16, sep *string) *uintUint16MapValue { + s := &uintUint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintUint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4520,10 +5687,11 @@ func (v *uintUint16MapValue) Set(val string) error { return nil } -func (v *uintUint16MapValue) Get() interface{} { +func (v *uintUint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4531,6 +5699,7 @@ func (v *uintUint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4542,23 +5711,37 @@ func (v *uintUint16MapValue) IsCumulative() bool { // -- uint8Uint16MapValue. type uint8Uint16MapValue struct { - value *map[uint8]uint16 + value *map[uint8]uint16 + separator string } -var ( - _ RepeatableFlag = (*uint8Uint16MapValue)(nil) - _ Value = (*uint8Uint16MapValue)(nil) - _ Getter = (*uint8Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Uint16MapValue)(nil) +var _ Value = (*uint8Uint16MapValue)(nil) +var _ Getter = (*uint8Uint16MapValue)(nil) -func newUint8Uint16MapValue(m *map[uint8]uint16) *uint8Uint16MapValue { - return &uint8Uint16MapValue{ +func newUint8Uint16MapValue(m *map[uint8]uint16, sep *string) *uint8Uint16MapValue { + s := &uint8Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4590,10 +5773,11 @@ func (v *uint8Uint16MapValue) Set(val string) error { return nil } -func (v *uint8Uint16MapValue) Get() interface{} { +func (v *uint8Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4601,6 +5785,7 @@ func (v *uint8Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4612,23 +5797,37 @@ func (v *uint8Uint16MapValue) IsCumulative() bool { // -- uint16Uint16MapValue. type uint16Uint16MapValue struct { - value *map[uint16]uint16 + value *map[uint16]uint16 + separator string } -var ( - _ RepeatableFlag = (*uint16Uint16MapValue)(nil) - _ Value = (*uint16Uint16MapValue)(nil) - _ Getter = (*uint16Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Uint16MapValue)(nil) +var _ Value = (*uint16Uint16MapValue)(nil) +var _ Getter = (*uint16Uint16MapValue)(nil) -func newUint16Uint16MapValue(m *map[uint16]uint16) *uint16Uint16MapValue { - return &uint16Uint16MapValue{ +func newUint16Uint16MapValue(m *map[uint16]uint16, sep *string) *uint16Uint16MapValue { + s := &uint16Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4660,10 +5859,11 @@ func (v *uint16Uint16MapValue) Set(val string) error { return nil } -func (v *uint16Uint16MapValue) Get() interface{} { +func (v *uint16Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4671,6 +5871,7 @@ func (v *uint16Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4682,23 +5883,37 @@ func (v *uint16Uint16MapValue) IsCumulative() bool { // -- uint32Uint16MapValue. type uint32Uint16MapValue struct { - value *map[uint32]uint16 + value *map[uint32]uint16 + separator string } -var ( - _ RepeatableFlag = (*uint32Uint16MapValue)(nil) - _ Value = (*uint32Uint16MapValue)(nil) - _ Getter = (*uint32Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Uint16MapValue)(nil) +var _ Value = (*uint32Uint16MapValue)(nil) +var _ Getter = (*uint32Uint16MapValue)(nil) -func newUint32Uint16MapValue(m *map[uint32]uint16) *uint32Uint16MapValue { - return &uint32Uint16MapValue{ +func newUint32Uint16MapValue(m *map[uint32]uint16, sep *string) *uint32Uint16MapValue { + s := &uint32Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4730,10 +5945,11 @@ func (v *uint32Uint16MapValue) Set(val string) error { return nil } -func (v *uint32Uint16MapValue) Get() interface{} { +func (v *uint32Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4741,6 +5957,7 @@ func (v *uint32Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4752,23 +5969,37 @@ func (v *uint32Uint16MapValue) IsCumulative() bool { // -- uint64Uint16MapValue. type uint64Uint16MapValue struct { - value *map[uint64]uint16 + value *map[uint64]uint16 + separator string } -var ( - _ RepeatableFlag = (*uint64Uint16MapValue)(nil) - _ Value = (*uint64Uint16MapValue)(nil) - _ Getter = (*uint64Uint16MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Uint16MapValue)(nil) +var _ Value = (*uint64Uint16MapValue)(nil) +var _ Getter = (*uint64Uint16MapValue)(nil) -func newUint64Uint16MapValue(m *map[uint64]uint16) *uint64Uint16MapValue { - return &uint64Uint16MapValue{ +func newUint64Uint16MapValue(m *map[uint64]uint16, sep *string) *uint64Uint16MapValue { + s := &uint64Uint16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Uint16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4800,10 +6031,11 @@ func (v *uint64Uint16MapValue) Set(val string) error { return nil } -func (v *uint64Uint16MapValue) Get() interface{} { +func (v *uint64Uint16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4811,6 +6043,7 @@ func (v *uint64Uint16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4825,35 +6058,42 @@ type uint32Value struct { value *uint32 } -var ( - _ Value = (*uint32Value)(nil) - _ Getter = (*uint32Value)(nil) -) +var _ Value = (*uint32Value)(nil) +var _ Getter = (*uint32Value)(nil) func newUint32Value(p *uint32) *uint32Value { return &uint32Value{value: p} } func (v *uint32Value) Set(s string) error { + parsed, err := strconv.ParseUint(s, 0, 32) if err == nil { + *v.value = (uint32)(parsed) + return nil } + return err + } -func (v *uint32Value) Get() interface{} { +func (v *uint32Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *uint32Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatUint(uint64(*v.value), 10) } + return "" } @@ -4862,24 +6102,38 @@ func (v *uint32Value) Type() string { return "uint32" } // -- uint32Slice Value type uint32SliceValue struct { - value *[]uint32 - changed bool + value *[]uint32 + changed bool + separator string } -var ( - _ RepeatableFlag = (*uint32SliceValue)(nil) - _ Value = (*uint32SliceValue)(nil) - _ Getter = (*uint32SliceValue)(nil) -) +var _ RepeatableFlag = (*uint32SliceValue)(nil) +var _ Value = (*uint32SliceValue)(nil) +var _ Getter = (*uint32SliceValue)(nil) -func newUint32SliceValue(slice *[]uint32) *uint32SliceValue { - return &uint32SliceValue{ +func newUint32SliceValue(slice *[]uint32, sep *string) *uint32SliceValue { + s := &uint32SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]uint32, len(ss)) for i, s := range ss { @@ -4887,7 +6141,9 @@ func (v *uint32SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (uint32)(parsed) + } if !v.changed { @@ -4896,24 +6152,29 @@ func (v *uint32SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *uint32SliceValue) Get() interface{} { +func (v *uint32SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]uint32)(nil) } func (v *uint32SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newUint32Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -4925,23 +6186,37 @@ func (v *uint32SliceValue) IsCumulative() bool { // -- stringUint32MapValue. type stringUint32MapValue struct { - value *map[string]uint32 + value *map[string]uint32 + separator string } -var ( - _ RepeatableFlag = (*stringUint32MapValue)(nil) - _ Value = (*stringUint32MapValue)(nil) - _ Getter = (*stringUint32MapValue)(nil) -) +var _ RepeatableFlag = (*stringUint32MapValue)(nil) +var _ Value = (*stringUint32MapValue)(nil) +var _ Getter = (*stringUint32MapValue)(nil) -func newStringUint32MapValue(m *map[string]uint32) *stringUint32MapValue { - return &stringUint32MapValue{ +func newStringUint32MapValue(m *map[string]uint32, sep *string) *stringUint32MapValue { + s := &stringUint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringUint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -4968,10 +6243,11 @@ func (v *stringUint32MapValue) Set(val string) error { return nil } -func (v *stringUint32MapValue) Get() interface{} { +func (v *stringUint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -4979,6 +6255,7 @@ func (v *stringUint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -4990,23 +6267,37 @@ func (v *stringUint32MapValue) IsCumulative() bool { // -- intUint32MapValue. type intUint32MapValue struct { - value *map[int]uint32 + value *map[int]uint32 + separator string } -var ( - _ RepeatableFlag = (*intUint32MapValue)(nil) - _ Value = (*intUint32MapValue)(nil) - _ Getter = (*intUint32MapValue)(nil) -) +var _ RepeatableFlag = (*intUint32MapValue)(nil) +var _ Value = (*intUint32MapValue)(nil) +var _ Getter = (*intUint32MapValue)(nil) -func newIntUint32MapValue(m *map[int]uint32) *intUint32MapValue { - return &intUint32MapValue{ +func newIntUint32MapValue(m *map[int]uint32, sep *string) *intUint32MapValue { + s := &intUint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intUint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5038,10 +6329,11 @@ func (v *intUint32MapValue) Set(val string) error { return nil } -func (v *intUint32MapValue) Get() interface{} { +func (v *intUint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5049,6 +6341,7 @@ func (v *intUint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5060,23 +6353,37 @@ func (v *intUint32MapValue) IsCumulative() bool { // -- int8Uint32MapValue. type int8Uint32MapValue struct { - value *map[int8]uint32 + value *map[int8]uint32 + separator string } -var ( - _ RepeatableFlag = (*int8Uint32MapValue)(nil) - _ Value = (*int8Uint32MapValue)(nil) - _ Getter = (*int8Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*int8Uint32MapValue)(nil) +var _ Value = (*int8Uint32MapValue)(nil) +var _ Getter = (*int8Uint32MapValue)(nil) -func newInt8Uint32MapValue(m *map[int8]uint32) *int8Uint32MapValue { - return &int8Uint32MapValue{ +func newInt8Uint32MapValue(m *map[int8]uint32, sep *string) *int8Uint32MapValue { + s := &int8Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5108,10 +6415,11 @@ func (v *int8Uint32MapValue) Set(val string) error { return nil } -func (v *int8Uint32MapValue) Get() interface{} { +func (v *int8Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5119,6 +6427,7 @@ func (v *int8Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5130,23 +6439,37 @@ func (v *int8Uint32MapValue) IsCumulative() bool { // -- int16Uint32MapValue. type int16Uint32MapValue struct { - value *map[int16]uint32 + value *map[int16]uint32 + separator string } -var ( - _ RepeatableFlag = (*int16Uint32MapValue)(nil) - _ Value = (*int16Uint32MapValue)(nil) - _ Getter = (*int16Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*int16Uint32MapValue)(nil) +var _ Value = (*int16Uint32MapValue)(nil) +var _ Getter = (*int16Uint32MapValue)(nil) -func newInt16Uint32MapValue(m *map[int16]uint32) *int16Uint32MapValue { - return &int16Uint32MapValue{ +func newInt16Uint32MapValue(m *map[int16]uint32, sep *string) *int16Uint32MapValue { + s := &int16Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5178,10 +6501,11 @@ func (v *int16Uint32MapValue) Set(val string) error { return nil } -func (v *int16Uint32MapValue) Get() interface{} { +func (v *int16Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5189,6 +6513,7 @@ func (v *int16Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5200,23 +6525,37 @@ func (v *int16Uint32MapValue) IsCumulative() bool { // -- int32Uint32MapValue. type int32Uint32MapValue struct { - value *map[int32]uint32 + value *map[int32]uint32 + separator string } -var ( - _ RepeatableFlag = (*int32Uint32MapValue)(nil) - _ Value = (*int32Uint32MapValue)(nil) - _ Getter = (*int32Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*int32Uint32MapValue)(nil) +var _ Value = (*int32Uint32MapValue)(nil) +var _ Getter = (*int32Uint32MapValue)(nil) -func newInt32Uint32MapValue(m *map[int32]uint32) *int32Uint32MapValue { - return &int32Uint32MapValue{ +func newInt32Uint32MapValue(m *map[int32]uint32, sep *string) *int32Uint32MapValue { + s := &int32Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5248,10 +6587,11 @@ func (v *int32Uint32MapValue) Set(val string) error { return nil } -func (v *int32Uint32MapValue) Get() interface{} { +func (v *int32Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5259,6 +6599,7 @@ func (v *int32Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5270,23 +6611,37 @@ func (v *int32Uint32MapValue) IsCumulative() bool { // -- int64Uint32MapValue. type int64Uint32MapValue struct { - value *map[int64]uint32 + value *map[int64]uint32 + separator string } -var ( - _ RepeatableFlag = (*int64Uint32MapValue)(nil) - _ Value = (*int64Uint32MapValue)(nil) - _ Getter = (*int64Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*int64Uint32MapValue)(nil) +var _ Value = (*int64Uint32MapValue)(nil) +var _ Getter = (*int64Uint32MapValue)(nil) -func newInt64Uint32MapValue(m *map[int64]uint32) *int64Uint32MapValue { - return &int64Uint32MapValue{ +func newInt64Uint32MapValue(m *map[int64]uint32, sep *string) *int64Uint32MapValue { + s := &int64Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5318,10 +6673,11 @@ func (v *int64Uint32MapValue) Set(val string) error { return nil } -func (v *int64Uint32MapValue) Get() interface{} { +func (v *int64Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5329,6 +6685,7 @@ func (v *int64Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5340,23 +6697,37 @@ func (v *int64Uint32MapValue) IsCumulative() bool { // -- uintUint32MapValue. type uintUint32MapValue struct { - value *map[uint]uint32 + value *map[uint]uint32 + separator string } -var ( - _ RepeatableFlag = (*uintUint32MapValue)(nil) - _ Value = (*uintUint32MapValue)(nil) - _ Getter = (*uintUint32MapValue)(nil) -) +var _ RepeatableFlag = (*uintUint32MapValue)(nil) +var _ Value = (*uintUint32MapValue)(nil) +var _ Getter = (*uintUint32MapValue)(nil) -func newUintUint32MapValue(m *map[uint]uint32) *uintUint32MapValue { - return &uintUint32MapValue{ +func newUintUint32MapValue(m *map[uint]uint32, sep *string) *uintUint32MapValue { + s := &uintUint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintUint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5388,10 +6759,11 @@ func (v *uintUint32MapValue) Set(val string) error { return nil } -func (v *uintUint32MapValue) Get() interface{} { +func (v *uintUint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5399,6 +6771,7 @@ func (v *uintUint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5410,23 +6783,37 @@ func (v *uintUint32MapValue) IsCumulative() bool { // -- uint8Uint32MapValue. type uint8Uint32MapValue struct { - value *map[uint8]uint32 + value *map[uint8]uint32 + separator string } -var ( - _ RepeatableFlag = (*uint8Uint32MapValue)(nil) - _ Value = (*uint8Uint32MapValue)(nil) - _ Getter = (*uint8Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Uint32MapValue)(nil) +var _ Value = (*uint8Uint32MapValue)(nil) +var _ Getter = (*uint8Uint32MapValue)(nil) -func newUint8Uint32MapValue(m *map[uint8]uint32) *uint8Uint32MapValue { - return &uint8Uint32MapValue{ +func newUint8Uint32MapValue(m *map[uint8]uint32, sep *string) *uint8Uint32MapValue { + s := &uint8Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5458,10 +6845,11 @@ func (v *uint8Uint32MapValue) Set(val string) error { return nil } -func (v *uint8Uint32MapValue) Get() interface{} { +func (v *uint8Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5469,6 +6857,7 @@ func (v *uint8Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5480,23 +6869,37 @@ func (v *uint8Uint32MapValue) IsCumulative() bool { // -- uint16Uint32MapValue. type uint16Uint32MapValue struct { - value *map[uint16]uint32 + value *map[uint16]uint32 + separator string } -var ( - _ RepeatableFlag = (*uint16Uint32MapValue)(nil) - _ Value = (*uint16Uint32MapValue)(nil) - _ Getter = (*uint16Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Uint32MapValue)(nil) +var _ Value = (*uint16Uint32MapValue)(nil) +var _ Getter = (*uint16Uint32MapValue)(nil) -func newUint16Uint32MapValue(m *map[uint16]uint32) *uint16Uint32MapValue { - return &uint16Uint32MapValue{ +func newUint16Uint32MapValue(m *map[uint16]uint32, sep *string) *uint16Uint32MapValue { + s := &uint16Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5528,10 +6931,11 @@ func (v *uint16Uint32MapValue) Set(val string) error { return nil } -func (v *uint16Uint32MapValue) Get() interface{} { +func (v *uint16Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5539,6 +6943,7 @@ func (v *uint16Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5550,23 +6955,37 @@ func (v *uint16Uint32MapValue) IsCumulative() bool { // -- uint32Uint32MapValue. type uint32Uint32MapValue struct { - value *map[uint32]uint32 + value *map[uint32]uint32 + separator string } -var ( - _ RepeatableFlag = (*uint32Uint32MapValue)(nil) - _ Value = (*uint32Uint32MapValue)(nil) - _ Getter = (*uint32Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Uint32MapValue)(nil) +var _ Value = (*uint32Uint32MapValue)(nil) +var _ Getter = (*uint32Uint32MapValue)(nil) -func newUint32Uint32MapValue(m *map[uint32]uint32) *uint32Uint32MapValue { - return &uint32Uint32MapValue{ +func newUint32Uint32MapValue(m *map[uint32]uint32, sep *string) *uint32Uint32MapValue { + s := &uint32Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5598,10 +7017,11 @@ func (v *uint32Uint32MapValue) Set(val string) error { return nil } -func (v *uint32Uint32MapValue) Get() interface{} { +func (v *uint32Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5609,6 +7029,7 @@ func (v *uint32Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5620,23 +7041,37 @@ func (v *uint32Uint32MapValue) IsCumulative() bool { // -- uint64Uint32MapValue. type uint64Uint32MapValue struct { - value *map[uint64]uint32 + value *map[uint64]uint32 + separator string } -var ( - _ RepeatableFlag = (*uint64Uint32MapValue)(nil) - _ Value = (*uint64Uint32MapValue)(nil) - _ Getter = (*uint64Uint32MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Uint32MapValue)(nil) +var _ Value = (*uint64Uint32MapValue)(nil) +var _ Getter = (*uint64Uint32MapValue)(nil) -func newUint64Uint32MapValue(m *map[uint64]uint32) *uint64Uint32MapValue { - return &uint64Uint32MapValue{ +func newUint64Uint32MapValue(m *map[uint64]uint32, sep *string) *uint64Uint32MapValue { + s := &uint64Uint32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Uint32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5668,10 +7103,11 @@ func (v *uint64Uint32MapValue) Set(val string) error { return nil } -func (v *uint64Uint32MapValue) Get() interface{} { +func (v *uint64Uint32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5679,6 +7115,7 @@ func (v *uint64Uint32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5693,35 +7130,42 @@ type uint64Value struct { value *uint64 } -var ( - _ Value = (*uint64Value)(nil) - _ Getter = (*uint64Value)(nil) -) +var _ Value = (*uint64Value)(nil) +var _ Getter = (*uint64Value)(nil) func newUint64Value(p *uint64) *uint64Value { return &uint64Value{value: p} } func (v *uint64Value) Set(s string) error { + parsed, err := strconv.ParseUint(s, 0, 64) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *uint64Value) Get() interface{} { +func (v *uint64Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *uint64Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatUint(*v.value, 10) } + return "" } @@ -5730,24 +7174,38 @@ func (v *uint64Value) Type() string { return "uint64" } // -- uint64Slice Value type uint64SliceValue struct { - value *[]uint64 - changed bool + value *[]uint64 + changed bool + separator string } -var ( - _ RepeatableFlag = (*uint64SliceValue)(nil) - _ Value = (*uint64SliceValue)(nil) - _ Getter = (*uint64SliceValue)(nil) -) +var _ RepeatableFlag = (*uint64SliceValue)(nil) +var _ Value = (*uint64SliceValue)(nil) +var _ Getter = (*uint64SliceValue)(nil) -func newUint64SliceValue(slice *[]uint64) *uint64SliceValue { - return &uint64SliceValue{ +func newUint64SliceValue(slice *[]uint64, sep *string) *uint64SliceValue { + s := &uint64SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]uint64, len(ss)) for i, s := range ss { @@ -5755,7 +7213,9 @@ func (v *uint64SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -5764,24 +7224,29 @@ func (v *uint64SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *uint64SliceValue) Get() interface{} { +func (v *uint64SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]uint64)(nil) } func (v *uint64SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newUint64Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -5793,23 +7258,37 @@ func (v *uint64SliceValue) IsCumulative() bool { // -- stringUint64MapValue. type stringUint64MapValue struct { - value *map[string]uint64 + value *map[string]uint64 + separator string } -var ( - _ RepeatableFlag = (*stringUint64MapValue)(nil) - _ Value = (*stringUint64MapValue)(nil) - _ Getter = (*stringUint64MapValue)(nil) -) +var _ RepeatableFlag = (*stringUint64MapValue)(nil) +var _ Value = (*stringUint64MapValue)(nil) +var _ Getter = (*stringUint64MapValue)(nil) -func newStringUint64MapValue(m *map[string]uint64) *stringUint64MapValue { - return &stringUint64MapValue{ +func newStringUint64MapValue(m *map[string]uint64, sep *string) *stringUint64MapValue { + s := &stringUint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringUint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5836,10 +7315,11 @@ func (v *stringUint64MapValue) Set(val string) error { return nil } -func (v *stringUint64MapValue) Get() interface{} { +func (v *stringUint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5847,6 +7327,7 @@ func (v *stringUint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5858,23 +7339,37 @@ func (v *stringUint64MapValue) IsCumulative() bool { // -- intUint64MapValue. type intUint64MapValue struct { - value *map[int]uint64 + value *map[int]uint64 + separator string } -var ( - _ RepeatableFlag = (*intUint64MapValue)(nil) - _ Value = (*intUint64MapValue)(nil) - _ Getter = (*intUint64MapValue)(nil) -) +var _ RepeatableFlag = (*intUint64MapValue)(nil) +var _ Value = (*intUint64MapValue)(nil) +var _ Getter = (*intUint64MapValue)(nil) -func newIntUint64MapValue(m *map[int]uint64) *intUint64MapValue { - return &intUint64MapValue{ +func newIntUint64MapValue(m *map[int]uint64, sep *string) *intUint64MapValue { + s := &intUint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intUint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5906,10 +7401,11 @@ func (v *intUint64MapValue) Set(val string) error { return nil } -func (v *intUint64MapValue) Get() interface{} { +func (v *intUint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5917,6 +7413,7 @@ func (v *intUint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5928,23 +7425,37 @@ func (v *intUint64MapValue) IsCumulative() bool { // -- int8Uint64MapValue. type int8Uint64MapValue struct { - value *map[int8]uint64 + value *map[int8]uint64 + separator string } -var ( - _ RepeatableFlag = (*int8Uint64MapValue)(nil) - _ Value = (*int8Uint64MapValue)(nil) - _ Getter = (*int8Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*int8Uint64MapValue)(nil) +var _ Value = (*int8Uint64MapValue)(nil) +var _ Getter = (*int8Uint64MapValue)(nil) -func newInt8Uint64MapValue(m *map[int8]uint64) *int8Uint64MapValue { - return &int8Uint64MapValue{ +func newInt8Uint64MapValue(m *map[int8]uint64, sep *string) *int8Uint64MapValue { + s := &int8Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -5976,10 +7487,11 @@ func (v *int8Uint64MapValue) Set(val string) error { return nil } -func (v *int8Uint64MapValue) Get() interface{} { +func (v *int8Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -5987,6 +7499,7 @@ func (v *int8Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -5998,23 +7511,37 @@ func (v *int8Uint64MapValue) IsCumulative() bool { // -- int16Uint64MapValue. type int16Uint64MapValue struct { - value *map[int16]uint64 + value *map[int16]uint64 + separator string } -var ( - _ RepeatableFlag = (*int16Uint64MapValue)(nil) - _ Value = (*int16Uint64MapValue)(nil) - _ Getter = (*int16Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*int16Uint64MapValue)(nil) +var _ Value = (*int16Uint64MapValue)(nil) +var _ Getter = (*int16Uint64MapValue)(nil) -func newInt16Uint64MapValue(m *map[int16]uint64) *int16Uint64MapValue { - return &int16Uint64MapValue{ +func newInt16Uint64MapValue(m *map[int16]uint64, sep *string) *int16Uint64MapValue { + s := &int16Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6046,10 +7573,11 @@ func (v *int16Uint64MapValue) Set(val string) error { return nil } -func (v *int16Uint64MapValue) Get() interface{} { +func (v *int16Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6057,6 +7585,7 @@ func (v *int16Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6068,23 +7597,37 @@ func (v *int16Uint64MapValue) IsCumulative() bool { // -- int32Uint64MapValue. type int32Uint64MapValue struct { - value *map[int32]uint64 + value *map[int32]uint64 + separator string } -var ( - _ RepeatableFlag = (*int32Uint64MapValue)(nil) - _ Value = (*int32Uint64MapValue)(nil) - _ Getter = (*int32Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*int32Uint64MapValue)(nil) +var _ Value = (*int32Uint64MapValue)(nil) +var _ Getter = (*int32Uint64MapValue)(nil) -func newInt32Uint64MapValue(m *map[int32]uint64) *int32Uint64MapValue { - return &int32Uint64MapValue{ +func newInt32Uint64MapValue(m *map[int32]uint64, sep *string) *int32Uint64MapValue { + s := &int32Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6116,10 +7659,11 @@ func (v *int32Uint64MapValue) Set(val string) error { return nil } -func (v *int32Uint64MapValue) Get() interface{} { +func (v *int32Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6127,6 +7671,7 @@ func (v *int32Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6138,23 +7683,37 @@ func (v *int32Uint64MapValue) IsCumulative() bool { // -- int64Uint64MapValue. type int64Uint64MapValue struct { - value *map[int64]uint64 + value *map[int64]uint64 + separator string } -var ( - _ RepeatableFlag = (*int64Uint64MapValue)(nil) - _ Value = (*int64Uint64MapValue)(nil) - _ Getter = (*int64Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*int64Uint64MapValue)(nil) +var _ Value = (*int64Uint64MapValue)(nil) +var _ Getter = (*int64Uint64MapValue)(nil) -func newInt64Uint64MapValue(m *map[int64]uint64) *int64Uint64MapValue { - return &int64Uint64MapValue{ +func newInt64Uint64MapValue(m *map[int64]uint64, sep *string) *int64Uint64MapValue { + s := &int64Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6186,10 +7745,11 @@ func (v *int64Uint64MapValue) Set(val string) error { return nil } -func (v *int64Uint64MapValue) Get() interface{} { +func (v *int64Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6197,6 +7757,7 @@ func (v *int64Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6208,23 +7769,37 @@ func (v *int64Uint64MapValue) IsCumulative() bool { // -- uintUint64MapValue. type uintUint64MapValue struct { - value *map[uint]uint64 + value *map[uint]uint64 + separator string } -var ( - _ RepeatableFlag = (*uintUint64MapValue)(nil) - _ Value = (*uintUint64MapValue)(nil) - _ Getter = (*uintUint64MapValue)(nil) -) +var _ RepeatableFlag = (*uintUint64MapValue)(nil) +var _ Value = (*uintUint64MapValue)(nil) +var _ Getter = (*uintUint64MapValue)(nil) -func newUintUint64MapValue(m *map[uint]uint64) *uintUint64MapValue { - return &uintUint64MapValue{ +func newUintUint64MapValue(m *map[uint]uint64, sep *string) *uintUint64MapValue { + s := &uintUint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintUint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6256,10 +7831,11 @@ func (v *uintUint64MapValue) Set(val string) error { return nil } -func (v *uintUint64MapValue) Get() interface{} { +func (v *uintUint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6267,6 +7843,7 @@ func (v *uintUint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6278,23 +7855,37 @@ func (v *uintUint64MapValue) IsCumulative() bool { // -- uint8Uint64MapValue. type uint8Uint64MapValue struct { - value *map[uint8]uint64 + value *map[uint8]uint64 + separator string } -var ( - _ RepeatableFlag = (*uint8Uint64MapValue)(nil) - _ Value = (*uint8Uint64MapValue)(nil) - _ Getter = (*uint8Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Uint64MapValue)(nil) +var _ Value = (*uint8Uint64MapValue)(nil) +var _ Getter = (*uint8Uint64MapValue)(nil) -func newUint8Uint64MapValue(m *map[uint8]uint64) *uint8Uint64MapValue { - return &uint8Uint64MapValue{ +func newUint8Uint64MapValue(m *map[uint8]uint64, sep *string) *uint8Uint64MapValue { + s := &uint8Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6326,10 +7917,11 @@ func (v *uint8Uint64MapValue) Set(val string) error { return nil } -func (v *uint8Uint64MapValue) Get() interface{} { +func (v *uint8Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6337,6 +7929,7 @@ func (v *uint8Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6348,23 +7941,37 @@ func (v *uint8Uint64MapValue) IsCumulative() bool { // -- uint16Uint64MapValue. type uint16Uint64MapValue struct { - value *map[uint16]uint64 + value *map[uint16]uint64 + separator string } -var ( - _ RepeatableFlag = (*uint16Uint64MapValue)(nil) - _ Value = (*uint16Uint64MapValue)(nil) - _ Getter = (*uint16Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Uint64MapValue)(nil) +var _ Value = (*uint16Uint64MapValue)(nil) +var _ Getter = (*uint16Uint64MapValue)(nil) -func newUint16Uint64MapValue(m *map[uint16]uint64) *uint16Uint64MapValue { - return &uint16Uint64MapValue{ +func newUint16Uint64MapValue(m *map[uint16]uint64, sep *string) *uint16Uint64MapValue { + s := &uint16Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6396,10 +8003,11 @@ func (v *uint16Uint64MapValue) Set(val string) error { return nil } -func (v *uint16Uint64MapValue) Get() interface{} { +func (v *uint16Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6407,6 +8015,7 @@ func (v *uint16Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6418,23 +8027,37 @@ func (v *uint16Uint64MapValue) IsCumulative() bool { // -- uint32Uint64MapValue. type uint32Uint64MapValue struct { - value *map[uint32]uint64 + value *map[uint32]uint64 + separator string } -var ( - _ RepeatableFlag = (*uint32Uint64MapValue)(nil) - _ Value = (*uint32Uint64MapValue)(nil) - _ Getter = (*uint32Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Uint64MapValue)(nil) +var _ Value = (*uint32Uint64MapValue)(nil) +var _ Getter = (*uint32Uint64MapValue)(nil) -func newUint32Uint64MapValue(m *map[uint32]uint64) *uint32Uint64MapValue { - return &uint32Uint64MapValue{ +func newUint32Uint64MapValue(m *map[uint32]uint64, sep *string) *uint32Uint64MapValue { + s := &uint32Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6466,10 +8089,11 @@ func (v *uint32Uint64MapValue) Set(val string) error { return nil } -func (v *uint32Uint64MapValue) Get() interface{} { +func (v *uint32Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6477,6 +8101,7 @@ func (v *uint32Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6488,23 +8113,37 @@ func (v *uint32Uint64MapValue) IsCumulative() bool { // -- uint64Uint64MapValue. type uint64Uint64MapValue struct { - value *map[uint64]uint64 + value *map[uint64]uint64 + separator string } -var ( - _ RepeatableFlag = (*uint64Uint64MapValue)(nil) - _ Value = (*uint64Uint64MapValue)(nil) - _ Getter = (*uint64Uint64MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Uint64MapValue)(nil) +var _ Value = (*uint64Uint64MapValue)(nil) +var _ Getter = (*uint64Uint64MapValue)(nil) -func newUint64Uint64MapValue(m *map[uint64]uint64) *uint64Uint64MapValue { - return &uint64Uint64MapValue{ +func newUint64Uint64MapValue(m *map[uint64]uint64, sep *string) *uint64Uint64MapValue { + s := &uint64Uint64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Uint64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6536,10 +8175,11 @@ func (v *uint64Uint64MapValue) Set(val string) error { return nil } -func (v *uint64Uint64MapValue) Get() interface{} { +func (v *uint64Uint64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6547,6 +8187,7 @@ func (v *uint64Uint64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6561,35 +8202,42 @@ type intValue struct { value *int } -var ( - _ Value = (*intValue)(nil) - _ Getter = (*intValue)(nil) -) +var _ Value = (*intValue)(nil) +var _ Getter = (*intValue)(nil) func newIntValue(p *int) *intValue { return &intValue{value: p} } func (v *intValue) Set(s string) error { + parsed, err := strconv.ParseInt(s, 0, 64) if err == nil { + *v.value = (int)(parsed) + return nil } + return err + } -func (v *intValue) Get() interface{} { +func (v *intValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *intValue) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.Itoa(*v.value) } + return "" } @@ -6598,24 +8246,38 @@ func (v *intValue) Type() string { return "int" } // -- intSlice Value type intSliceValue struct { - value *[]int - changed bool + value *[]int + changed bool + separator string } -var ( - _ RepeatableFlag = (*intSliceValue)(nil) - _ Value = (*intSliceValue)(nil) - _ Getter = (*intSliceValue)(nil) -) +var _ RepeatableFlag = (*intSliceValue)(nil) +var _ Value = (*intSliceValue)(nil) +var _ Getter = (*intSliceValue)(nil) -func newIntSliceValue(slice *[]int) *intSliceValue { - return &intSliceValue{ +func newIntSliceValue(slice *[]int, sep *string) *intSliceValue { + s := &intSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]int, len(ss)) for i, s := range ss { @@ -6623,7 +8285,9 @@ func (v *intSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (int)(parsed) + } if !v.changed { @@ -6632,24 +8296,29 @@ func (v *intSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *intSliceValue) Get() interface{} { +func (v *intSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]int)(nil) } func (v *intSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newIntValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -6661,23 +8330,37 @@ func (v *intSliceValue) IsCumulative() bool { // -- stringIntMapValue. type stringIntMapValue struct { - value *map[string]int + value *map[string]int + separator string } -var ( - _ RepeatableFlag = (*stringIntMapValue)(nil) - _ Value = (*stringIntMapValue)(nil) - _ Getter = (*stringIntMapValue)(nil) -) +var _ RepeatableFlag = (*stringIntMapValue)(nil) +var _ Value = (*stringIntMapValue)(nil) +var _ Getter = (*stringIntMapValue)(nil) -func newStringIntMapValue(m *map[string]int) *stringIntMapValue { - return &stringIntMapValue{ +func newStringIntMapValue(m *map[string]int, sep *string) *stringIntMapValue { + s := &stringIntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringIntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6704,10 +8387,11 @@ func (v *stringIntMapValue) Set(val string) error { return nil } -func (v *stringIntMapValue) Get() interface{} { +func (v *stringIntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6715,6 +8399,7 @@ func (v *stringIntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6726,23 +8411,37 @@ func (v *stringIntMapValue) IsCumulative() bool { // -- intIntMapValue. type intIntMapValue struct { - value *map[int]int + value *map[int]int + separator string } -var ( - _ RepeatableFlag = (*intIntMapValue)(nil) - _ Value = (*intIntMapValue)(nil) - _ Getter = (*intIntMapValue)(nil) -) +var _ RepeatableFlag = (*intIntMapValue)(nil) +var _ Value = (*intIntMapValue)(nil) +var _ Getter = (*intIntMapValue)(nil) -func newIntIntMapValue(m *map[int]int) *intIntMapValue { - return &intIntMapValue{ +func newIntIntMapValue(m *map[int]int, sep *string) *intIntMapValue { + s := &intIntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intIntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6774,10 +8473,11 @@ func (v *intIntMapValue) Set(val string) error { return nil } -func (v *intIntMapValue) Get() interface{} { +func (v *intIntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6785,6 +8485,7 @@ func (v *intIntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6796,23 +8497,37 @@ func (v *intIntMapValue) IsCumulative() bool { // -- int8IntMapValue. type int8IntMapValue struct { - value *map[int8]int + value *map[int8]int + separator string } -var ( - _ RepeatableFlag = (*int8IntMapValue)(nil) - _ Value = (*int8IntMapValue)(nil) - _ Getter = (*int8IntMapValue)(nil) -) +var _ RepeatableFlag = (*int8IntMapValue)(nil) +var _ Value = (*int8IntMapValue)(nil) +var _ Getter = (*int8IntMapValue)(nil) -func newInt8IntMapValue(m *map[int8]int) *int8IntMapValue { - return &int8IntMapValue{ +func newInt8IntMapValue(m *map[int8]int, sep *string) *int8IntMapValue { + s := &int8IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6844,10 +8559,11 @@ func (v *int8IntMapValue) Set(val string) error { return nil } -func (v *int8IntMapValue) Get() interface{} { +func (v *int8IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6855,6 +8571,7 @@ func (v *int8IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6866,23 +8583,37 @@ func (v *int8IntMapValue) IsCumulative() bool { // -- int16IntMapValue. type int16IntMapValue struct { - value *map[int16]int + value *map[int16]int + separator string } -var ( - _ RepeatableFlag = (*int16IntMapValue)(nil) - _ Value = (*int16IntMapValue)(nil) - _ Getter = (*int16IntMapValue)(nil) -) +var _ RepeatableFlag = (*int16IntMapValue)(nil) +var _ Value = (*int16IntMapValue)(nil) +var _ Getter = (*int16IntMapValue)(nil) -func newInt16IntMapValue(m *map[int16]int) *int16IntMapValue { - return &int16IntMapValue{ +func newInt16IntMapValue(m *map[int16]int, sep *string) *int16IntMapValue { + s := &int16IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6914,10 +8645,11 @@ func (v *int16IntMapValue) Set(val string) error { return nil } -func (v *int16IntMapValue) Get() interface{} { +func (v *int16IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6925,6 +8657,7 @@ func (v *int16IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -6936,23 +8669,37 @@ func (v *int16IntMapValue) IsCumulative() bool { // -- int32IntMapValue. type int32IntMapValue struct { - value *map[int32]int + value *map[int32]int + separator string } -var ( - _ RepeatableFlag = (*int32IntMapValue)(nil) - _ Value = (*int32IntMapValue)(nil) - _ Getter = (*int32IntMapValue)(nil) -) +var _ RepeatableFlag = (*int32IntMapValue)(nil) +var _ Value = (*int32IntMapValue)(nil) +var _ Getter = (*int32IntMapValue)(nil) -func newInt32IntMapValue(m *map[int32]int) *int32IntMapValue { - return &int32IntMapValue{ +func newInt32IntMapValue(m *map[int32]int, sep *string) *int32IntMapValue { + s := &int32IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -6984,10 +8731,11 @@ func (v *int32IntMapValue) Set(val string) error { return nil } -func (v *int32IntMapValue) Get() interface{} { +func (v *int32IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -6995,6 +8743,7 @@ func (v *int32IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7006,23 +8755,37 @@ func (v *int32IntMapValue) IsCumulative() bool { // -- int64IntMapValue. type int64IntMapValue struct { - value *map[int64]int + value *map[int64]int + separator string } -var ( - _ RepeatableFlag = (*int64IntMapValue)(nil) - _ Value = (*int64IntMapValue)(nil) - _ Getter = (*int64IntMapValue)(nil) -) +var _ RepeatableFlag = (*int64IntMapValue)(nil) +var _ Value = (*int64IntMapValue)(nil) +var _ Getter = (*int64IntMapValue)(nil) -func newInt64IntMapValue(m *map[int64]int) *int64IntMapValue { - return &int64IntMapValue{ +func newInt64IntMapValue(m *map[int64]int, sep *string) *int64IntMapValue { + s := &int64IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7054,10 +8817,11 @@ func (v *int64IntMapValue) Set(val string) error { return nil } -func (v *int64IntMapValue) Get() interface{} { +func (v *int64IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7065,6 +8829,7 @@ func (v *int64IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7076,23 +8841,37 @@ func (v *int64IntMapValue) IsCumulative() bool { // -- uintIntMapValue. type uintIntMapValue struct { - value *map[uint]int + value *map[uint]int + separator string } -var ( - _ RepeatableFlag = (*uintIntMapValue)(nil) - _ Value = (*uintIntMapValue)(nil) - _ Getter = (*uintIntMapValue)(nil) -) +var _ RepeatableFlag = (*uintIntMapValue)(nil) +var _ Value = (*uintIntMapValue)(nil) +var _ Getter = (*uintIntMapValue)(nil) -func newUintIntMapValue(m *map[uint]int) *uintIntMapValue { - return &uintIntMapValue{ +func newUintIntMapValue(m *map[uint]int, sep *string) *uintIntMapValue { + s := &uintIntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintIntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7124,10 +8903,11 @@ func (v *uintIntMapValue) Set(val string) error { return nil } -func (v *uintIntMapValue) Get() interface{} { +func (v *uintIntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7135,6 +8915,7 @@ func (v *uintIntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7146,23 +8927,37 @@ func (v *uintIntMapValue) IsCumulative() bool { // -- uint8IntMapValue. type uint8IntMapValue struct { - value *map[uint8]int + value *map[uint8]int + separator string } -var ( - _ RepeatableFlag = (*uint8IntMapValue)(nil) - _ Value = (*uint8IntMapValue)(nil) - _ Getter = (*uint8IntMapValue)(nil) -) +var _ RepeatableFlag = (*uint8IntMapValue)(nil) +var _ Value = (*uint8IntMapValue)(nil) +var _ Getter = (*uint8IntMapValue)(nil) -func newUint8IntMapValue(m *map[uint8]int) *uint8IntMapValue { - return &uint8IntMapValue{ +func newUint8IntMapValue(m *map[uint8]int, sep *string) *uint8IntMapValue { + s := &uint8IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7194,10 +8989,11 @@ func (v *uint8IntMapValue) Set(val string) error { return nil } -func (v *uint8IntMapValue) Get() interface{} { +func (v *uint8IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7205,6 +9001,7 @@ func (v *uint8IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7216,23 +9013,37 @@ func (v *uint8IntMapValue) IsCumulative() bool { // -- uint16IntMapValue. type uint16IntMapValue struct { - value *map[uint16]int + value *map[uint16]int + separator string } -var ( - _ RepeatableFlag = (*uint16IntMapValue)(nil) - _ Value = (*uint16IntMapValue)(nil) - _ Getter = (*uint16IntMapValue)(nil) -) +var _ RepeatableFlag = (*uint16IntMapValue)(nil) +var _ Value = (*uint16IntMapValue)(nil) +var _ Getter = (*uint16IntMapValue)(nil) -func newUint16IntMapValue(m *map[uint16]int) *uint16IntMapValue { - return &uint16IntMapValue{ +func newUint16IntMapValue(m *map[uint16]int, sep *string) *uint16IntMapValue { + s := &uint16IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7264,10 +9075,11 @@ func (v *uint16IntMapValue) Set(val string) error { return nil } -func (v *uint16IntMapValue) Get() interface{} { +func (v *uint16IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7275,6 +9087,7 @@ func (v *uint16IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7286,23 +9099,37 @@ func (v *uint16IntMapValue) IsCumulative() bool { // -- uint32IntMapValue. type uint32IntMapValue struct { - value *map[uint32]int + value *map[uint32]int + separator string } -var ( - _ RepeatableFlag = (*uint32IntMapValue)(nil) - _ Value = (*uint32IntMapValue)(nil) - _ Getter = (*uint32IntMapValue)(nil) -) +var _ RepeatableFlag = (*uint32IntMapValue)(nil) +var _ Value = (*uint32IntMapValue)(nil) +var _ Getter = (*uint32IntMapValue)(nil) -func newUint32IntMapValue(m *map[uint32]int) *uint32IntMapValue { - return &uint32IntMapValue{ +func newUint32IntMapValue(m *map[uint32]int, sep *string) *uint32IntMapValue { + s := &uint32IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7334,10 +9161,11 @@ func (v *uint32IntMapValue) Set(val string) error { return nil } -func (v *uint32IntMapValue) Get() interface{} { +func (v *uint32IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7345,6 +9173,7 @@ func (v *uint32IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7356,23 +9185,37 @@ func (v *uint32IntMapValue) IsCumulative() bool { // -- uint64IntMapValue. type uint64IntMapValue struct { - value *map[uint64]int + value *map[uint64]int + separator string } -var ( - _ RepeatableFlag = (*uint64IntMapValue)(nil) - _ Value = (*uint64IntMapValue)(nil) - _ Getter = (*uint64IntMapValue)(nil) -) +var _ RepeatableFlag = (*uint64IntMapValue)(nil) +var _ Value = (*uint64IntMapValue)(nil) +var _ Getter = (*uint64IntMapValue)(nil) -func newUint64IntMapValue(m *map[uint64]int) *uint64IntMapValue { - return &uint64IntMapValue{ +func newUint64IntMapValue(m *map[uint64]int, sep *string) *uint64IntMapValue { + s := &uint64IntMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64IntMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7404,10 +9247,11 @@ func (v *uint64IntMapValue) Set(val string) error { return nil } -func (v *uint64IntMapValue) Get() interface{} { +func (v *uint64IntMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7415,6 +9259,7 @@ func (v *uint64IntMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7429,35 +9274,42 @@ type int8Value struct { value *int8 } -var ( - _ Value = (*int8Value)(nil) - _ Getter = (*int8Value)(nil) -) +var _ Value = (*int8Value)(nil) +var _ Getter = (*int8Value)(nil) func newInt8Value(p *int8) *int8Value { return &int8Value{value: p} } func (v *int8Value) Set(s string) error { + parsed, err := strconv.ParseInt(s, 0, 8) if err == nil { + *v.value = (int8)(parsed) + return nil } + return err + } -func (v *int8Value) Get() interface{} { +func (v *int8Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *int8Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.Itoa(int(*v.value)) } + return "" } @@ -7466,24 +9318,38 @@ func (v *int8Value) Type() string { return "int8" } // -- int8Slice Value type int8SliceValue struct { - value *[]int8 - changed bool + value *[]int8 + changed bool + separator string } -var ( - _ RepeatableFlag = (*int8SliceValue)(nil) - _ Value = (*int8SliceValue)(nil) - _ Getter = (*int8SliceValue)(nil) -) +var _ RepeatableFlag = (*int8SliceValue)(nil) +var _ Value = (*int8SliceValue)(nil) +var _ Getter = (*int8SliceValue)(nil) -func newInt8SliceValue(slice *[]int8) *int8SliceValue { - return &int8SliceValue{ +func newInt8SliceValue(slice *[]int8, sep *string) *int8SliceValue { + s := &int8SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]int8, len(ss)) for i, s := range ss { @@ -7491,7 +9357,9 @@ func (v *int8SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (int8)(parsed) + } if !v.changed { @@ -7500,24 +9368,29 @@ func (v *int8SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *int8SliceValue) Get() interface{} { +func (v *int8SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]int8)(nil) } func (v *int8SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newInt8Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -7529,23 +9402,37 @@ func (v *int8SliceValue) IsCumulative() bool { // -- stringInt8MapValue. type stringInt8MapValue struct { - value *map[string]int8 + value *map[string]int8 + separator string } -var ( - _ RepeatableFlag = (*stringInt8MapValue)(nil) - _ Value = (*stringInt8MapValue)(nil) - _ Getter = (*stringInt8MapValue)(nil) -) +var _ RepeatableFlag = (*stringInt8MapValue)(nil) +var _ Value = (*stringInt8MapValue)(nil) +var _ Getter = (*stringInt8MapValue)(nil) -func newStringInt8MapValue(m *map[string]int8) *stringInt8MapValue { - return &stringInt8MapValue{ +func newStringInt8MapValue(m *map[string]int8, sep *string) *stringInt8MapValue { + s := &stringInt8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringInt8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7572,10 +9459,11 @@ func (v *stringInt8MapValue) Set(val string) error { return nil } -func (v *stringInt8MapValue) Get() interface{} { +func (v *stringInt8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7583,6 +9471,7 @@ func (v *stringInt8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7594,23 +9483,37 @@ func (v *stringInt8MapValue) IsCumulative() bool { // -- intInt8MapValue. type intInt8MapValue struct { - value *map[int]int8 + value *map[int]int8 + separator string } -var ( - _ RepeatableFlag = (*intInt8MapValue)(nil) - _ Value = (*intInt8MapValue)(nil) - _ Getter = (*intInt8MapValue)(nil) -) +var _ RepeatableFlag = (*intInt8MapValue)(nil) +var _ Value = (*intInt8MapValue)(nil) +var _ Getter = (*intInt8MapValue)(nil) -func newIntInt8MapValue(m *map[int]int8) *intInt8MapValue { - return &intInt8MapValue{ +func newIntInt8MapValue(m *map[int]int8, sep *string) *intInt8MapValue { + s := &intInt8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intInt8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7642,10 +9545,11 @@ func (v *intInt8MapValue) Set(val string) error { return nil } -func (v *intInt8MapValue) Get() interface{} { +func (v *intInt8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7653,6 +9557,7 @@ func (v *intInt8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7664,23 +9569,37 @@ func (v *intInt8MapValue) IsCumulative() bool { // -- int8Int8MapValue. type int8Int8MapValue struct { - value *map[int8]int8 + value *map[int8]int8 + separator string } -var ( - _ RepeatableFlag = (*int8Int8MapValue)(nil) - _ Value = (*int8Int8MapValue)(nil) - _ Getter = (*int8Int8MapValue)(nil) -) +var _ RepeatableFlag = (*int8Int8MapValue)(nil) +var _ Value = (*int8Int8MapValue)(nil) +var _ Getter = (*int8Int8MapValue)(nil) -func newInt8Int8MapValue(m *map[int8]int8) *int8Int8MapValue { - return &int8Int8MapValue{ +func newInt8Int8MapValue(m *map[int8]int8, sep *string) *int8Int8MapValue { + s := &int8Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7712,10 +9631,11 @@ func (v *int8Int8MapValue) Set(val string) error { return nil } -func (v *int8Int8MapValue) Get() interface{} { +func (v *int8Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7723,6 +9643,7 @@ func (v *int8Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7734,23 +9655,37 @@ func (v *int8Int8MapValue) IsCumulative() bool { // -- int16Int8MapValue. type int16Int8MapValue struct { - value *map[int16]int8 + value *map[int16]int8 + separator string } -var ( - _ RepeatableFlag = (*int16Int8MapValue)(nil) - _ Value = (*int16Int8MapValue)(nil) - _ Getter = (*int16Int8MapValue)(nil) -) +var _ RepeatableFlag = (*int16Int8MapValue)(nil) +var _ Value = (*int16Int8MapValue)(nil) +var _ Getter = (*int16Int8MapValue)(nil) -func newInt16Int8MapValue(m *map[int16]int8) *int16Int8MapValue { - return &int16Int8MapValue{ +func newInt16Int8MapValue(m *map[int16]int8, sep *string) *int16Int8MapValue { + s := &int16Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7782,10 +9717,11 @@ func (v *int16Int8MapValue) Set(val string) error { return nil } -func (v *int16Int8MapValue) Get() interface{} { +func (v *int16Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7793,6 +9729,7 @@ func (v *int16Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7804,23 +9741,37 @@ func (v *int16Int8MapValue) IsCumulative() bool { // -- int32Int8MapValue. type int32Int8MapValue struct { - value *map[int32]int8 + value *map[int32]int8 + separator string } -var ( - _ RepeatableFlag = (*int32Int8MapValue)(nil) - _ Value = (*int32Int8MapValue)(nil) - _ Getter = (*int32Int8MapValue)(nil) -) +var _ RepeatableFlag = (*int32Int8MapValue)(nil) +var _ Value = (*int32Int8MapValue)(nil) +var _ Getter = (*int32Int8MapValue)(nil) -func newInt32Int8MapValue(m *map[int32]int8) *int32Int8MapValue { - return &int32Int8MapValue{ +func newInt32Int8MapValue(m *map[int32]int8, sep *string) *int32Int8MapValue { + s := &int32Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7852,10 +9803,11 @@ func (v *int32Int8MapValue) Set(val string) error { return nil } -func (v *int32Int8MapValue) Get() interface{} { +func (v *int32Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7863,6 +9815,7 @@ func (v *int32Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7874,23 +9827,37 @@ func (v *int32Int8MapValue) IsCumulative() bool { // -- int64Int8MapValue. type int64Int8MapValue struct { - value *map[int64]int8 + value *map[int64]int8 + separator string } -var ( - _ RepeatableFlag = (*int64Int8MapValue)(nil) - _ Value = (*int64Int8MapValue)(nil) - _ Getter = (*int64Int8MapValue)(nil) -) +var _ RepeatableFlag = (*int64Int8MapValue)(nil) +var _ Value = (*int64Int8MapValue)(nil) +var _ Getter = (*int64Int8MapValue)(nil) -func newInt64Int8MapValue(m *map[int64]int8) *int64Int8MapValue { - return &int64Int8MapValue{ +func newInt64Int8MapValue(m *map[int64]int8, sep *string) *int64Int8MapValue { + s := &int64Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7922,10 +9889,11 @@ func (v *int64Int8MapValue) Set(val string) error { return nil } -func (v *int64Int8MapValue) Get() interface{} { +func (v *int64Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -7933,6 +9901,7 @@ func (v *int64Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -7944,23 +9913,37 @@ func (v *int64Int8MapValue) IsCumulative() bool { // -- uintInt8MapValue. type uintInt8MapValue struct { - value *map[uint]int8 + value *map[uint]int8 + separator string } -var ( - _ RepeatableFlag = (*uintInt8MapValue)(nil) - _ Value = (*uintInt8MapValue)(nil) - _ Getter = (*uintInt8MapValue)(nil) -) +var _ RepeatableFlag = (*uintInt8MapValue)(nil) +var _ Value = (*uintInt8MapValue)(nil) +var _ Getter = (*uintInt8MapValue)(nil) -func newUintInt8MapValue(m *map[uint]int8) *uintInt8MapValue { - return &uintInt8MapValue{ +func newUintInt8MapValue(m *map[uint]int8, sep *string) *uintInt8MapValue { + s := &uintInt8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintInt8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -7992,10 +9975,11 @@ func (v *uintInt8MapValue) Set(val string) error { return nil } -func (v *uintInt8MapValue) Get() interface{} { +func (v *uintInt8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8003,6 +9987,7 @@ func (v *uintInt8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8014,23 +9999,37 @@ func (v *uintInt8MapValue) IsCumulative() bool { // -- uint8Int8MapValue. type uint8Int8MapValue struct { - value *map[uint8]int8 + value *map[uint8]int8 + separator string } -var ( - _ RepeatableFlag = (*uint8Int8MapValue)(nil) - _ Value = (*uint8Int8MapValue)(nil) - _ Getter = (*uint8Int8MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Int8MapValue)(nil) +var _ Value = (*uint8Int8MapValue)(nil) +var _ Getter = (*uint8Int8MapValue)(nil) -func newUint8Int8MapValue(m *map[uint8]int8) *uint8Int8MapValue { - return &uint8Int8MapValue{ +func newUint8Int8MapValue(m *map[uint8]int8, sep *string) *uint8Int8MapValue { + s := &uint8Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8062,10 +10061,11 @@ func (v *uint8Int8MapValue) Set(val string) error { return nil } -func (v *uint8Int8MapValue) Get() interface{} { +func (v *uint8Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8073,6 +10073,7 @@ func (v *uint8Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8084,23 +10085,37 @@ func (v *uint8Int8MapValue) IsCumulative() bool { // -- uint16Int8MapValue. type uint16Int8MapValue struct { - value *map[uint16]int8 + value *map[uint16]int8 + separator string } -var ( - _ RepeatableFlag = (*uint16Int8MapValue)(nil) - _ Value = (*uint16Int8MapValue)(nil) - _ Getter = (*uint16Int8MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Int8MapValue)(nil) +var _ Value = (*uint16Int8MapValue)(nil) +var _ Getter = (*uint16Int8MapValue)(nil) -func newUint16Int8MapValue(m *map[uint16]int8) *uint16Int8MapValue { - return &uint16Int8MapValue{ +func newUint16Int8MapValue(m *map[uint16]int8, sep *string) *uint16Int8MapValue { + s := &uint16Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8132,10 +10147,11 @@ func (v *uint16Int8MapValue) Set(val string) error { return nil } -func (v *uint16Int8MapValue) Get() interface{} { +func (v *uint16Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8143,6 +10159,7 @@ func (v *uint16Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8154,23 +10171,37 @@ func (v *uint16Int8MapValue) IsCumulative() bool { // -- uint32Int8MapValue. type uint32Int8MapValue struct { - value *map[uint32]int8 + value *map[uint32]int8 + separator string } -var ( - _ RepeatableFlag = (*uint32Int8MapValue)(nil) - _ Value = (*uint32Int8MapValue)(nil) - _ Getter = (*uint32Int8MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Int8MapValue)(nil) +var _ Value = (*uint32Int8MapValue)(nil) +var _ Getter = (*uint32Int8MapValue)(nil) -func newUint32Int8MapValue(m *map[uint32]int8) *uint32Int8MapValue { - return &uint32Int8MapValue{ +func newUint32Int8MapValue(m *map[uint32]int8, sep *string) *uint32Int8MapValue { + s := &uint32Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8202,10 +10233,11 @@ func (v *uint32Int8MapValue) Set(val string) error { return nil } -func (v *uint32Int8MapValue) Get() interface{} { +func (v *uint32Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8213,6 +10245,7 @@ func (v *uint32Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8224,23 +10257,37 @@ func (v *uint32Int8MapValue) IsCumulative() bool { // -- uint64Int8MapValue. type uint64Int8MapValue struct { - value *map[uint64]int8 + value *map[uint64]int8 + separator string } -var ( - _ RepeatableFlag = (*uint64Int8MapValue)(nil) - _ Value = (*uint64Int8MapValue)(nil) - _ Getter = (*uint64Int8MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Int8MapValue)(nil) +var _ Value = (*uint64Int8MapValue)(nil) +var _ Getter = (*uint64Int8MapValue)(nil) -func newUint64Int8MapValue(m *map[uint64]int8) *uint64Int8MapValue { - return &uint64Int8MapValue{ +func newUint64Int8MapValue(m *map[uint64]int8, sep *string) *uint64Int8MapValue { + s := &uint64Int8MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Int8MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8272,10 +10319,11 @@ func (v *uint64Int8MapValue) Set(val string) error { return nil } -func (v *uint64Int8MapValue) Get() interface{} { +func (v *uint64Int8MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8283,6 +10331,7 @@ func (v *uint64Int8MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8297,35 +10346,42 @@ type int16Value struct { value *int16 } -var ( - _ Value = (*int16Value)(nil) - _ Getter = (*int16Value)(nil) -) +var _ Value = (*int16Value)(nil) +var _ Getter = (*int16Value)(nil) func newInt16Value(p *int16) *int16Value { return &int16Value{value: p} } func (v *int16Value) Set(s string) error { + parsed, err := strconv.ParseInt(s, 0, 16) if err == nil { + *v.value = (int16)(parsed) + return nil } + return err + } -func (v *int16Value) Get() interface{} { +func (v *int16Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *int16Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.Itoa(int(*v.value)) } + return "" } @@ -8334,24 +10390,38 @@ func (v *int16Value) Type() string { return "int16" } // -- int16Slice Value type int16SliceValue struct { - value *[]int16 - changed bool + value *[]int16 + changed bool + separator string } -var ( - _ RepeatableFlag = (*int16SliceValue)(nil) - _ Value = (*int16SliceValue)(nil) - _ Getter = (*int16SliceValue)(nil) -) +var _ RepeatableFlag = (*int16SliceValue)(nil) +var _ Value = (*int16SliceValue)(nil) +var _ Getter = (*int16SliceValue)(nil) -func newInt16SliceValue(slice *[]int16) *int16SliceValue { - return &int16SliceValue{ +func newInt16SliceValue(slice *[]int16, sep *string) *int16SliceValue { + s := &int16SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]int16, len(ss)) for i, s := range ss { @@ -8359,7 +10429,9 @@ func (v *int16SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (int16)(parsed) + } if !v.changed { @@ -8368,24 +10440,29 @@ func (v *int16SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *int16SliceValue) Get() interface{} { +func (v *int16SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]int16)(nil) } func (v *int16SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newInt16Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -8397,23 +10474,37 @@ func (v *int16SliceValue) IsCumulative() bool { // -- stringInt16MapValue. type stringInt16MapValue struct { - value *map[string]int16 + value *map[string]int16 + separator string } -var ( - _ RepeatableFlag = (*stringInt16MapValue)(nil) - _ Value = (*stringInt16MapValue)(nil) - _ Getter = (*stringInt16MapValue)(nil) -) +var _ RepeatableFlag = (*stringInt16MapValue)(nil) +var _ Value = (*stringInt16MapValue)(nil) +var _ Getter = (*stringInt16MapValue)(nil) -func newStringInt16MapValue(m *map[string]int16) *stringInt16MapValue { - return &stringInt16MapValue{ +func newStringInt16MapValue(m *map[string]int16, sep *string) *stringInt16MapValue { + s := &stringInt16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringInt16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8440,10 +10531,11 @@ func (v *stringInt16MapValue) Set(val string) error { return nil } -func (v *stringInt16MapValue) Get() interface{} { +func (v *stringInt16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8451,6 +10543,7 @@ func (v *stringInt16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8462,23 +10555,37 @@ func (v *stringInt16MapValue) IsCumulative() bool { // -- intInt16MapValue. type intInt16MapValue struct { - value *map[int]int16 + value *map[int]int16 + separator string } -var ( - _ RepeatableFlag = (*intInt16MapValue)(nil) - _ Value = (*intInt16MapValue)(nil) - _ Getter = (*intInt16MapValue)(nil) -) +var _ RepeatableFlag = (*intInt16MapValue)(nil) +var _ Value = (*intInt16MapValue)(nil) +var _ Getter = (*intInt16MapValue)(nil) -func newIntInt16MapValue(m *map[int]int16) *intInt16MapValue { - return &intInt16MapValue{ +func newIntInt16MapValue(m *map[int]int16, sep *string) *intInt16MapValue { + s := &intInt16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intInt16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8510,10 +10617,11 @@ func (v *intInt16MapValue) Set(val string) error { return nil } -func (v *intInt16MapValue) Get() interface{} { +func (v *intInt16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8521,6 +10629,7 @@ func (v *intInt16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8532,23 +10641,37 @@ func (v *intInt16MapValue) IsCumulative() bool { // -- int8Int16MapValue. type int8Int16MapValue struct { - value *map[int8]int16 + value *map[int8]int16 + separator string } -var ( - _ RepeatableFlag = (*int8Int16MapValue)(nil) - _ Value = (*int8Int16MapValue)(nil) - _ Getter = (*int8Int16MapValue)(nil) -) +var _ RepeatableFlag = (*int8Int16MapValue)(nil) +var _ Value = (*int8Int16MapValue)(nil) +var _ Getter = (*int8Int16MapValue)(nil) -func newInt8Int16MapValue(m *map[int8]int16) *int8Int16MapValue { - return &int8Int16MapValue{ +func newInt8Int16MapValue(m *map[int8]int16, sep *string) *int8Int16MapValue { + s := &int8Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8580,10 +10703,11 @@ func (v *int8Int16MapValue) Set(val string) error { return nil } -func (v *int8Int16MapValue) Get() interface{} { +func (v *int8Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8591,6 +10715,7 @@ func (v *int8Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8602,23 +10727,37 @@ func (v *int8Int16MapValue) IsCumulative() bool { // -- int16Int16MapValue. type int16Int16MapValue struct { - value *map[int16]int16 + value *map[int16]int16 + separator string } -var ( - _ RepeatableFlag = (*int16Int16MapValue)(nil) - _ Value = (*int16Int16MapValue)(nil) - _ Getter = (*int16Int16MapValue)(nil) -) +var _ RepeatableFlag = (*int16Int16MapValue)(nil) +var _ Value = (*int16Int16MapValue)(nil) +var _ Getter = (*int16Int16MapValue)(nil) -func newInt16Int16MapValue(m *map[int16]int16) *int16Int16MapValue { - return &int16Int16MapValue{ +func newInt16Int16MapValue(m *map[int16]int16, sep *string) *int16Int16MapValue { + s := &int16Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8650,10 +10789,11 @@ func (v *int16Int16MapValue) Set(val string) error { return nil } -func (v *int16Int16MapValue) Get() interface{} { +func (v *int16Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8661,6 +10801,7 @@ func (v *int16Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8672,23 +10813,37 @@ func (v *int16Int16MapValue) IsCumulative() bool { // -- int32Int16MapValue. type int32Int16MapValue struct { - value *map[int32]int16 + value *map[int32]int16 + separator string } -var ( - _ RepeatableFlag = (*int32Int16MapValue)(nil) - _ Value = (*int32Int16MapValue)(nil) - _ Getter = (*int32Int16MapValue)(nil) -) +var _ RepeatableFlag = (*int32Int16MapValue)(nil) +var _ Value = (*int32Int16MapValue)(nil) +var _ Getter = (*int32Int16MapValue)(nil) -func newInt32Int16MapValue(m *map[int32]int16) *int32Int16MapValue { - return &int32Int16MapValue{ +func newInt32Int16MapValue(m *map[int32]int16, sep *string) *int32Int16MapValue { + s := &int32Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8720,10 +10875,11 @@ func (v *int32Int16MapValue) Set(val string) error { return nil } -func (v *int32Int16MapValue) Get() interface{} { +func (v *int32Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8731,6 +10887,7 @@ func (v *int32Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8742,23 +10899,37 @@ func (v *int32Int16MapValue) IsCumulative() bool { // -- int64Int16MapValue. type int64Int16MapValue struct { - value *map[int64]int16 + value *map[int64]int16 + separator string } -var ( - _ RepeatableFlag = (*int64Int16MapValue)(nil) - _ Value = (*int64Int16MapValue)(nil) - _ Getter = (*int64Int16MapValue)(nil) -) +var _ RepeatableFlag = (*int64Int16MapValue)(nil) +var _ Value = (*int64Int16MapValue)(nil) +var _ Getter = (*int64Int16MapValue)(nil) -func newInt64Int16MapValue(m *map[int64]int16) *int64Int16MapValue { - return &int64Int16MapValue{ +func newInt64Int16MapValue(m *map[int64]int16, sep *string) *int64Int16MapValue { + s := &int64Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8790,10 +10961,11 @@ func (v *int64Int16MapValue) Set(val string) error { return nil } -func (v *int64Int16MapValue) Get() interface{} { +func (v *int64Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8801,6 +10973,7 @@ func (v *int64Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8812,23 +10985,37 @@ func (v *int64Int16MapValue) IsCumulative() bool { // -- uintInt16MapValue. type uintInt16MapValue struct { - value *map[uint]int16 + value *map[uint]int16 + separator string } -var ( - _ RepeatableFlag = (*uintInt16MapValue)(nil) - _ Value = (*uintInt16MapValue)(nil) - _ Getter = (*uintInt16MapValue)(nil) -) +var _ RepeatableFlag = (*uintInt16MapValue)(nil) +var _ Value = (*uintInt16MapValue)(nil) +var _ Getter = (*uintInt16MapValue)(nil) -func newUintInt16MapValue(m *map[uint]int16) *uintInt16MapValue { - return &uintInt16MapValue{ +func newUintInt16MapValue(m *map[uint]int16, sep *string) *uintInt16MapValue { + s := &uintInt16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintInt16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8860,10 +11047,11 @@ func (v *uintInt16MapValue) Set(val string) error { return nil } -func (v *uintInt16MapValue) Get() interface{} { +func (v *uintInt16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8871,6 +11059,7 @@ func (v *uintInt16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8882,23 +11071,37 @@ func (v *uintInt16MapValue) IsCumulative() bool { // -- uint8Int16MapValue. type uint8Int16MapValue struct { - value *map[uint8]int16 + value *map[uint8]int16 + separator string } -var ( - _ RepeatableFlag = (*uint8Int16MapValue)(nil) - _ Value = (*uint8Int16MapValue)(nil) - _ Getter = (*uint8Int16MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Int16MapValue)(nil) +var _ Value = (*uint8Int16MapValue)(nil) +var _ Getter = (*uint8Int16MapValue)(nil) -func newUint8Int16MapValue(m *map[uint8]int16) *uint8Int16MapValue { - return &uint8Int16MapValue{ +func newUint8Int16MapValue(m *map[uint8]int16, sep *string) *uint8Int16MapValue { + s := &uint8Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -8930,10 +11133,11 @@ func (v *uint8Int16MapValue) Set(val string) error { return nil } -func (v *uint8Int16MapValue) Get() interface{} { +func (v *uint8Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -8941,6 +11145,7 @@ func (v *uint8Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -8952,23 +11157,37 @@ func (v *uint8Int16MapValue) IsCumulative() bool { // -- uint16Int16MapValue. type uint16Int16MapValue struct { - value *map[uint16]int16 + value *map[uint16]int16 + separator string } -var ( - _ RepeatableFlag = (*uint16Int16MapValue)(nil) - _ Value = (*uint16Int16MapValue)(nil) - _ Getter = (*uint16Int16MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Int16MapValue)(nil) +var _ Value = (*uint16Int16MapValue)(nil) +var _ Getter = (*uint16Int16MapValue)(nil) -func newUint16Int16MapValue(m *map[uint16]int16) *uint16Int16MapValue { - return &uint16Int16MapValue{ +func newUint16Int16MapValue(m *map[uint16]int16, sep *string) *uint16Int16MapValue { + s := &uint16Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9000,10 +11219,11 @@ func (v *uint16Int16MapValue) Set(val string) error { return nil } -func (v *uint16Int16MapValue) Get() interface{} { +func (v *uint16Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9011,6 +11231,7 @@ func (v *uint16Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9022,23 +11243,37 @@ func (v *uint16Int16MapValue) IsCumulative() bool { // -- uint32Int16MapValue. type uint32Int16MapValue struct { - value *map[uint32]int16 + value *map[uint32]int16 + separator string } -var ( - _ RepeatableFlag = (*uint32Int16MapValue)(nil) - _ Value = (*uint32Int16MapValue)(nil) - _ Getter = (*uint32Int16MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Int16MapValue)(nil) +var _ Value = (*uint32Int16MapValue)(nil) +var _ Getter = (*uint32Int16MapValue)(nil) -func newUint32Int16MapValue(m *map[uint32]int16) *uint32Int16MapValue { - return &uint32Int16MapValue{ +func newUint32Int16MapValue(m *map[uint32]int16, sep *string) *uint32Int16MapValue { + s := &uint32Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9070,10 +11305,11 @@ func (v *uint32Int16MapValue) Set(val string) error { return nil } -func (v *uint32Int16MapValue) Get() interface{} { +func (v *uint32Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9081,6 +11317,7 @@ func (v *uint32Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9092,23 +11329,37 @@ func (v *uint32Int16MapValue) IsCumulative() bool { // -- uint64Int16MapValue. type uint64Int16MapValue struct { - value *map[uint64]int16 + value *map[uint64]int16 + separator string } -var ( - _ RepeatableFlag = (*uint64Int16MapValue)(nil) - _ Value = (*uint64Int16MapValue)(nil) - _ Getter = (*uint64Int16MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Int16MapValue)(nil) +var _ Value = (*uint64Int16MapValue)(nil) +var _ Getter = (*uint64Int16MapValue)(nil) -func newUint64Int16MapValue(m *map[uint64]int16) *uint64Int16MapValue { - return &uint64Int16MapValue{ +func newUint64Int16MapValue(m *map[uint64]int16, sep *string) *uint64Int16MapValue { + s := &uint64Int16MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Int16MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9140,10 +11391,11 @@ func (v *uint64Int16MapValue) Set(val string) error { return nil } -func (v *uint64Int16MapValue) Get() interface{} { +func (v *uint64Int16MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9151,6 +11403,7 @@ func (v *uint64Int16MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9165,35 +11418,42 @@ type int32Value struct { value *int32 } -var ( - _ Value = (*int32Value)(nil) - _ Getter = (*int32Value)(nil) -) +var _ Value = (*int32Value)(nil) +var _ Getter = (*int32Value)(nil) func newInt32Value(p *int32) *int32Value { return &int32Value{value: p} } func (v *int32Value) Set(s string) error { + parsed, err := strconv.ParseInt(s, 0, 32) if err == nil { + *v.value = (int32)(parsed) + return nil } + return err + } -func (v *int32Value) Get() interface{} { +func (v *int32Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *int32Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.Itoa(int(*v.value)) } + return "" } @@ -9202,24 +11462,38 @@ func (v *int32Value) Type() string { return "int32" } // -- int32Slice Value type int32SliceValue struct { - value *[]int32 - changed bool + value *[]int32 + changed bool + separator string } -var ( - _ RepeatableFlag = (*int32SliceValue)(nil) - _ Value = (*int32SliceValue)(nil) - _ Getter = (*int32SliceValue)(nil) -) +var _ RepeatableFlag = (*int32SliceValue)(nil) +var _ Value = (*int32SliceValue)(nil) +var _ Getter = (*int32SliceValue)(nil) -func newInt32SliceValue(slice *[]int32) *int32SliceValue { - return &int32SliceValue{ +func newInt32SliceValue(slice *[]int32, sep *string) *int32SliceValue { + s := &int32SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]int32, len(ss)) for i, s := range ss { @@ -9227,7 +11501,9 @@ func (v *int32SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (int32)(parsed) + } if !v.changed { @@ -9236,24 +11512,29 @@ func (v *int32SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *int32SliceValue) Get() interface{} { +func (v *int32SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]int32)(nil) } func (v *int32SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newInt32Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -9265,23 +11546,37 @@ func (v *int32SliceValue) IsCumulative() bool { // -- stringInt32MapValue. type stringInt32MapValue struct { - value *map[string]int32 + value *map[string]int32 + separator string } -var ( - _ RepeatableFlag = (*stringInt32MapValue)(nil) - _ Value = (*stringInt32MapValue)(nil) - _ Getter = (*stringInt32MapValue)(nil) -) +var _ RepeatableFlag = (*stringInt32MapValue)(nil) +var _ Value = (*stringInt32MapValue)(nil) +var _ Getter = (*stringInt32MapValue)(nil) -func newStringInt32MapValue(m *map[string]int32) *stringInt32MapValue { - return &stringInt32MapValue{ +func newStringInt32MapValue(m *map[string]int32, sep *string) *stringInt32MapValue { + s := &stringInt32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringInt32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9308,10 +11603,11 @@ func (v *stringInt32MapValue) Set(val string) error { return nil } -func (v *stringInt32MapValue) Get() interface{} { +func (v *stringInt32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9319,6 +11615,7 @@ func (v *stringInt32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9330,23 +11627,37 @@ func (v *stringInt32MapValue) IsCumulative() bool { // -- intInt32MapValue. type intInt32MapValue struct { - value *map[int]int32 + value *map[int]int32 + separator string } -var ( - _ RepeatableFlag = (*intInt32MapValue)(nil) - _ Value = (*intInt32MapValue)(nil) - _ Getter = (*intInt32MapValue)(nil) -) +var _ RepeatableFlag = (*intInt32MapValue)(nil) +var _ Value = (*intInt32MapValue)(nil) +var _ Getter = (*intInt32MapValue)(nil) -func newIntInt32MapValue(m *map[int]int32) *intInt32MapValue { - return &intInt32MapValue{ +func newIntInt32MapValue(m *map[int]int32, sep *string) *intInt32MapValue { + s := &intInt32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intInt32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9378,10 +11689,11 @@ func (v *intInt32MapValue) Set(val string) error { return nil } -func (v *intInt32MapValue) Get() interface{} { +func (v *intInt32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9389,6 +11701,7 @@ func (v *intInt32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9400,23 +11713,37 @@ func (v *intInt32MapValue) IsCumulative() bool { // -- int8Int32MapValue. type int8Int32MapValue struct { - value *map[int8]int32 + value *map[int8]int32 + separator string } -var ( - _ RepeatableFlag = (*int8Int32MapValue)(nil) - _ Value = (*int8Int32MapValue)(nil) - _ Getter = (*int8Int32MapValue)(nil) -) +var _ RepeatableFlag = (*int8Int32MapValue)(nil) +var _ Value = (*int8Int32MapValue)(nil) +var _ Getter = (*int8Int32MapValue)(nil) -func newInt8Int32MapValue(m *map[int8]int32) *int8Int32MapValue { - return &int8Int32MapValue{ +func newInt8Int32MapValue(m *map[int8]int32, sep *string) *int8Int32MapValue { + s := &int8Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9448,10 +11775,11 @@ func (v *int8Int32MapValue) Set(val string) error { return nil } -func (v *int8Int32MapValue) Get() interface{} { +func (v *int8Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9459,6 +11787,7 @@ func (v *int8Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9470,23 +11799,37 @@ func (v *int8Int32MapValue) IsCumulative() bool { // -- int16Int32MapValue. type int16Int32MapValue struct { - value *map[int16]int32 + value *map[int16]int32 + separator string } -var ( - _ RepeatableFlag = (*int16Int32MapValue)(nil) - _ Value = (*int16Int32MapValue)(nil) - _ Getter = (*int16Int32MapValue)(nil) -) +var _ RepeatableFlag = (*int16Int32MapValue)(nil) +var _ Value = (*int16Int32MapValue)(nil) +var _ Getter = (*int16Int32MapValue)(nil) -func newInt16Int32MapValue(m *map[int16]int32) *int16Int32MapValue { - return &int16Int32MapValue{ +func newInt16Int32MapValue(m *map[int16]int32, sep *string) *int16Int32MapValue { + s := &int16Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9518,10 +11861,11 @@ func (v *int16Int32MapValue) Set(val string) error { return nil } -func (v *int16Int32MapValue) Get() interface{} { +func (v *int16Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9529,6 +11873,7 @@ func (v *int16Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9540,23 +11885,37 @@ func (v *int16Int32MapValue) IsCumulative() bool { // -- int32Int32MapValue. type int32Int32MapValue struct { - value *map[int32]int32 + value *map[int32]int32 + separator string } -var ( - _ RepeatableFlag = (*int32Int32MapValue)(nil) - _ Value = (*int32Int32MapValue)(nil) - _ Getter = (*int32Int32MapValue)(nil) -) +var _ RepeatableFlag = (*int32Int32MapValue)(nil) +var _ Value = (*int32Int32MapValue)(nil) +var _ Getter = (*int32Int32MapValue)(nil) -func newInt32Int32MapValue(m *map[int32]int32) *int32Int32MapValue { - return &int32Int32MapValue{ +func newInt32Int32MapValue(m *map[int32]int32, sep *string) *int32Int32MapValue { + s := &int32Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9588,10 +11947,11 @@ func (v *int32Int32MapValue) Set(val string) error { return nil } -func (v *int32Int32MapValue) Get() interface{} { +func (v *int32Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9599,6 +11959,7 @@ func (v *int32Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9610,23 +11971,37 @@ func (v *int32Int32MapValue) IsCumulative() bool { // -- int64Int32MapValue. type int64Int32MapValue struct { - value *map[int64]int32 + value *map[int64]int32 + separator string } -var ( - _ RepeatableFlag = (*int64Int32MapValue)(nil) - _ Value = (*int64Int32MapValue)(nil) - _ Getter = (*int64Int32MapValue)(nil) -) +var _ RepeatableFlag = (*int64Int32MapValue)(nil) +var _ Value = (*int64Int32MapValue)(nil) +var _ Getter = (*int64Int32MapValue)(nil) -func newInt64Int32MapValue(m *map[int64]int32) *int64Int32MapValue { - return &int64Int32MapValue{ +func newInt64Int32MapValue(m *map[int64]int32, sep *string) *int64Int32MapValue { + s := &int64Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9658,10 +12033,11 @@ func (v *int64Int32MapValue) Set(val string) error { return nil } -func (v *int64Int32MapValue) Get() interface{} { +func (v *int64Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9669,6 +12045,7 @@ func (v *int64Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9680,23 +12057,37 @@ func (v *int64Int32MapValue) IsCumulative() bool { // -- uintInt32MapValue. type uintInt32MapValue struct { - value *map[uint]int32 + value *map[uint]int32 + separator string } -var ( - _ RepeatableFlag = (*uintInt32MapValue)(nil) - _ Value = (*uintInt32MapValue)(nil) - _ Getter = (*uintInt32MapValue)(nil) -) +var _ RepeatableFlag = (*uintInt32MapValue)(nil) +var _ Value = (*uintInt32MapValue)(nil) +var _ Getter = (*uintInt32MapValue)(nil) -func newUintInt32MapValue(m *map[uint]int32) *uintInt32MapValue { - return &uintInt32MapValue{ +func newUintInt32MapValue(m *map[uint]int32, sep *string) *uintInt32MapValue { + s := &uintInt32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintInt32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9728,10 +12119,11 @@ func (v *uintInt32MapValue) Set(val string) error { return nil } -func (v *uintInt32MapValue) Get() interface{} { +func (v *uintInt32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9739,6 +12131,7 @@ func (v *uintInt32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9750,23 +12143,37 @@ func (v *uintInt32MapValue) IsCumulative() bool { // -- uint8Int32MapValue. type uint8Int32MapValue struct { - value *map[uint8]int32 + value *map[uint8]int32 + separator string } -var ( - _ RepeatableFlag = (*uint8Int32MapValue)(nil) - _ Value = (*uint8Int32MapValue)(nil) - _ Getter = (*uint8Int32MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Int32MapValue)(nil) +var _ Value = (*uint8Int32MapValue)(nil) +var _ Getter = (*uint8Int32MapValue)(nil) -func newUint8Int32MapValue(m *map[uint8]int32) *uint8Int32MapValue { - return &uint8Int32MapValue{ +func newUint8Int32MapValue(m *map[uint8]int32, sep *string) *uint8Int32MapValue { + s := &uint8Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9798,10 +12205,11 @@ func (v *uint8Int32MapValue) Set(val string) error { return nil } -func (v *uint8Int32MapValue) Get() interface{} { +func (v *uint8Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9809,6 +12217,7 @@ func (v *uint8Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9820,23 +12229,37 @@ func (v *uint8Int32MapValue) IsCumulative() bool { // -- uint16Int32MapValue. type uint16Int32MapValue struct { - value *map[uint16]int32 + value *map[uint16]int32 + separator string } -var ( - _ RepeatableFlag = (*uint16Int32MapValue)(nil) - _ Value = (*uint16Int32MapValue)(nil) - _ Getter = (*uint16Int32MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Int32MapValue)(nil) +var _ Value = (*uint16Int32MapValue)(nil) +var _ Getter = (*uint16Int32MapValue)(nil) -func newUint16Int32MapValue(m *map[uint16]int32) *uint16Int32MapValue { - return &uint16Int32MapValue{ +func newUint16Int32MapValue(m *map[uint16]int32, sep *string) *uint16Int32MapValue { + s := &uint16Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9868,10 +12291,11 @@ func (v *uint16Int32MapValue) Set(val string) error { return nil } -func (v *uint16Int32MapValue) Get() interface{} { +func (v *uint16Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9879,6 +12303,7 @@ func (v *uint16Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9890,23 +12315,37 @@ func (v *uint16Int32MapValue) IsCumulative() bool { // -- uint32Int32MapValue. type uint32Int32MapValue struct { - value *map[uint32]int32 + value *map[uint32]int32 + separator string } -var ( - _ RepeatableFlag = (*uint32Int32MapValue)(nil) - _ Value = (*uint32Int32MapValue)(nil) - _ Getter = (*uint32Int32MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Int32MapValue)(nil) +var _ Value = (*uint32Int32MapValue)(nil) +var _ Getter = (*uint32Int32MapValue)(nil) -func newUint32Int32MapValue(m *map[uint32]int32) *uint32Int32MapValue { - return &uint32Int32MapValue{ +func newUint32Int32MapValue(m *map[uint32]int32, sep *string) *uint32Int32MapValue { + s := &uint32Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -9938,10 +12377,11 @@ func (v *uint32Int32MapValue) Set(val string) error { return nil } -func (v *uint32Int32MapValue) Get() interface{} { +func (v *uint32Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -9949,6 +12389,7 @@ func (v *uint32Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -9960,23 +12401,37 @@ func (v *uint32Int32MapValue) IsCumulative() bool { // -- uint64Int32MapValue. type uint64Int32MapValue struct { - value *map[uint64]int32 + value *map[uint64]int32 + separator string } -var ( - _ RepeatableFlag = (*uint64Int32MapValue)(nil) - _ Value = (*uint64Int32MapValue)(nil) - _ Getter = (*uint64Int32MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Int32MapValue)(nil) +var _ Value = (*uint64Int32MapValue)(nil) +var _ Getter = (*uint64Int32MapValue)(nil) -func newUint64Int32MapValue(m *map[uint64]int32) *uint64Int32MapValue { - return &uint64Int32MapValue{ +func newUint64Int32MapValue(m *map[uint64]int32, sep *string) *uint64Int32MapValue { + s := &uint64Int32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Int32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10008,10 +12463,11 @@ func (v *uint64Int32MapValue) Set(val string) error { return nil } -func (v *uint64Int32MapValue) Get() interface{} { +func (v *uint64Int32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10019,6 +12475,7 @@ func (v *uint64Int32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10033,35 +12490,42 @@ type int64Value struct { value *int64 } -var ( - _ Value = (*int64Value)(nil) - _ Getter = (*int64Value)(nil) -) +var _ Value = (*int64Value)(nil) +var _ Getter = (*int64Value)(nil) func newInt64Value(p *int64) *int64Value { return &int64Value{value: p} } func (v *int64Value) Set(s string) error { + parsed, err := strconv.ParseInt(s, 0, 64) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *int64Value) Get() interface{} { +func (v *int64Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *int64Value) String() string { if v != nil && v.value != nil { - return fmt.Sprintf("%v", *v.value) + + return strconv.FormatInt(*v.value, 10) } + return "" } @@ -10070,24 +12534,38 @@ func (v *int64Value) Type() string { return "int64" } // -- int64Slice Value type int64SliceValue struct { - value *[]int64 - changed bool + value *[]int64 + changed bool + separator string } -var ( - _ RepeatableFlag = (*int64SliceValue)(nil) - _ Value = (*int64SliceValue)(nil) - _ Getter = (*int64SliceValue)(nil) -) +var _ RepeatableFlag = (*int64SliceValue)(nil) +var _ Value = (*int64SliceValue)(nil) +var _ Getter = (*int64SliceValue)(nil) -func newInt64SliceValue(slice *[]int64) *int64SliceValue { - return &int64SliceValue{ +func newInt64SliceValue(slice *[]int64, sep *string) *int64SliceValue { + s := &int64SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]int64, len(ss)) for i, s := range ss { @@ -10095,7 +12573,9 @@ func (v *int64SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -10104,24 +12584,29 @@ func (v *int64SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *int64SliceValue) Get() interface{} { +func (v *int64SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]int64)(nil) } func (v *int64SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newInt64Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -10133,23 +12618,37 @@ func (v *int64SliceValue) IsCumulative() bool { // -- stringInt64MapValue. type stringInt64MapValue struct { - value *map[string]int64 + value *map[string]int64 + separator string } -var ( - _ RepeatableFlag = (*stringInt64MapValue)(nil) - _ Value = (*stringInt64MapValue)(nil) - _ Getter = (*stringInt64MapValue)(nil) -) +var _ RepeatableFlag = (*stringInt64MapValue)(nil) +var _ Value = (*stringInt64MapValue)(nil) +var _ Getter = (*stringInt64MapValue)(nil) -func newStringInt64MapValue(m *map[string]int64) *stringInt64MapValue { - return &stringInt64MapValue{ +func newStringInt64MapValue(m *map[string]int64, sep *string) *stringInt64MapValue { + s := &stringInt64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringInt64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10176,10 +12675,11 @@ func (v *stringInt64MapValue) Set(val string) error { return nil } -func (v *stringInt64MapValue) Get() interface{} { +func (v *stringInt64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10187,6 +12687,7 @@ func (v *stringInt64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10198,23 +12699,37 @@ func (v *stringInt64MapValue) IsCumulative() bool { // -- intInt64MapValue. type intInt64MapValue struct { - value *map[int]int64 + value *map[int]int64 + separator string } -var ( - _ RepeatableFlag = (*intInt64MapValue)(nil) - _ Value = (*intInt64MapValue)(nil) - _ Getter = (*intInt64MapValue)(nil) -) +var _ RepeatableFlag = (*intInt64MapValue)(nil) +var _ Value = (*intInt64MapValue)(nil) +var _ Getter = (*intInt64MapValue)(nil) -func newIntInt64MapValue(m *map[int]int64) *intInt64MapValue { - return &intInt64MapValue{ +func newIntInt64MapValue(m *map[int]int64, sep *string) *intInt64MapValue { + s := &intInt64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intInt64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10246,10 +12761,11 @@ func (v *intInt64MapValue) Set(val string) error { return nil } -func (v *intInt64MapValue) Get() interface{} { +func (v *intInt64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10257,6 +12773,7 @@ func (v *intInt64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10268,23 +12785,37 @@ func (v *intInt64MapValue) IsCumulative() bool { // -- int8Int64MapValue. type int8Int64MapValue struct { - value *map[int8]int64 + value *map[int8]int64 + separator string } -var ( - _ RepeatableFlag = (*int8Int64MapValue)(nil) - _ Value = (*int8Int64MapValue)(nil) - _ Getter = (*int8Int64MapValue)(nil) -) +var _ RepeatableFlag = (*int8Int64MapValue)(nil) +var _ Value = (*int8Int64MapValue)(nil) +var _ Getter = (*int8Int64MapValue)(nil) -func newInt8Int64MapValue(m *map[int8]int64) *int8Int64MapValue { - return &int8Int64MapValue{ +func newInt8Int64MapValue(m *map[int8]int64, sep *string) *int8Int64MapValue { + s := &int8Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10316,10 +12847,11 @@ func (v *int8Int64MapValue) Set(val string) error { return nil } -func (v *int8Int64MapValue) Get() interface{} { +func (v *int8Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10327,6 +12859,7 @@ func (v *int8Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10338,23 +12871,37 @@ func (v *int8Int64MapValue) IsCumulative() bool { // -- int16Int64MapValue. type int16Int64MapValue struct { - value *map[int16]int64 + value *map[int16]int64 + separator string } -var ( - _ RepeatableFlag = (*int16Int64MapValue)(nil) - _ Value = (*int16Int64MapValue)(nil) - _ Getter = (*int16Int64MapValue)(nil) -) +var _ RepeatableFlag = (*int16Int64MapValue)(nil) +var _ Value = (*int16Int64MapValue)(nil) +var _ Getter = (*int16Int64MapValue)(nil) -func newInt16Int64MapValue(m *map[int16]int64) *int16Int64MapValue { - return &int16Int64MapValue{ +func newInt16Int64MapValue(m *map[int16]int64, sep *string) *int16Int64MapValue { + s := &int16Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10386,10 +12933,11 @@ func (v *int16Int64MapValue) Set(val string) error { return nil } -func (v *int16Int64MapValue) Get() interface{} { +func (v *int16Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10397,6 +12945,7 @@ func (v *int16Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10408,23 +12957,37 @@ func (v *int16Int64MapValue) IsCumulative() bool { // -- int32Int64MapValue. type int32Int64MapValue struct { - value *map[int32]int64 + value *map[int32]int64 + separator string } -var ( - _ RepeatableFlag = (*int32Int64MapValue)(nil) - _ Value = (*int32Int64MapValue)(nil) - _ Getter = (*int32Int64MapValue)(nil) -) +var _ RepeatableFlag = (*int32Int64MapValue)(nil) +var _ Value = (*int32Int64MapValue)(nil) +var _ Getter = (*int32Int64MapValue)(nil) -func newInt32Int64MapValue(m *map[int32]int64) *int32Int64MapValue { - return &int32Int64MapValue{ +func newInt32Int64MapValue(m *map[int32]int64, sep *string) *int32Int64MapValue { + s := &int32Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10456,10 +13019,11 @@ func (v *int32Int64MapValue) Set(val string) error { return nil } -func (v *int32Int64MapValue) Get() interface{} { +func (v *int32Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10467,6 +13031,7 @@ func (v *int32Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10478,23 +13043,37 @@ func (v *int32Int64MapValue) IsCumulative() bool { // -- int64Int64MapValue. type int64Int64MapValue struct { - value *map[int64]int64 + value *map[int64]int64 + separator string } -var ( - _ RepeatableFlag = (*int64Int64MapValue)(nil) - _ Value = (*int64Int64MapValue)(nil) - _ Getter = (*int64Int64MapValue)(nil) -) +var _ RepeatableFlag = (*int64Int64MapValue)(nil) +var _ Value = (*int64Int64MapValue)(nil) +var _ Getter = (*int64Int64MapValue)(nil) -func newInt64Int64MapValue(m *map[int64]int64) *int64Int64MapValue { - return &int64Int64MapValue{ +func newInt64Int64MapValue(m *map[int64]int64, sep *string) *int64Int64MapValue { + s := &int64Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10526,10 +13105,11 @@ func (v *int64Int64MapValue) Set(val string) error { return nil } -func (v *int64Int64MapValue) Get() interface{} { +func (v *int64Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10537,6 +13117,7 @@ func (v *int64Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10548,23 +13129,37 @@ func (v *int64Int64MapValue) IsCumulative() bool { // -- uintInt64MapValue. type uintInt64MapValue struct { - value *map[uint]int64 + value *map[uint]int64 + separator string } -var ( - _ RepeatableFlag = (*uintInt64MapValue)(nil) - _ Value = (*uintInt64MapValue)(nil) - _ Getter = (*uintInt64MapValue)(nil) -) +var _ RepeatableFlag = (*uintInt64MapValue)(nil) +var _ Value = (*uintInt64MapValue)(nil) +var _ Getter = (*uintInt64MapValue)(nil) -func newUintInt64MapValue(m *map[uint]int64) *uintInt64MapValue { - return &uintInt64MapValue{ +func newUintInt64MapValue(m *map[uint]int64, sep *string) *uintInt64MapValue { + s := &uintInt64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintInt64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10596,10 +13191,11 @@ func (v *uintInt64MapValue) Set(val string) error { return nil } -func (v *uintInt64MapValue) Get() interface{} { +func (v *uintInt64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10607,6 +13203,7 @@ func (v *uintInt64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10618,23 +13215,37 @@ func (v *uintInt64MapValue) IsCumulative() bool { // -- uint8Int64MapValue. type uint8Int64MapValue struct { - value *map[uint8]int64 + value *map[uint8]int64 + separator string } -var ( - _ RepeatableFlag = (*uint8Int64MapValue)(nil) - _ Value = (*uint8Int64MapValue)(nil) - _ Getter = (*uint8Int64MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Int64MapValue)(nil) +var _ Value = (*uint8Int64MapValue)(nil) +var _ Getter = (*uint8Int64MapValue)(nil) -func newUint8Int64MapValue(m *map[uint8]int64) *uint8Int64MapValue { - return &uint8Int64MapValue{ +func newUint8Int64MapValue(m *map[uint8]int64, sep *string) *uint8Int64MapValue { + s := &uint8Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10666,10 +13277,11 @@ func (v *uint8Int64MapValue) Set(val string) error { return nil } -func (v *uint8Int64MapValue) Get() interface{} { +func (v *uint8Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10677,6 +13289,7 @@ func (v *uint8Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10688,23 +13301,37 @@ func (v *uint8Int64MapValue) IsCumulative() bool { // -- uint16Int64MapValue. type uint16Int64MapValue struct { - value *map[uint16]int64 + value *map[uint16]int64 + separator string } -var ( - _ RepeatableFlag = (*uint16Int64MapValue)(nil) - _ Value = (*uint16Int64MapValue)(nil) - _ Getter = (*uint16Int64MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Int64MapValue)(nil) +var _ Value = (*uint16Int64MapValue)(nil) +var _ Getter = (*uint16Int64MapValue)(nil) -func newUint16Int64MapValue(m *map[uint16]int64) *uint16Int64MapValue { - return &uint16Int64MapValue{ +func newUint16Int64MapValue(m *map[uint16]int64, sep *string) *uint16Int64MapValue { + s := &uint16Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10736,10 +13363,11 @@ func (v *uint16Int64MapValue) Set(val string) error { return nil } -func (v *uint16Int64MapValue) Get() interface{} { +func (v *uint16Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10747,6 +13375,7 @@ func (v *uint16Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10758,23 +13387,37 @@ func (v *uint16Int64MapValue) IsCumulative() bool { // -- uint32Int64MapValue. type uint32Int64MapValue struct { - value *map[uint32]int64 + value *map[uint32]int64 + separator string } -var ( - _ RepeatableFlag = (*uint32Int64MapValue)(nil) - _ Value = (*uint32Int64MapValue)(nil) - _ Getter = (*uint32Int64MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Int64MapValue)(nil) +var _ Value = (*uint32Int64MapValue)(nil) +var _ Getter = (*uint32Int64MapValue)(nil) -func newUint32Int64MapValue(m *map[uint32]int64) *uint32Int64MapValue { - return &uint32Int64MapValue{ +func newUint32Int64MapValue(m *map[uint32]int64, sep *string) *uint32Int64MapValue { + s := &uint32Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10806,10 +13449,11 @@ func (v *uint32Int64MapValue) Set(val string) error { return nil } -func (v *uint32Int64MapValue) Get() interface{} { +func (v *uint32Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10817,6 +13461,7 @@ func (v *uint32Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10828,23 +13473,37 @@ func (v *uint32Int64MapValue) IsCumulative() bool { // -- uint64Int64MapValue. type uint64Int64MapValue struct { - value *map[uint64]int64 + value *map[uint64]int64 + separator string } -var ( - _ RepeatableFlag = (*uint64Int64MapValue)(nil) - _ Value = (*uint64Int64MapValue)(nil) - _ Getter = (*uint64Int64MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Int64MapValue)(nil) +var _ Value = (*uint64Int64MapValue)(nil) +var _ Getter = (*uint64Int64MapValue)(nil) -func newUint64Int64MapValue(m *map[uint64]int64) *uint64Int64MapValue { - return &uint64Int64MapValue{ +func newUint64Int64MapValue(m *map[uint64]int64, sep *string) *uint64Int64MapValue { + s := &uint64Int64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Int64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -10876,10 +13535,11 @@ func (v *uint64Int64MapValue) Set(val string) error { return nil } -func (v *uint64Int64MapValue) Get() interface{} { +func (v *uint64Int64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -10887,6 +13547,7 @@ func (v *uint64Int64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10901,35 +13562,42 @@ type float64Value struct { value *float64 } -var ( - _ Value = (*float64Value)(nil) - _ Getter = (*float64Value)(nil) -) +var _ Value = (*float64Value)(nil) +var _ Getter = (*float64Value)(nil) func newFloat64Value(p *float64) *float64Value { return &float64Value{value: p} } func (v *float64Value) Set(s string) error { + parsed, err := strconv.ParseFloat(s, 64) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *float64Value) Get() interface{} { +func (v *float64Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *float64Value) String() string { if v != nil && v.value != nil { + return fmt.Sprintf("%v", *v.value) } + return "" } @@ -10938,24 +13606,38 @@ func (v *float64Value) Type() string { return "float64" } // -- float64Slice Value type float64SliceValue struct { - value *[]float64 - changed bool + value *[]float64 + changed bool + separator string } -var ( - _ RepeatableFlag = (*float64SliceValue)(nil) - _ Value = (*float64SliceValue)(nil) - _ Getter = (*float64SliceValue)(nil) -) +var _ RepeatableFlag = (*float64SliceValue)(nil) +var _ Value = (*float64SliceValue)(nil) +var _ Getter = (*float64SliceValue)(nil) -func newFloat64SliceValue(slice *[]float64) *float64SliceValue { - return &float64SliceValue{ +func newFloat64SliceValue(slice *[]float64, sep *string) *float64SliceValue { + s := &float64SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *float64SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]float64, len(ss)) for i, s := range ss { @@ -10963,7 +13645,9 @@ func (v *float64SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -10972,24 +13656,29 @@ func (v *float64SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *float64SliceValue) Get() interface{} { +func (v *float64SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]float64)(nil) } func (v *float64SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newFloat64Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -11001,23 +13690,37 @@ func (v *float64SliceValue) IsCumulative() bool { // -- stringFloat64MapValue. type stringFloat64MapValue struct { - value *map[string]float64 + value *map[string]float64 + separator string } -var ( - _ RepeatableFlag = (*stringFloat64MapValue)(nil) - _ Value = (*stringFloat64MapValue)(nil) - _ Getter = (*stringFloat64MapValue)(nil) -) +var _ RepeatableFlag = (*stringFloat64MapValue)(nil) +var _ Value = (*stringFloat64MapValue)(nil) +var _ Getter = (*stringFloat64MapValue)(nil) -func newStringFloat64MapValue(m *map[string]float64) *stringFloat64MapValue { - return &stringFloat64MapValue{ +func newStringFloat64MapValue(m *map[string]float64, sep *string) *stringFloat64MapValue { + s := &stringFloat64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringFloat64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11044,10 +13747,11 @@ func (v *stringFloat64MapValue) Set(val string) error { return nil } -func (v *stringFloat64MapValue) Get() interface{} { +func (v *stringFloat64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11055,6 +13759,7 @@ func (v *stringFloat64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11066,23 +13771,37 @@ func (v *stringFloat64MapValue) IsCumulative() bool { // -- intFloat64MapValue. type intFloat64MapValue struct { - value *map[int]float64 + value *map[int]float64 + separator string } -var ( - _ RepeatableFlag = (*intFloat64MapValue)(nil) - _ Value = (*intFloat64MapValue)(nil) - _ Getter = (*intFloat64MapValue)(nil) -) +var _ RepeatableFlag = (*intFloat64MapValue)(nil) +var _ Value = (*intFloat64MapValue)(nil) +var _ Getter = (*intFloat64MapValue)(nil) -func newIntFloat64MapValue(m *map[int]float64) *intFloat64MapValue { - return &intFloat64MapValue{ +func newIntFloat64MapValue(m *map[int]float64, sep *string) *intFloat64MapValue { + s := &intFloat64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intFloat64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11114,10 +13833,11 @@ func (v *intFloat64MapValue) Set(val string) error { return nil } -func (v *intFloat64MapValue) Get() interface{} { +func (v *intFloat64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11125,6 +13845,7 @@ func (v *intFloat64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11136,23 +13857,37 @@ func (v *intFloat64MapValue) IsCumulative() bool { // -- int8Float64MapValue. type int8Float64MapValue struct { - value *map[int8]float64 + value *map[int8]float64 + separator string } -var ( - _ RepeatableFlag = (*int8Float64MapValue)(nil) - _ Value = (*int8Float64MapValue)(nil) - _ Getter = (*int8Float64MapValue)(nil) -) +var _ RepeatableFlag = (*int8Float64MapValue)(nil) +var _ Value = (*int8Float64MapValue)(nil) +var _ Getter = (*int8Float64MapValue)(nil) -func newInt8Float64MapValue(m *map[int8]float64) *int8Float64MapValue { - return &int8Float64MapValue{ +func newInt8Float64MapValue(m *map[int8]float64, sep *string) *int8Float64MapValue { + s := &int8Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11184,10 +13919,11 @@ func (v *int8Float64MapValue) Set(val string) error { return nil } -func (v *int8Float64MapValue) Get() interface{} { +func (v *int8Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11195,6 +13931,7 @@ func (v *int8Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11206,23 +13943,37 @@ func (v *int8Float64MapValue) IsCumulative() bool { // -- int16Float64MapValue. type int16Float64MapValue struct { - value *map[int16]float64 + value *map[int16]float64 + separator string } -var ( - _ RepeatableFlag = (*int16Float64MapValue)(nil) - _ Value = (*int16Float64MapValue)(nil) - _ Getter = (*int16Float64MapValue)(nil) -) +var _ RepeatableFlag = (*int16Float64MapValue)(nil) +var _ Value = (*int16Float64MapValue)(nil) +var _ Getter = (*int16Float64MapValue)(nil) -func newInt16Float64MapValue(m *map[int16]float64) *int16Float64MapValue { - return &int16Float64MapValue{ +func newInt16Float64MapValue(m *map[int16]float64, sep *string) *int16Float64MapValue { + s := &int16Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11254,10 +14005,11 @@ func (v *int16Float64MapValue) Set(val string) error { return nil } -func (v *int16Float64MapValue) Get() interface{} { +func (v *int16Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11265,6 +14017,7 @@ func (v *int16Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11276,23 +14029,37 @@ func (v *int16Float64MapValue) IsCumulative() bool { // -- int32Float64MapValue. type int32Float64MapValue struct { - value *map[int32]float64 + value *map[int32]float64 + separator string } -var ( - _ RepeatableFlag = (*int32Float64MapValue)(nil) - _ Value = (*int32Float64MapValue)(nil) - _ Getter = (*int32Float64MapValue)(nil) -) +var _ RepeatableFlag = (*int32Float64MapValue)(nil) +var _ Value = (*int32Float64MapValue)(nil) +var _ Getter = (*int32Float64MapValue)(nil) -func newInt32Float64MapValue(m *map[int32]float64) *int32Float64MapValue { - return &int32Float64MapValue{ +func newInt32Float64MapValue(m *map[int32]float64, sep *string) *int32Float64MapValue { + s := &int32Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11324,10 +14091,11 @@ func (v *int32Float64MapValue) Set(val string) error { return nil } -func (v *int32Float64MapValue) Get() interface{} { +func (v *int32Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11335,6 +14103,7 @@ func (v *int32Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11346,23 +14115,37 @@ func (v *int32Float64MapValue) IsCumulative() bool { // -- int64Float64MapValue. type int64Float64MapValue struct { - value *map[int64]float64 + value *map[int64]float64 + separator string } -var ( - _ RepeatableFlag = (*int64Float64MapValue)(nil) - _ Value = (*int64Float64MapValue)(nil) - _ Getter = (*int64Float64MapValue)(nil) -) +var _ RepeatableFlag = (*int64Float64MapValue)(nil) +var _ Value = (*int64Float64MapValue)(nil) +var _ Getter = (*int64Float64MapValue)(nil) -func newInt64Float64MapValue(m *map[int64]float64) *int64Float64MapValue { - return &int64Float64MapValue{ +func newInt64Float64MapValue(m *map[int64]float64, sep *string) *int64Float64MapValue { + s := &int64Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11394,10 +14177,11 @@ func (v *int64Float64MapValue) Set(val string) error { return nil } -func (v *int64Float64MapValue) Get() interface{} { +func (v *int64Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11405,6 +14189,7 @@ func (v *int64Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11416,23 +14201,37 @@ func (v *int64Float64MapValue) IsCumulative() bool { // -- uintFloat64MapValue. type uintFloat64MapValue struct { - value *map[uint]float64 + value *map[uint]float64 + separator string } -var ( - _ RepeatableFlag = (*uintFloat64MapValue)(nil) - _ Value = (*uintFloat64MapValue)(nil) - _ Getter = (*uintFloat64MapValue)(nil) -) +var _ RepeatableFlag = (*uintFloat64MapValue)(nil) +var _ Value = (*uintFloat64MapValue)(nil) +var _ Getter = (*uintFloat64MapValue)(nil) -func newUintFloat64MapValue(m *map[uint]float64) *uintFloat64MapValue { - return &uintFloat64MapValue{ +func newUintFloat64MapValue(m *map[uint]float64, sep *string) *uintFloat64MapValue { + s := &uintFloat64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintFloat64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11464,10 +14263,11 @@ func (v *uintFloat64MapValue) Set(val string) error { return nil } -func (v *uintFloat64MapValue) Get() interface{} { +func (v *uintFloat64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11475,6 +14275,7 @@ func (v *uintFloat64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11486,23 +14287,37 @@ func (v *uintFloat64MapValue) IsCumulative() bool { // -- uint8Float64MapValue. type uint8Float64MapValue struct { - value *map[uint8]float64 + value *map[uint8]float64 + separator string } -var ( - _ RepeatableFlag = (*uint8Float64MapValue)(nil) - _ Value = (*uint8Float64MapValue)(nil) - _ Getter = (*uint8Float64MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Float64MapValue)(nil) +var _ Value = (*uint8Float64MapValue)(nil) +var _ Getter = (*uint8Float64MapValue)(nil) -func newUint8Float64MapValue(m *map[uint8]float64) *uint8Float64MapValue { - return &uint8Float64MapValue{ +func newUint8Float64MapValue(m *map[uint8]float64, sep *string) *uint8Float64MapValue { + s := &uint8Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11534,10 +14349,11 @@ func (v *uint8Float64MapValue) Set(val string) error { return nil } -func (v *uint8Float64MapValue) Get() interface{} { +func (v *uint8Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11545,6 +14361,7 @@ func (v *uint8Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11556,23 +14373,37 @@ func (v *uint8Float64MapValue) IsCumulative() bool { // -- uint16Float64MapValue. type uint16Float64MapValue struct { - value *map[uint16]float64 + value *map[uint16]float64 + separator string } -var ( - _ RepeatableFlag = (*uint16Float64MapValue)(nil) - _ Value = (*uint16Float64MapValue)(nil) - _ Getter = (*uint16Float64MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Float64MapValue)(nil) +var _ Value = (*uint16Float64MapValue)(nil) +var _ Getter = (*uint16Float64MapValue)(nil) -func newUint16Float64MapValue(m *map[uint16]float64) *uint16Float64MapValue { - return &uint16Float64MapValue{ +func newUint16Float64MapValue(m *map[uint16]float64, sep *string) *uint16Float64MapValue { + s := &uint16Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11604,10 +14435,11 @@ func (v *uint16Float64MapValue) Set(val string) error { return nil } -func (v *uint16Float64MapValue) Get() interface{} { +func (v *uint16Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11615,6 +14447,7 @@ func (v *uint16Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11626,23 +14459,37 @@ func (v *uint16Float64MapValue) IsCumulative() bool { // -- uint32Float64MapValue. type uint32Float64MapValue struct { - value *map[uint32]float64 + value *map[uint32]float64 + separator string } -var ( - _ RepeatableFlag = (*uint32Float64MapValue)(nil) - _ Value = (*uint32Float64MapValue)(nil) - _ Getter = (*uint32Float64MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Float64MapValue)(nil) +var _ Value = (*uint32Float64MapValue)(nil) +var _ Getter = (*uint32Float64MapValue)(nil) -func newUint32Float64MapValue(m *map[uint32]float64) *uint32Float64MapValue { - return &uint32Float64MapValue{ +func newUint32Float64MapValue(m *map[uint32]float64, sep *string) *uint32Float64MapValue { + s := &uint32Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11674,10 +14521,11 @@ func (v *uint32Float64MapValue) Set(val string) error { return nil } -func (v *uint32Float64MapValue) Get() interface{} { +func (v *uint32Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11685,6 +14533,7 @@ func (v *uint32Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11696,23 +14545,37 @@ func (v *uint32Float64MapValue) IsCumulative() bool { // -- uint64Float64MapValue. type uint64Float64MapValue struct { - value *map[uint64]float64 + value *map[uint64]float64 + separator string } -var ( - _ RepeatableFlag = (*uint64Float64MapValue)(nil) - _ Value = (*uint64Float64MapValue)(nil) - _ Getter = (*uint64Float64MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Float64MapValue)(nil) +var _ Value = (*uint64Float64MapValue)(nil) +var _ Getter = (*uint64Float64MapValue)(nil) -func newUint64Float64MapValue(m *map[uint64]float64) *uint64Float64MapValue { - return &uint64Float64MapValue{ +func newUint64Float64MapValue(m *map[uint64]float64, sep *string) *uint64Float64MapValue { + s := &uint64Float64MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Float64MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11744,10 +14607,11 @@ func (v *uint64Float64MapValue) Set(val string) error { return nil } -func (v *uint64Float64MapValue) Get() interface{} { +func (v *uint64Float64MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11755,6 +14619,7 @@ func (v *uint64Float64MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11769,35 +14634,42 @@ type float32Value struct { value *float32 } -var ( - _ Value = (*float32Value)(nil) - _ Getter = (*float32Value)(nil) -) +var _ Value = (*float32Value)(nil) +var _ Getter = (*float32Value)(nil) func newFloat32Value(p *float32) *float32Value { return &float32Value{value: p} } func (v *float32Value) Set(s string) error { + parsed, err := strconv.ParseFloat(s, 32) if err == nil { + *v.value = (float32)(parsed) + return nil } + return err + } -func (v *float32Value) Get() interface{} { +func (v *float32Value) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *float32Value) String() string { if v != nil && v.value != nil { + return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11806,24 +14678,38 @@ func (v *float32Value) Type() string { return "float32" } // -- float32Slice Value type float32SliceValue struct { - value *[]float32 - changed bool + value *[]float32 + changed bool + separator string } -var ( - _ RepeatableFlag = (*float32SliceValue)(nil) - _ Value = (*float32SliceValue)(nil) - _ Getter = (*float32SliceValue)(nil) -) +var _ RepeatableFlag = (*float32SliceValue)(nil) +var _ Value = (*float32SliceValue)(nil) +var _ Getter = (*float32SliceValue)(nil) -func newFloat32SliceValue(slice *[]float32) *float32SliceValue { - return &float32SliceValue{ +func newFloat32SliceValue(slice *[]float32, sep *string) *float32SliceValue { + s := &float32SliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *float32SliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]float32, len(ss)) for i, s := range ss { @@ -11831,7 +14717,9 @@ func (v *float32SliceValue) Set(raw string) error { if err != nil { return err } + out[i] = (float32)(parsed) + } if !v.changed { @@ -11840,24 +14728,29 @@ func (v *float32SliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *float32SliceValue) Get() interface{} { +func (v *float32SliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]float32)(nil) } func (v *float32SliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newFloat32Value(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -11869,23 +14762,37 @@ func (v *float32SliceValue) IsCumulative() bool { // -- stringFloat32MapValue. type stringFloat32MapValue struct { - value *map[string]float32 + value *map[string]float32 + separator string } -var ( - _ RepeatableFlag = (*stringFloat32MapValue)(nil) - _ Value = (*stringFloat32MapValue)(nil) - _ Getter = (*stringFloat32MapValue)(nil) -) +var _ RepeatableFlag = (*stringFloat32MapValue)(nil) +var _ Value = (*stringFloat32MapValue)(nil) +var _ Getter = (*stringFloat32MapValue)(nil) -func newStringFloat32MapValue(m *map[string]float32) *stringFloat32MapValue { - return &stringFloat32MapValue{ +func newStringFloat32MapValue(m *map[string]float32, sep *string) *stringFloat32MapValue { + s := &stringFloat32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringFloat32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11912,10 +14819,11 @@ func (v *stringFloat32MapValue) Set(val string) error { return nil } -func (v *stringFloat32MapValue) Get() interface{} { +func (v *stringFloat32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11923,6 +14831,7 @@ func (v *stringFloat32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -11934,23 +14843,37 @@ func (v *stringFloat32MapValue) IsCumulative() bool { // -- intFloat32MapValue. type intFloat32MapValue struct { - value *map[int]float32 + value *map[int]float32 + separator string } -var ( - _ RepeatableFlag = (*intFloat32MapValue)(nil) - _ Value = (*intFloat32MapValue)(nil) - _ Getter = (*intFloat32MapValue)(nil) -) +var _ RepeatableFlag = (*intFloat32MapValue)(nil) +var _ Value = (*intFloat32MapValue)(nil) +var _ Getter = (*intFloat32MapValue)(nil) -func newIntFloat32MapValue(m *map[int]float32) *intFloat32MapValue { - return &intFloat32MapValue{ +func newIntFloat32MapValue(m *map[int]float32, sep *string) *intFloat32MapValue { + s := &intFloat32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intFloat32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -11982,10 +14905,11 @@ func (v *intFloat32MapValue) Set(val string) error { return nil } -func (v *intFloat32MapValue) Get() interface{} { +func (v *intFloat32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -11993,6 +14917,7 @@ func (v *intFloat32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12004,23 +14929,37 @@ func (v *intFloat32MapValue) IsCumulative() bool { // -- int8Float32MapValue. type int8Float32MapValue struct { - value *map[int8]float32 + value *map[int8]float32 + separator string } -var ( - _ RepeatableFlag = (*int8Float32MapValue)(nil) - _ Value = (*int8Float32MapValue)(nil) - _ Getter = (*int8Float32MapValue)(nil) -) +var _ RepeatableFlag = (*int8Float32MapValue)(nil) +var _ Value = (*int8Float32MapValue)(nil) +var _ Getter = (*int8Float32MapValue)(nil) -func newInt8Float32MapValue(m *map[int8]float32) *int8Float32MapValue { - return &int8Float32MapValue{ +func newInt8Float32MapValue(m *map[int8]float32, sep *string) *int8Float32MapValue { + s := &int8Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12052,10 +14991,11 @@ func (v *int8Float32MapValue) Set(val string) error { return nil } -func (v *int8Float32MapValue) Get() interface{} { +func (v *int8Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12063,6 +15003,7 @@ func (v *int8Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12074,23 +15015,37 @@ func (v *int8Float32MapValue) IsCumulative() bool { // -- int16Float32MapValue. type int16Float32MapValue struct { - value *map[int16]float32 + value *map[int16]float32 + separator string } -var ( - _ RepeatableFlag = (*int16Float32MapValue)(nil) - _ Value = (*int16Float32MapValue)(nil) - _ Getter = (*int16Float32MapValue)(nil) -) +var _ RepeatableFlag = (*int16Float32MapValue)(nil) +var _ Value = (*int16Float32MapValue)(nil) +var _ Getter = (*int16Float32MapValue)(nil) -func newInt16Float32MapValue(m *map[int16]float32) *int16Float32MapValue { - return &int16Float32MapValue{ +func newInt16Float32MapValue(m *map[int16]float32, sep *string) *int16Float32MapValue { + s := &int16Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12122,10 +15077,11 @@ func (v *int16Float32MapValue) Set(val string) error { return nil } -func (v *int16Float32MapValue) Get() interface{} { +func (v *int16Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12133,6 +15089,7 @@ func (v *int16Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12144,23 +15101,37 @@ func (v *int16Float32MapValue) IsCumulative() bool { // -- int32Float32MapValue. type int32Float32MapValue struct { - value *map[int32]float32 + value *map[int32]float32 + separator string } -var ( - _ RepeatableFlag = (*int32Float32MapValue)(nil) - _ Value = (*int32Float32MapValue)(nil) - _ Getter = (*int32Float32MapValue)(nil) -) +var _ RepeatableFlag = (*int32Float32MapValue)(nil) +var _ Value = (*int32Float32MapValue)(nil) +var _ Getter = (*int32Float32MapValue)(nil) -func newInt32Float32MapValue(m *map[int32]float32) *int32Float32MapValue { - return &int32Float32MapValue{ +func newInt32Float32MapValue(m *map[int32]float32, sep *string) *int32Float32MapValue { + s := &int32Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12192,10 +15163,11 @@ func (v *int32Float32MapValue) Set(val string) error { return nil } -func (v *int32Float32MapValue) Get() interface{} { +func (v *int32Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12203,6 +15175,7 @@ func (v *int32Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12214,23 +15187,37 @@ func (v *int32Float32MapValue) IsCumulative() bool { // -- int64Float32MapValue. type int64Float32MapValue struct { - value *map[int64]float32 + value *map[int64]float32 + separator string } -var ( - _ RepeatableFlag = (*int64Float32MapValue)(nil) - _ Value = (*int64Float32MapValue)(nil) - _ Getter = (*int64Float32MapValue)(nil) -) +var _ RepeatableFlag = (*int64Float32MapValue)(nil) +var _ Value = (*int64Float32MapValue)(nil) +var _ Getter = (*int64Float32MapValue)(nil) -func newInt64Float32MapValue(m *map[int64]float32) *int64Float32MapValue { - return &int64Float32MapValue{ +func newInt64Float32MapValue(m *map[int64]float32, sep *string) *int64Float32MapValue { + s := &int64Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12262,10 +15249,11 @@ func (v *int64Float32MapValue) Set(val string) error { return nil } -func (v *int64Float32MapValue) Get() interface{} { +func (v *int64Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12273,6 +15261,7 @@ func (v *int64Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12284,23 +15273,37 @@ func (v *int64Float32MapValue) IsCumulative() bool { // -- uintFloat32MapValue. type uintFloat32MapValue struct { - value *map[uint]float32 + value *map[uint]float32 + separator string } -var ( - _ RepeatableFlag = (*uintFloat32MapValue)(nil) - _ Value = (*uintFloat32MapValue)(nil) - _ Getter = (*uintFloat32MapValue)(nil) -) +var _ RepeatableFlag = (*uintFloat32MapValue)(nil) +var _ Value = (*uintFloat32MapValue)(nil) +var _ Getter = (*uintFloat32MapValue)(nil) -func newUintFloat32MapValue(m *map[uint]float32) *uintFloat32MapValue { - return &uintFloat32MapValue{ +func newUintFloat32MapValue(m *map[uint]float32, sep *string) *uintFloat32MapValue { + s := &uintFloat32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintFloat32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12332,10 +15335,11 @@ func (v *uintFloat32MapValue) Set(val string) error { return nil } -func (v *uintFloat32MapValue) Get() interface{} { +func (v *uintFloat32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12343,6 +15347,7 @@ func (v *uintFloat32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12354,23 +15359,37 @@ func (v *uintFloat32MapValue) IsCumulative() bool { // -- uint8Float32MapValue. type uint8Float32MapValue struct { - value *map[uint8]float32 + value *map[uint8]float32 + separator string } -var ( - _ RepeatableFlag = (*uint8Float32MapValue)(nil) - _ Value = (*uint8Float32MapValue)(nil) - _ Getter = (*uint8Float32MapValue)(nil) -) +var _ RepeatableFlag = (*uint8Float32MapValue)(nil) +var _ Value = (*uint8Float32MapValue)(nil) +var _ Getter = (*uint8Float32MapValue)(nil) -func newUint8Float32MapValue(m *map[uint8]float32) *uint8Float32MapValue { - return &uint8Float32MapValue{ +func newUint8Float32MapValue(m *map[uint8]float32, sep *string) *uint8Float32MapValue { + s := &uint8Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12402,10 +15421,11 @@ func (v *uint8Float32MapValue) Set(val string) error { return nil } -func (v *uint8Float32MapValue) Get() interface{} { +func (v *uint8Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12413,6 +15433,7 @@ func (v *uint8Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12424,23 +15445,37 @@ func (v *uint8Float32MapValue) IsCumulative() bool { // -- uint16Float32MapValue. type uint16Float32MapValue struct { - value *map[uint16]float32 + value *map[uint16]float32 + separator string } -var ( - _ RepeatableFlag = (*uint16Float32MapValue)(nil) - _ Value = (*uint16Float32MapValue)(nil) - _ Getter = (*uint16Float32MapValue)(nil) -) +var _ RepeatableFlag = (*uint16Float32MapValue)(nil) +var _ Value = (*uint16Float32MapValue)(nil) +var _ Getter = (*uint16Float32MapValue)(nil) -func newUint16Float32MapValue(m *map[uint16]float32) *uint16Float32MapValue { - return &uint16Float32MapValue{ +func newUint16Float32MapValue(m *map[uint16]float32, sep *string) *uint16Float32MapValue { + s := &uint16Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12472,10 +15507,11 @@ func (v *uint16Float32MapValue) Set(val string) error { return nil } -func (v *uint16Float32MapValue) Get() interface{} { +func (v *uint16Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12483,6 +15519,7 @@ func (v *uint16Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12494,23 +15531,37 @@ func (v *uint16Float32MapValue) IsCumulative() bool { // -- uint32Float32MapValue. type uint32Float32MapValue struct { - value *map[uint32]float32 + value *map[uint32]float32 + separator string } -var ( - _ RepeatableFlag = (*uint32Float32MapValue)(nil) - _ Value = (*uint32Float32MapValue)(nil) - _ Getter = (*uint32Float32MapValue)(nil) -) +var _ RepeatableFlag = (*uint32Float32MapValue)(nil) +var _ Value = (*uint32Float32MapValue)(nil) +var _ Getter = (*uint32Float32MapValue)(nil) -func newUint32Float32MapValue(m *map[uint32]float32) *uint32Float32MapValue { - return &uint32Float32MapValue{ +func newUint32Float32MapValue(m *map[uint32]float32, sep *string) *uint32Float32MapValue { + s := &uint32Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12542,10 +15593,11 @@ func (v *uint32Float32MapValue) Set(val string) error { return nil } -func (v *uint32Float32MapValue) Get() interface{} { +func (v *uint32Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12553,6 +15605,7 @@ func (v *uint32Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12564,23 +15617,37 @@ func (v *uint32Float32MapValue) IsCumulative() bool { // -- uint64Float32MapValue. type uint64Float32MapValue struct { - value *map[uint64]float32 + value *map[uint64]float32 + separator string } -var ( - _ RepeatableFlag = (*uint64Float32MapValue)(nil) - _ Value = (*uint64Float32MapValue)(nil) - _ Getter = (*uint64Float32MapValue)(nil) -) +var _ RepeatableFlag = (*uint64Float32MapValue)(nil) +var _ Value = (*uint64Float32MapValue)(nil) +var _ Getter = (*uint64Float32MapValue)(nil) -func newUint64Float32MapValue(m *map[uint64]float32) *uint64Float32MapValue { - return &uint64Float32MapValue{ +func newUint64Float32MapValue(m *map[uint64]float32, sep *string) *uint64Float32MapValue { + s := &uint64Float32MapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64Float32MapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12612,10 +15679,11 @@ func (v *uint64Float32MapValue) Set(val string) error { return nil } -func (v *uint64Float32MapValue) Get() interface{} { +func (v *uint64Float32MapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12623,6 +15691,7 @@ func (v *uint64Float32MapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12637,35 +15706,42 @@ type durationValue struct { value *time.Duration } -var ( - _ Value = (*durationValue)(nil) - _ Getter = (*durationValue)(nil) -) +var _ Value = (*durationValue)(nil) +var _ Getter = (*durationValue)(nil) func newDurationValue(p *time.Duration) *durationValue { return &durationValue{value: p} } func (v *durationValue) Set(s string) error { + parsed, err := time.ParseDuration(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *durationValue) Get() interface{} { +func (v *durationValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *durationValue) String() string { if v != nil && v.value != nil { + return (*v.value).String() } + return "" } @@ -12674,24 +15750,38 @@ func (v *durationValue) Type() string { return "duration" } // -- time.DurationSlice Value type durationSliceValue struct { - value *[]time.Duration - changed bool + value *[]time.Duration + changed bool + separator string } -var ( - _ RepeatableFlag = (*durationSliceValue)(nil) - _ Value = (*durationSliceValue)(nil) - _ Getter = (*durationSliceValue)(nil) -) +var _ RepeatableFlag = (*durationSliceValue)(nil) +var _ Value = (*durationSliceValue)(nil) +var _ Getter = (*durationSliceValue)(nil) -func newDurationSliceValue(slice *[]time.Duration) *durationSliceValue { - return &durationSliceValue{ +func newDurationSliceValue(slice *[]time.Duration, sep *string) *durationSliceValue { + s := &durationSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *durationSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]time.Duration, len(ss)) for i, s := range ss { @@ -12699,7 +15789,9 @@ func (v *durationSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -12708,24 +15800,29 @@ func (v *durationSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *durationSliceValue) Get() interface{} { +func (v *durationSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]time.Duration)(nil) } func (v *durationSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newDurationValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -12737,23 +15834,37 @@ func (v *durationSliceValue) IsCumulative() bool { // -- stringDurationMapValue. type stringDurationMapValue struct { - value *map[string]time.Duration + value *map[string]time.Duration + separator string } -var ( - _ RepeatableFlag = (*stringDurationMapValue)(nil) - _ Value = (*stringDurationMapValue)(nil) - _ Getter = (*stringDurationMapValue)(nil) -) +var _ RepeatableFlag = (*stringDurationMapValue)(nil) +var _ Value = (*stringDurationMapValue)(nil) +var _ Getter = (*stringDurationMapValue)(nil) -func newStringDurationMapValue(m *map[string]time.Duration) *stringDurationMapValue { - return &stringDurationMapValue{ +func newStringDurationMapValue(m *map[string]time.Duration, sep *string) *stringDurationMapValue { + s := &stringDurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringDurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12780,10 +15891,11 @@ func (v *stringDurationMapValue) Set(val string) error { return nil } -func (v *stringDurationMapValue) Get() interface{} { +func (v *stringDurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12791,6 +15903,7 @@ func (v *stringDurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12802,23 +15915,37 @@ func (v *stringDurationMapValue) IsCumulative() bool { // -- intDurationMapValue. type intDurationMapValue struct { - value *map[int]time.Duration + value *map[int]time.Duration + separator string } -var ( - _ RepeatableFlag = (*intDurationMapValue)(nil) - _ Value = (*intDurationMapValue)(nil) - _ Getter = (*intDurationMapValue)(nil) -) +var _ RepeatableFlag = (*intDurationMapValue)(nil) +var _ Value = (*intDurationMapValue)(nil) +var _ Getter = (*intDurationMapValue)(nil) -func newIntDurationMapValue(m *map[int]time.Duration) *intDurationMapValue { - return &intDurationMapValue{ +func newIntDurationMapValue(m *map[int]time.Duration, sep *string) *intDurationMapValue { + s := &intDurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intDurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12850,10 +15977,11 @@ func (v *intDurationMapValue) Set(val string) error { return nil } -func (v *intDurationMapValue) Get() interface{} { +func (v *intDurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12861,6 +15989,7 @@ func (v *intDurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12872,23 +16001,37 @@ func (v *intDurationMapValue) IsCumulative() bool { // -- int8DurationMapValue. type int8DurationMapValue struct { - value *map[int8]time.Duration + value *map[int8]time.Duration + separator string } -var ( - _ RepeatableFlag = (*int8DurationMapValue)(nil) - _ Value = (*int8DurationMapValue)(nil) - _ Getter = (*int8DurationMapValue)(nil) -) +var _ RepeatableFlag = (*int8DurationMapValue)(nil) +var _ Value = (*int8DurationMapValue)(nil) +var _ Getter = (*int8DurationMapValue)(nil) -func newInt8DurationMapValue(m *map[int8]time.Duration) *int8DurationMapValue { - return &int8DurationMapValue{ +func newInt8DurationMapValue(m *map[int8]time.Duration, sep *string) *int8DurationMapValue { + s := &int8DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12920,10 +16063,11 @@ func (v *int8DurationMapValue) Set(val string) error { return nil } -func (v *int8DurationMapValue) Get() interface{} { +func (v *int8DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -12931,6 +16075,7 @@ func (v *int8DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -12942,23 +16087,37 @@ func (v *int8DurationMapValue) IsCumulative() bool { // -- int16DurationMapValue. type int16DurationMapValue struct { - value *map[int16]time.Duration + value *map[int16]time.Duration + separator string } -var ( - _ RepeatableFlag = (*int16DurationMapValue)(nil) - _ Value = (*int16DurationMapValue)(nil) - _ Getter = (*int16DurationMapValue)(nil) -) +var _ RepeatableFlag = (*int16DurationMapValue)(nil) +var _ Value = (*int16DurationMapValue)(nil) +var _ Getter = (*int16DurationMapValue)(nil) -func newInt16DurationMapValue(m *map[int16]time.Duration) *int16DurationMapValue { - return &int16DurationMapValue{ +func newInt16DurationMapValue(m *map[int16]time.Duration, sep *string) *int16DurationMapValue { + s := &int16DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -12990,10 +16149,11 @@ func (v *int16DurationMapValue) Set(val string) error { return nil } -func (v *int16DurationMapValue) Get() interface{} { +func (v *int16DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13001,6 +16161,7 @@ func (v *int16DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13012,23 +16173,37 @@ func (v *int16DurationMapValue) IsCumulative() bool { // -- int32DurationMapValue. type int32DurationMapValue struct { - value *map[int32]time.Duration + value *map[int32]time.Duration + separator string } -var ( - _ RepeatableFlag = (*int32DurationMapValue)(nil) - _ Value = (*int32DurationMapValue)(nil) - _ Getter = (*int32DurationMapValue)(nil) -) +var _ RepeatableFlag = (*int32DurationMapValue)(nil) +var _ Value = (*int32DurationMapValue)(nil) +var _ Getter = (*int32DurationMapValue)(nil) -func newInt32DurationMapValue(m *map[int32]time.Duration) *int32DurationMapValue { - return &int32DurationMapValue{ +func newInt32DurationMapValue(m *map[int32]time.Duration, sep *string) *int32DurationMapValue { + s := &int32DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13060,10 +16235,11 @@ func (v *int32DurationMapValue) Set(val string) error { return nil } -func (v *int32DurationMapValue) Get() interface{} { +func (v *int32DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13071,6 +16247,7 @@ func (v *int32DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13082,23 +16259,37 @@ func (v *int32DurationMapValue) IsCumulative() bool { // -- int64DurationMapValue. type int64DurationMapValue struct { - value *map[int64]time.Duration + value *map[int64]time.Duration + separator string } -var ( - _ RepeatableFlag = (*int64DurationMapValue)(nil) - _ Value = (*int64DurationMapValue)(nil) - _ Getter = (*int64DurationMapValue)(nil) -) +var _ RepeatableFlag = (*int64DurationMapValue)(nil) +var _ Value = (*int64DurationMapValue)(nil) +var _ Getter = (*int64DurationMapValue)(nil) -func newInt64DurationMapValue(m *map[int64]time.Duration) *int64DurationMapValue { - return &int64DurationMapValue{ +func newInt64DurationMapValue(m *map[int64]time.Duration, sep *string) *int64DurationMapValue { + s := &int64DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13130,10 +16321,11 @@ func (v *int64DurationMapValue) Set(val string) error { return nil } -func (v *int64DurationMapValue) Get() interface{} { +func (v *int64DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13141,6 +16333,7 @@ func (v *int64DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13152,23 +16345,37 @@ func (v *int64DurationMapValue) IsCumulative() bool { // -- uintDurationMapValue. type uintDurationMapValue struct { - value *map[uint]time.Duration + value *map[uint]time.Duration + separator string } -var ( - _ RepeatableFlag = (*uintDurationMapValue)(nil) - _ Value = (*uintDurationMapValue)(nil) - _ Getter = (*uintDurationMapValue)(nil) -) +var _ RepeatableFlag = (*uintDurationMapValue)(nil) +var _ Value = (*uintDurationMapValue)(nil) +var _ Getter = (*uintDurationMapValue)(nil) -func newUintDurationMapValue(m *map[uint]time.Duration) *uintDurationMapValue { - return &uintDurationMapValue{ +func newUintDurationMapValue(m *map[uint]time.Duration, sep *string) *uintDurationMapValue { + s := &uintDurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintDurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13200,10 +16407,11 @@ func (v *uintDurationMapValue) Set(val string) error { return nil } -func (v *uintDurationMapValue) Get() interface{} { +func (v *uintDurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13211,6 +16419,7 @@ func (v *uintDurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13222,23 +16431,37 @@ func (v *uintDurationMapValue) IsCumulative() bool { // -- uint8DurationMapValue. type uint8DurationMapValue struct { - value *map[uint8]time.Duration + value *map[uint8]time.Duration + separator string } -var ( - _ RepeatableFlag = (*uint8DurationMapValue)(nil) - _ Value = (*uint8DurationMapValue)(nil) - _ Getter = (*uint8DurationMapValue)(nil) -) +var _ RepeatableFlag = (*uint8DurationMapValue)(nil) +var _ Value = (*uint8DurationMapValue)(nil) +var _ Getter = (*uint8DurationMapValue)(nil) -func newUint8DurationMapValue(m *map[uint8]time.Duration) *uint8DurationMapValue { - return &uint8DurationMapValue{ +func newUint8DurationMapValue(m *map[uint8]time.Duration, sep *string) *uint8DurationMapValue { + s := &uint8DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13270,10 +16493,11 @@ func (v *uint8DurationMapValue) Set(val string) error { return nil } -func (v *uint8DurationMapValue) Get() interface{} { +func (v *uint8DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13281,6 +16505,7 @@ func (v *uint8DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13292,23 +16517,37 @@ func (v *uint8DurationMapValue) IsCumulative() bool { // -- uint16DurationMapValue. type uint16DurationMapValue struct { - value *map[uint16]time.Duration + value *map[uint16]time.Duration + separator string } -var ( - _ RepeatableFlag = (*uint16DurationMapValue)(nil) - _ Value = (*uint16DurationMapValue)(nil) - _ Getter = (*uint16DurationMapValue)(nil) -) +var _ RepeatableFlag = (*uint16DurationMapValue)(nil) +var _ Value = (*uint16DurationMapValue)(nil) +var _ Getter = (*uint16DurationMapValue)(nil) -func newUint16DurationMapValue(m *map[uint16]time.Duration) *uint16DurationMapValue { - return &uint16DurationMapValue{ +func newUint16DurationMapValue(m *map[uint16]time.Duration, sep *string) *uint16DurationMapValue { + s := &uint16DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13340,10 +16579,11 @@ func (v *uint16DurationMapValue) Set(val string) error { return nil } -func (v *uint16DurationMapValue) Get() interface{} { +func (v *uint16DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13351,6 +16591,7 @@ func (v *uint16DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13362,23 +16603,37 @@ func (v *uint16DurationMapValue) IsCumulative() bool { // -- uint32DurationMapValue. type uint32DurationMapValue struct { - value *map[uint32]time.Duration + value *map[uint32]time.Duration + separator string } -var ( - _ RepeatableFlag = (*uint32DurationMapValue)(nil) - _ Value = (*uint32DurationMapValue)(nil) - _ Getter = (*uint32DurationMapValue)(nil) -) +var _ RepeatableFlag = (*uint32DurationMapValue)(nil) +var _ Value = (*uint32DurationMapValue)(nil) +var _ Getter = (*uint32DurationMapValue)(nil) -func newUint32DurationMapValue(m *map[uint32]time.Duration) *uint32DurationMapValue { - return &uint32DurationMapValue{ +func newUint32DurationMapValue(m *map[uint32]time.Duration, sep *string) *uint32DurationMapValue { + s := &uint32DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13410,10 +16665,11 @@ func (v *uint32DurationMapValue) Set(val string) error { return nil } -func (v *uint32DurationMapValue) Get() interface{} { +func (v *uint32DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13421,6 +16677,7 @@ func (v *uint32DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13432,23 +16689,37 @@ func (v *uint32DurationMapValue) IsCumulative() bool { // -- uint64DurationMapValue. type uint64DurationMapValue struct { - value *map[uint64]time.Duration + value *map[uint64]time.Duration + separator string } -var ( - _ RepeatableFlag = (*uint64DurationMapValue)(nil) - _ Value = (*uint64DurationMapValue)(nil) - _ Getter = (*uint64DurationMapValue)(nil) -) +var _ RepeatableFlag = (*uint64DurationMapValue)(nil) +var _ Value = (*uint64DurationMapValue)(nil) +var _ Getter = (*uint64DurationMapValue)(nil) -func newUint64DurationMapValue(m *map[uint64]time.Duration) *uint64DurationMapValue { - return &uint64DurationMapValue{ +func newUint64DurationMapValue(m *map[uint64]time.Duration, sep *string) *uint64DurationMapValue { + s := &uint64DurationMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64DurationMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13480,10 +16751,11 @@ func (v *uint64DurationMapValue) Set(val string) error { return nil } -func (v *uint64DurationMapValue) Get() interface{} { +func (v *uint64DurationMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13491,6 +16763,7 @@ func (v *uint64DurationMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13505,35 +16778,42 @@ type ipValue struct { value *net.IP } -var ( - _ Value = (*ipValue)(nil) - _ Getter = (*ipValue)(nil) -) +var _ Value = (*ipValue)(nil) +var _ Getter = (*ipValue)(nil) func newIPValue(p *net.IP) *ipValue { return &ipValue{value: p} } func (v *ipValue) Set(s string) error { + parsed, err := parseIP(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *ipValue) Get() interface{} { +func (v *ipValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *ipValue) String() string { if v != nil && v.value != nil { + return v.value.String() } + return "" } @@ -13542,24 +16822,38 @@ func (v *ipValue) Type() string { return "ip" } // -- net.IPSlice Value type ipSliceValue struct { - value *[]net.IP - changed bool + value *[]net.IP + changed bool + separator string } -var ( - _ RepeatableFlag = (*ipSliceValue)(nil) - _ Value = (*ipSliceValue)(nil) - _ Getter = (*ipSliceValue)(nil) -) +var _ RepeatableFlag = (*ipSliceValue)(nil) +var _ Value = (*ipSliceValue)(nil) +var _ Getter = (*ipSliceValue)(nil) -func newIPSliceValue(slice *[]net.IP) *ipSliceValue { - return &ipSliceValue{ +func newIPSliceValue(slice *[]net.IP, sep *string) *ipSliceValue { + s := &ipSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *ipSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]net.IP, len(ss)) for i, s := range ss { @@ -13567,7 +16861,9 @@ func (v *ipSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -13576,24 +16872,29 @@ func (v *ipSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *ipSliceValue) Get() interface{} { +func (v *ipSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]net.IP)(nil) } func (v *ipSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newIPValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -13605,23 +16906,37 @@ func (v *ipSliceValue) IsCumulative() bool { // -- stringIPMapValue. type stringIPMapValue struct { - value *map[string]net.IP + value *map[string]net.IP + separator string } -var ( - _ RepeatableFlag = (*stringIPMapValue)(nil) - _ Value = (*stringIPMapValue)(nil) - _ Getter = (*stringIPMapValue)(nil) -) +var _ RepeatableFlag = (*stringIPMapValue)(nil) +var _ Value = (*stringIPMapValue)(nil) +var _ Getter = (*stringIPMapValue)(nil) -func newStringIPMapValue(m *map[string]net.IP) *stringIPMapValue { - return &stringIPMapValue{ +func newStringIPMapValue(m *map[string]net.IP, sep *string) *stringIPMapValue { + s := &stringIPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringIPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13648,10 +16963,11 @@ func (v *stringIPMapValue) Set(val string) error { return nil } -func (v *stringIPMapValue) Get() interface{} { +func (v *stringIPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13659,6 +16975,7 @@ func (v *stringIPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13670,23 +16987,37 @@ func (v *stringIPMapValue) IsCumulative() bool { // -- intIPMapValue. type intIPMapValue struct { - value *map[int]net.IP + value *map[int]net.IP + separator string } -var ( - _ RepeatableFlag = (*intIPMapValue)(nil) - _ Value = (*intIPMapValue)(nil) - _ Getter = (*intIPMapValue)(nil) -) +var _ RepeatableFlag = (*intIPMapValue)(nil) +var _ Value = (*intIPMapValue)(nil) +var _ Getter = (*intIPMapValue)(nil) -func newIntIPMapValue(m *map[int]net.IP) *intIPMapValue { - return &intIPMapValue{ +func newIntIPMapValue(m *map[int]net.IP, sep *string) *intIPMapValue { + s := &intIPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intIPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13718,10 +17049,11 @@ func (v *intIPMapValue) Set(val string) error { return nil } -func (v *intIPMapValue) Get() interface{} { +func (v *intIPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13729,6 +17061,7 @@ func (v *intIPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13740,23 +17073,37 @@ func (v *intIPMapValue) IsCumulative() bool { // -- int8IPMapValue. type int8IPMapValue struct { - value *map[int8]net.IP + value *map[int8]net.IP + separator string } -var ( - _ RepeatableFlag = (*int8IPMapValue)(nil) - _ Value = (*int8IPMapValue)(nil) - _ Getter = (*int8IPMapValue)(nil) -) +var _ RepeatableFlag = (*int8IPMapValue)(nil) +var _ Value = (*int8IPMapValue)(nil) +var _ Getter = (*int8IPMapValue)(nil) -func newInt8IPMapValue(m *map[int8]net.IP) *int8IPMapValue { - return &int8IPMapValue{ +func newInt8IPMapValue(m *map[int8]net.IP, sep *string) *int8IPMapValue { + s := &int8IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13788,10 +17135,11 @@ func (v *int8IPMapValue) Set(val string) error { return nil } -func (v *int8IPMapValue) Get() interface{} { +func (v *int8IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13799,6 +17147,7 @@ func (v *int8IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13810,23 +17159,37 @@ func (v *int8IPMapValue) IsCumulative() bool { // -- int16IPMapValue. type int16IPMapValue struct { - value *map[int16]net.IP + value *map[int16]net.IP + separator string } -var ( - _ RepeatableFlag = (*int16IPMapValue)(nil) - _ Value = (*int16IPMapValue)(nil) - _ Getter = (*int16IPMapValue)(nil) -) +var _ RepeatableFlag = (*int16IPMapValue)(nil) +var _ Value = (*int16IPMapValue)(nil) +var _ Getter = (*int16IPMapValue)(nil) -func newInt16IPMapValue(m *map[int16]net.IP) *int16IPMapValue { - return &int16IPMapValue{ +func newInt16IPMapValue(m *map[int16]net.IP, sep *string) *int16IPMapValue { + s := &int16IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13858,10 +17221,11 @@ func (v *int16IPMapValue) Set(val string) error { return nil } -func (v *int16IPMapValue) Get() interface{} { +func (v *int16IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13869,6 +17233,7 @@ func (v *int16IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13880,23 +17245,37 @@ func (v *int16IPMapValue) IsCumulative() bool { // -- int32IPMapValue. type int32IPMapValue struct { - value *map[int32]net.IP + value *map[int32]net.IP + separator string } -var ( - _ RepeatableFlag = (*int32IPMapValue)(nil) - _ Value = (*int32IPMapValue)(nil) - _ Getter = (*int32IPMapValue)(nil) -) +var _ RepeatableFlag = (*int32IPMapValue)(nil) +var _ Value = (*int32IPMapValue)(nil) +var _ Getter = (*int32IPMapValue)(nil) -func newInt32IPMapValue(m *map[int32]net.IP) *int32IPMapValue { - return &int32IPMapValue{ +func newInt32IPMapValue(m *map[int32]net.IP, sep *string) *int32IPMapValue { + s := &int32IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13928,10 +17307,11 @@ func (v *int32IPMapValue) Set(val string) error { return nil } -func (v *int32IPMapValue) Get() interface{} { +func (v *int32IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -13939,6 +17319,7 @@ func (v *int32IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -13950,23 +17331,37 @@ func (v *int32IPMapValue) IsCumulative() bool { // -- int64IPMapValue. type int64IPMapValue struct { - value *map[int64]net.IP + value *map[int64]net.IP + separator string } -var ( - _ RepeatableFlag = (*int64IPMapValue)(nil) - _ Value = (*int64IPMapValue)(nil) - _ Getter = (*int64IPMapValue)(nil) -) +var _ RepeatableFlag = (*int64IPMapValue)(nil) +var _ Value = (*int64IPMapValue)(nil) +var _ Getter = (*int64IPMapValue)(nil) -func newInt64IPMapValue(m *map[int64]net.IP) *int64IPMapValue { - return &int64IPMapValue{ +func newInt64IPMapValue(m *map[int64]net.IP, sep *string) *int64IPMapValue { + s := &int64IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -13998,10 +17393,11 @@ func (v *int64IPMapValue) Set(val string) error { return nil } -func (v *int64IPMapValue) Get() interface{} { +func (v *int64IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14009,6 +17405,7 @@ func (v *int64IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14020,23 +17417,37 @@ func (v *int64IPMapValue) IsCumulative() bool { // -- uintIPMapValue. type uintIPMapValue struct { - value *map[uint]net.IP + value *map[uint]net.IP + separator string } -var ( - _ RepeatableFlag = (*uintIPMapValue)(nil) - _ Value = (*uintIPMapValue)(nil) - _ Getter = (*uintIPMapValue)(nil) -) +var _ RepeatableFlag = (*uintIPMapValue)(nil) +var _ Value = (*uintIPMapValue)(nil) +var _ Getter = (*uintIPMapValue)(nil) -func newUintIPMapValue(m *map[uint]net.IP) *uintIPMapValue { - return &uintIPMapValue{ +func newUintIPMapValue(m *map[uint]net.IP, sep *string) *uintIPMapValue { + s := &uintIPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintIPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14068,10 +17479,11 @@ func (v *uintIPMapValue) Set(val string) error { return nil } -func (v *uintIPMapValue) Get() interface{} { +func (v *uintIPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14079,6 +17491,7 @@ func (v *uintIPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14090,23 +17503,37 @@ func (v *uintIPMapValue) IsCumulative() bool { // -- uint8IPMapValue. type uint8IPMapValue struct { - value *map[uint8]net.IP + value *map[uint8]net.IP + separator string } -var ( - _ RepeatableFlag = (*uint8IPMapValue)(nil) - _ Value = (*uint8IPMapValue)(nil) - _ Getter = (*uint8IPMapValue)(nil) -) +var _ RepeatableFlag = (*uint8IPMapValue)(nil) +var _ Value = (*uint8IPMapValue)(nil) +var _ Getter = (*uint8IPMapValue)(nil) -func newUint8IPMapValue(m *map[uint8]net.IP) *uint8IPMapValue { - return &uint8IPMapValue{ +func newUint8IPMapValue(m *map[uint8]net.IP, sep *string) *uint8IPMapValue { + s := &uint8IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14138,10 +17565,11 @@ func (v *uint8IPMapValue) Set(val string) error { return nil } -func (v *uint8IPMapValue) Get() interface{} { +func (v *uint8IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14149,6 +17577,7 @@ func (v *uint8IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14160,23 +17589,37 @@ func (v *uint8IPMapValue) IsCumulative() bool { // -- uint16IPMapValue. type uint16IPMapValue struct { - value *map[uint16]net.IP + value *map[uint16]net.IP + separator string } -var ( - _ RepeatableFlag = (*uint16IPMapValue)(nil) - _ Value = (*uint16IPMapValue)(nil) - _ Getter = (*uint16IPMapValue)(nil) -) +var _ RepeatableFlag = (*uint16IPMapValue)(nil) +var _ Value = (*uint16IPMapValue)(nil) +var _ Getter = (*uint16IPMapValue)(nil) -func newUint16IPMapValue(m *map[uint16]net.IP) *uint16IPMapValue { - return &uint16IPMapValue{ +func newUint16IPMapValue(m *map[uint16]net.IP, sep *string) *uint16IPMapValue { + s := &uint16IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14208,10 +17651,11 @@ func (v *uint16IPMapValue) Set(val string) error { return nil } -func (v *uint16IPMapValue) Get() interface{} { +func (v *uint16IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14219,6 +17663,7 @@ func (v *uint16IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14230,23 +17675,37 @@ func (v *uint16IPMapValue) IsCumulative() bool { // -- uint32IPMapValue. type uint32IPMapValue struct { - value *map[uint32]net.IP + value *map[uint32]net.IP + separator string } -var ( - _ RepeatableFlag = (*uint32IPMapValue)(nil) - _ Value = (*uint32IPMapValue)(nil) - _ Getter = (*uint32IPMapValue)(nil) -) +var _ RepeatableFlag = (*uint32IPMapValue)(nil) +var _ Value = (*uint32IPMapValue)(nil) +var _ Getter = (*uint32IPMapValue)(nil) -func newUint32IPMapValue(m *map[uint32]net.IP) *uint32IPMapValue { - return &uint32IPMapValue{ +func newUint32IPMapValue(m *map[uint32]net.IP, sep *string) *uint32IPMapValue { + s := &uint32IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14278,10 +17737,11 @@ func (v *uint32IPMapValue) Set(val string) error { return nil } -func (v *uint32IPMapValue) Get() interface{} { +func (v *uint32IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14289,6 +17749,7 @@ func (v *uint32IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14300,23 +17761,37 @@ func (v *uint32IPMapValue) IsCumulative() bool { // -- uint64IPMapValue. type uint64IPMapValue struct { - value *map[uint64]net.IP + value *map[uint64]net.IP + separator string } -var ( - _ RepeatableFlag = (*uint64IPMapValue)(nil) - _ Value = (*uint64IPMapValue)(nil) - _ Getter = (*uint64IPMapValue)(nil) -) +var _ RepeatableFlag = (*uint64IPMapValue)(nil) +var _ Value = (*uint64IPMapValue)(nil) +var _ Getter = (*uint64IPMapValue)(nil) -func newUint64IPMapValue(m *map[uint64]net.IP) *uint64IPMapValue { - return &uint64IPMapValue{ +func newUint64IPMapValue(m *map[uint64]net.IP, sep *string) *uint64IPMapValue { + s := &uint64IPMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64IPMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14348,10 +17823,11 @@ func (v *uint64IPMapValue) Set(val string) error { return nil } -func (v *uint64IPMapValue) Get() interface{} { +func (v *uint64IPMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14359,6 +17835,7 @@ func (v *uint64IPMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14373,35 +17850,42 @@ type hexBytesValue struct { value *HexBytes } -var ( - _ Value = (*hexBytesValue)(nil) - _ Getter = (*hexBytesValue)(nil) -) +var _ Value = (*hexBytesValue)(nil) +var _ Getter = (*hexBytesValue)(nil) func newHexBytesValue(p *HexBytes) *hexBytesValue { return &hexBytesValue{value: p} } func (v *hexBytesValue) Set(s string) error { + parsed, err := hex.DecodeString(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *hexBytesValue) Get() interface{} { +func (v *hexBytesValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *hexBytesValue) String() string { if v != nil && v.value != nil { + return fmt.Sprintf("%x", *v.value) } + return "" } @@ -14410,24 +17894,38 @@ func (v *hexBytesValue) Type() string { return "hexBytes" } // -- HexBytesSlice Value type hexBytesSliceValue struct { - value *[]HexBytes - changed bool + value *[]HexBytes + changed bool + separator string } -var ( - _ RepeatableFlag = (*hexBytesSliceValue)(nil) - _ Value = (*hexBytesSliceValue)(nil) - _ Getter = (*hexBytesSliceValue)(nil) -) +var _ RepeatableFlag = (*hexBytesSliceValue)(nil) +var _ Value = (*hexBytesSliceValue)(nil) +var _ Getter = (*hexBytesSliceValue)(nil) -func newHexBytesSliceValue(slice *[]HexBytes) *hexBytesSliceValue { - return &hexBytesSliceValue{ +func newHexBytesSliceValue(slice *[]HexBytes, sep *string) *hexBytesSliceValue { + s := &hexBytesSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *hexBytesSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]HexBytes, len(ss)) for i, s := range ss { @@ -14435,7 +17933,9 @@ func (v *hexBytesSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -14444,24 +17944,29 @@ func (v *hexBytesSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *hexBytesSliceValue) Get() interface{} { +func (v *hexBytesSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]HexBytes)(nil) } func (v *hexBytesSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newHexBytesValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -14473,23 +17978,37 @@ func (v *hexBytesSliceValue) IsCumulative() bool { // -- stringHexBytesMapValue. type stringHexBytesMapValue struct { - value *map[string]HexBytes + value *map[string]HexBytes + separator string } -var ( - _ RepeatableFlag = (*stringHexBytesMapValue)(nil) - _ Value = (*stringHexBytesMapValue)(nil) - _ Getter = (*stringHexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*stringHexBytesMapValue)(nil) +var _ Value = (*stringHexBytesMapValue)(nil) +var _ Getter = (*stringHexBytesMapValue)(nil) -func newStringHexBytesMapValue(m *map[string]HexBytes) *stringHexBytesMapValue { - return &stringHexBytesMapValue{ +func newStringHexBytesMapValue(m *map[string]HexBytes, sep *string) *stringHexBytesMapValue { + s := &stringHexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringHexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14516,10 +18035,11 @@ func (v *stringHexBytesMapValue) Set(val string) error { return nil } -func (v *stringHexBytesMapValue) Get() interface{} { +func (v *stringHexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14527,6 +18047,7 @@ func (v *stringHexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14538,23 +18059,37 @@ func (v *stringHexBytesMapValue) IsCumulative() bool { // -- intHexBytesMapValue. type intHexBytesMapValue struct { - value *map[int]HexBytes + value *map[int]HexBytes + separator string } -var ( - _ RepeatableFlag = (*intHexBytesMapValue)(nil) - _ Value = (*intHexBytesMapValue)(nil) - _ Getter = (*intHexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*intHexBytesMapValue)(nil) +var _ Value = (*intHexBytesMapValue)(nil) +var _ Getter = (*intHexBytesMapValue)(nil) -func newIntHexBytesMapValue(m *map[int]HexBytes) *intHexBytesMapValue { - return &intHexBytesMapValue{ +func newIntHexBytesMapValue(m *map[int]HexBytes, sep *string) *intHexBytesMapValue { + s := &intHexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intHexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14586,10 +18121,11 @@ func (v *intHexBytesMapValue) Set(val string) error { return nil } -func (v *intHexBytesMapValue) Get() interface{} { +func (v *intHexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14597,6 +18133,7 @@ func (v *intHexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14608,23 +18145,37 @@ func (v *intHexBytesMapValue) IsCumulative() bool { // -- int8HexBytesMapValue. type int8HexBytesMapValue struct { - value *map[int8]HexBytes + value *map[int8]HexBytes + separator string } -var ( - _ RepeatableFlag = (*int8HexBytesMapValue)(nil) - _ Value = (*int8HexBytesMapValue)(nil) - _ Getter = (*int8HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*int8HexBytesMapValue)(nil) +var _ Value = (*int8HexBytesMapValue)(nil) +var _ Getter = (*int8HexBytesMapValue)(nil) -func newInt8HexBytesMapValue(m *map[int8]HexBytes) *int8HexBytesMapValue { - return &int8HexBytesMapValue{ +func newInt8HexBytesMapValue(m *map[int8]HexBytes, sep *string) *int8HexBytesMapValue { + s := &int8HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14656,10 +18207,11 @@ func (v *int8HexBytesMapValue) Set(val string) error { return nil } -func (v *int8HexBytesMapValue) Get() interface{} { +func (v *int8HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14667,6 +18219,7 @@ func (v *int8HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14678,23 +18231,37 @@ func (v *int8HexBytesMapValue) IsCumulative() bool { // -- int16HexBytesMapValue. type int16HexBytesMapValue struct { - value *map[int16]HexBytes + value *map[int16]HexBytes + separator string } -var ( - _ RepeatableFlag = (*int16HexBytesMapValue)(nil) - _ Value = (*int16HexBytesMapValue)(nil) - _ Getter = (*int16HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*int16HexBytesMapValue)(nil) +var _ Value = (*int16HexBytesMapValue)(nil) +var _ Getter = (*int16HexBytesMapValue)(nil) -func newInt16HexBytesMapValue(m *map[int16]HexBytes) *int16HexBytesMapValue { - return &int16HexBytesMapValue{ +func newInt16HexBytesMapValue(m *map[int16]HexBytes, sep *string) *int16HexBytesMapValue { + s := &int16HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14726,10 +18293,11 @@ func (v *int16HexBytesMapValue) Set(val string) error { return nil } -func (v *int16HexBytesMapValue) Get() interface{} { +func (v *int16HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14737,6 +18305,7 @@ func (v *int16HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14748,23 +18317,37 @@ func (v *int16HexBytesMapValue) IsCumulative() bool { // -- int32HexBytesMapValue. type int32HexBytesMapValue struct { - value *map[int32]HexBytes + value *map[int32]HexBytes + separator string } -var ( - _ RepeatableFlag = (*int32HexBytesMapValue)(nil) - _ Value = (*int32HexBytesMapValue)(nil) - _ Getter = (*int32HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*int32HexBytesMapValue)(nil) +var _ Value = (*int32HexBytesMapValue)(nil) +var _ Getter = (*int32HexBytesMapValue)(nil) -func newInt32HexBytesMapValue(m *map[int32]HexBytes) *int32HexBytesMapValue { - return &int32HexBytesMapValue{ +func newInt32HexBytesMapValue(m *map[int32]HexBytes, sep *string) *int32HexBytesMapValue { + s := &int32HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14796,10 +18379,11 @@ func (v *int32HexBytesMapValue) Set(val string) error { return nil } -func (v *int32HexBytesMapValue) Get() interface{} { +func (v *int32HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14807,6 +18391,7 @@ func (v *int32HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14818,23 +18403,37 @@ func (v *int32HexBytesMapValue) IsCumulative() bool { // -- int64HexBytesMapValue. type int64HexBytesMapValue struct { - value *map[int64]HexBytes + value *map[int64]HexBytes + separator string } -var ( - _ RepeatableFlag = (*int64HexBytesMapValue)(nil) - _ Value = (*int64HexBytesMapValue)(nil) - _ Getter = (*int64HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*int64HexBytesMapValue)(nil) +var _ Value = (*int64HexBytesMapValue)(nil) +var _ Getter = (*int64HexBytesMapValue)(nil) -func newInt64HexBytesMapValue(m *map[int64]HexBytes) *int64HexBytesMapValue { - return &int64HexBytesMapValue{ +func newInt64HexBytesMapValue(m *map[int64]HexBytes, sep *string) *int64HexBytesMapValue { + s := &int64HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14866,10 +18465,11 @@ func (v *int64HexBytesMapValue) Set(val string) error { return nil } -func (v *int64HexBytesMapValue) Get() interface{} { +func (v *int64HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14877,6 +18477,7 @@ func (v *int64HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14888,23 +18489,37 @@ func (v *int64HexBytesMapValue) IsCumulative() bool { // -- uintHexBytesMapValue. type uintHexBytesMapValue struct { - value *map[uint]HexBytes + value *map[uint]HexBytes + separator string } -var ( - _ RepeatableFlag = (*uintHexBytesMapValue)(nil) - _ Value = (*uintHexBytesMapValue)(nil) - _ Getter = (*uintHexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*uintHexBytesMapValue)(nil) +var _ Value = (*uintHexBytesMapValue)(nil) +var _ Getter = (*uintHexBytesMapValue)(nil) -func newUintHexBytesMapValue(m *map[uint]HexBytes) *uintHexBytesMapValue { - return &uintHexBytesMapValue{ +func newUintHexBytesMapValue(m *map[uint]HexBytes, sep *string) *uintHexBytesMapValue { + s := &uintHexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintHexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -14936,10 +18551,11 @@ func (v *uintHexBytesMapValue) Set(val string) error { return nil } -func (v *uintHexBytesMapValue) Get() interface{} { +func (v *uintHexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -14947,6 +18563,7 @@ func (v *uintHexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -14958,23 +18575,37 @@ func (v *uintHexBytesMapValue) IsCumulative() bool { // -- uint8HexBytesMapValue. type uint8HexBytesMapValue struct { - value *map[uint8]HexBytes + value *map[uint8]HexBytes + separator string } -var ( - _ RepeatableFlag = (*uint8HexBytesMapValue)(nil) - _ Value = (*uint8HexBytesMapValue)(nil) - _ Getter = (*uint8HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*uint8HexBytesMapValue)(nil) +var _ Value = (*uint8HexBytesMapValue)(nil) +var _ Getter = (*uint8HexBytesMapValue)(nil) -func newUint8HexBytesMapValue(m *map[uint8]HexBytes) *uint8HexBytesMapValue { - return &uint8HexBytesMapValue{ +func newUint8HexBytesMapValue(m *map[uint8]HexBytes, sep *string) *uint8HexBytesMapValue { + s := &uint8HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15006,10 +18637,11 @@ func (v *uint8HexBytesMapValue) Set(val string) error { return nil } -func (v *uint8HexBytesMapValue) Get() interface{} { +func (v *uint8HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15017,6 +18649,7 @@ func (v *uint8HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15028,23 +18661,37 @@ func (v *uint8HexBytesMapValue) IsCumulative() bool { // -- uint16HexBytesMapValue. type uint16HexBytesMapValue struct { - value *map[uint16]HexBytes + value *map[uint16]HexBytes + separator string } -var ( - _ RepeatableFlag = (*uint16HexBytesMapValue)(nil) - _ Value = (*uint16HexBytesMapValue)(nil) - _ Getter = (*uint16HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*uint16HexBytesMapValue)(nil) +var _ Value = (*uint16HexBytesMapValue)(nil) +var _ Getter = (*uint16HexBytesMapValue)(nil) -func newUint16HexBytesMapValue(m *map[uint16]HexBytes) *uint16HexBytesMapValue { - return &uint16HexBytesMapValue{ +func newUint16HexBytesMapValue(m *map[uint16]HexBytes, sep *string) *uint16HexBytesMapValue { + s := &uint16HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15076,10 +18723,11 @@ func (v *uint16HexBytesMapValue) Set(val string) error { return nil } -func (v *uint16HexBytesMapValue) Get() interface{} { +func (v *uint16HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15087,6 +18735,7 @@ func (v *uint16HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15098,23 +18747,37 @@ func (v *uint16HexBytesMapValue) IsCumulative() bool { // -- uint32HexBytesMapValue. type uint32HexBytesMapValue struct { - value *map[uint32]HexBytes + value *map[uint32]HexBytes + separator string } -var ( - _ RepeatableFlag = (*uint32HexBytesMapValue)(nil) - _ Value = (*uint32HexBytesMapValue)(nil) - _ Getter = (*uint32HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*uint32HexBytesMapValue)(nil) +var _ Value = (*uint32HexBytesMapValue)(nil) +var _ Getter = (*uint32HexBytesMapValue)(nil) -func newUint32HexBytesMapValue(m *map[uint32]HexBytes) *uint32HexBytesMapValue { - return &uint32HexBytesMapValue{ +func newUint32HexBytesMapValue(m *map[uint32]HexBytes, sep *string) *uint32HexBytesMapValue { + s := &uint32HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15146,10 +18809,11 @@ func (v *uint32HexBytesMapValue) Set(val string) error { return nil } -func (v *uint32HexBytesMapValue) Get() interface{} { +func (v *uint32HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15157,6 +18821,7 @@ func (v *uint32HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15168,23 +18833,37 @@ func (v *uint32HexBytesMapValue) IsCumulative() bool { // -- uint64HexBytesMapValue. type uint64HexBytesMapValue struct { - value *map[uint64]HexBytes + value *map[uint64]HexBytes + separator string } -var ( - _ RepeatableFlag = (*uint64HexBytesMapValue)(nil) - _ Value = (*uint64HexBytesMapValue)(nil) - _ Getter = (*uint64HexBytesMapValue)(nil) -) +var _ RepeatableFlag = (*uint64HexBytesMapValue)(nil) +var _ Value = (*uint64HexBytesMapValue)(nil) +var _ Getter = (*uint64HexBytesMapValue)(nil) -func newUint64HexBytesMapValue(m *map[uint64]HexBytes) *uint64HexBytesMapValue { - return &uint64HexBytesMapValue{ +func newUint64HexBytesMapValue(m *map[uint64]HexBytes, sep *string) *uint64HexBytesMapValue { + s := &uint64HexBytesMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64HexBytesMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15216,10 +18895,11 @@ func (v *uint64HexBytesMapValue) Set(val string) error { return nil } -func (v *uint64HexBytesMapValue) Get() interface{} { +func (v *uint64HexBytesMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15227,6 +18907,7 @@ func (v *uint64HexBytesMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15241,35 +18922,42 @@ type regexpValue struct { value **regexp.Regexp } -var ( - _ Value = (*regexpValue)(nil) - _ Getter = (*regexpValue)(nil) -) +var _ Value = (*regexpValue)(nil) +var _ Getter = (*regexpValue)(nil) func newRegexpValue(p **regexp.Regexp) *regexpValue { return ®expValue{value: p} } func (v *regexpValue) Set(s string) error { + parsed, err := regexp.Compile(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *regexpValue) Get() interface{} { +func (v *regexpValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *regexpValue) String() string { if v != nil && v.value != nil { + return (**v.value).String() } + return "" } @@ -15278,24 +18966,38 @@ func (v *regexpValue) Type() string { return "regexp" } // -- *regexp.RegexpSlice Value type regexpSliceValue struct { - value *[]*regexp.Regexp - changed bool + value *[]*regexp.Regexp + changed bool + separator string } -var ( - _ RepeatableFlag = (*regexpSliceValue)(nil) - _ Value = (*regexpSliceValue)(nil) - _ Getter = (*regexpSliceValue)(nil) -) +var _ RepeatableFlag = (*regexpSliceValue)(nil) +var _ Value = (*regexpSliceValue)(nil) +var _ Getter = (*regexpSliceValue)(nil) -func newRegexpSliceValue(slice *[]*regexp.Regexp) *regexpSliceValue { - return ®expSliceValue{ +func newRegexpSliceValue(slice *[]*regexp.Regexp, sep *string) *regexpSliceValue { + s := ®expSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } -func (v *regexpSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") +func (v *regexpSliceValue) Set(raw string) error { + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]*regexp.Regexp, len(ss)) for i, s := range ss { @@ -15303,7 +19005,9 @@ func (v *regexpSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -15312,24 +19016,29 @@ func (v *regexpSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *regexpSliceValue) Get() interface{} { +func (v *regexpSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]*regexp.Regexp)(nil) } func (v *regexpSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newRegexpValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -15341,23 +19050,37 @@ func (v *regexpSliceValue) IsCumulative() bool { // -- stringRegexpMapValue. type stringRegexpMapValue struct { - value *map[string]*regexp.Regexp + value *map[string]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*stringRegexpMapValue)(nil) - _ Value = (*stringRegexpMapValue)(nil) - _ Getter = (*stringRegexpMapValue)(nil) -) +var _ RepeatableFlag = (*stringRegexpMapValue)(nil) +var _ Value = (*stringRegexpMapValue)(nil) +var _ Getter = (*stringRegexpMapValue)(nil) -func newStringRegexpMapValue(m *map[string]*regexp.Regexp) *stringRegexpMapValue { - return &stringRegexpMapValue{ +func newStringRegexpMapValue(m *map[string]*regexp.Regexp, sep *string) *stringRegexpMapValue { + s := &stringRegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringRegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15384,10 +19107,11 @@ func (v *stringRegexpMapValue) Set(val string) error { return nil } -func (v *stringRegexpMapValue) Get() interface{} { +func (v *stringRegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15395,6 +19119,7 @@ func (v *stringRegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15406,23 +19131,37 @@ func (v *stringRegexpMapValue) IsCumulative() bool { // -- intRegexpMapValue. type intRegexpMapValue struct { - value *map[int]*regexp.Regexp + value *map[int]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*intRegexpMapValue)(nil) - _ Value = (*intRegexpMapValue)(nil) - _ Getter = (*intRegexpMapValue)(nil) -) +var _ RepeatableFlag = (*intRegexpMapValue)(nil) +var _ Value = (*intRegexpMapValue)(nil) +var _ Getter = (*intRegexpMapValue)(nil) -func newIntRegexpMapValue(m *map[int]*regexp.Regexp) *intRegexpMapValue { - return &intRegexpMapValue{ +func newIntRegexpMapValue(m *map[int]*regexp.Regexp, sep *string) *intRegexpMapValue { + s := &intRegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intRegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15454,10 +19193,11 @@ func (v *intRegexpMapValue) Set(val string) error { return nil } -func (v *intRegexpMapValue) Get() interface{} { +func (v *intRegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15465,6 +19205,7 @@ func (v *intRegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15476,23 +19217,37 @@ func (v *intRegexpMapValue) IsCumulative() bool { // -- int8RegexpMapValue. type int8RegexpMapValue struct { - value *map[int8]*regexp.Regexp + value *map[int8]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*int8RegexpMapValue)(nil) - _ Value = (*int8RegexpMapValue)(nil) - _ Getter = (*int8RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*int8RegexpMapValue)(nil) +var _ Value = (*int8RegexpMapValue)(nil) +var _ Getter = (*int8RegexpMapValue)(nil) -func newInt8RegexpMapValue(m *map[int8]*regexp.Regexp) *int8RegexpMapValue { - return &int8RegexpMapValue{ +func newInt8RegexpMapValue(m *map[int8]*regexp.Regexp, sep *string) *int8RegexpMapValue { + s := &int8RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15524,10 +19279,11 @@ func (v *int8RegexpMapValue) Set(val string) error { return nil } -func (v *int8RegexpMapValue) Get() interface{} { +func (v *int8RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15535,6 +19291,7 @@ func (v *int8RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15546,23 +19303,37 @@ func (v *int8RegexpMapValue) IsCumulative() bool { // -- int16RegexpMapValue. type int16RegexpMapValue struct { - value *map[int16]*regexp.Regexp + value *map[int16]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*int16RegexpMapValue)(nil) - _ Value = (*int16RegexpMapValue)(nil) - _ Getter = (*int16RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*int16RegexpMapValue)(nil) +var _ Value = (*int16RegexpMapValue)(nil) +var _ Getter = (*int16RegexpMapValue)(nil) -func newInt16RegexpMapValue(m *map[int16]*regexp.Regexp) *int16RegexpMapValue { - return &int16RegexpMapValue{ +func newInt16RegexpMapValue(m *map[int16]*regexp.Regexp, sep *string) *int16RegexpMapValue { + s := &int16RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15594,10 +19365,11 @@ func (v *int16RegexpMapValue) Set(val string) error { return nil } -func (v *int16RegexpMapValue) Get() interface{} { +func (v *int16RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15605,6 +19377,7 @@ func (v *int16RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15616,23 +19389,37 @@ func (v *int16RegexpMapValue) IsCumulative() bool { // -- int32RegexpMapValue. type int32RegexpMapValue struct { - value *map[int32]*regexp.Regexp + value *map[int32]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*int32RegexpMapValue)(nil) - _ Value = (*int32RegexpMapValue)(nil) - _ Getter = (*int32RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*int32RegexpMapValue)(nil) +var _ Value = (*int32RegexpMapValue)(nil) +var _ Getter = (*int32RegexpMapValue)(nil) -func newInt32RegexpMapValue(m *map[int32]*regexp.Regexp) *int32RegexpMapValue { - return &int32RegexpMapValue{ +func newInt32RegexpMapValue(m *map[int32]*regexp.Regexp, sep *string) *int32RegexpMapValue { + s := &int32RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15664,10 +19451,11 @@ func (v *int32RegexpMapValue) Set(val string) error { return nil } -func (v *int32RegexpMapValue) Get() interface{} { +func (v *int32RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15675,6 +19463,7 @@ func (v *int32RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15686,23 +19475,37 @@ func (v *int32RegexpMapValue) IsCumulative() bool { // -- int64RegexpMapValue. type int64RegexpMapValue struct { - value *map[int64]*regexp.Regexp + value *map[int64]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*int64RegexpMapValue)(nil) - _ Value = (*int64RegexpMapValue)(nil) - _ Getter = (*int64RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*int64RegexpMapValue)(nil) +var _ Value = (*int64RegexpMapValue)(nil) +var _ Getter = (*int64RegexpMapValue)(nil) -func newInt64RegexpMapValue(m *map[int64]*regexp.Regexp) *int64RegexpMapValue { - return &int64RegexpMapValue{ +func newInt64RegexpMapValue(m *map[int64]*regexp.Regexp, sep *string) *int64RegexpMapValue { + s := &int64RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15734,10 +19537,11 @@ func (v *int64RegexpMapValue) Set(val string) error { return nil } -func (v *int64RegexpMapValue) Get() interface{} { +func (v *int64RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15745,6 +19549,7 @@ func (v *int64RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15756,23 +19561,37 @@ func (v *int64RegexpMapValue) IsCumulative() bool { // -- uintRegexpMapValue. type uintRegexpMapValue struct { - value *map[uint]*regexp.Regexp + value *map[uint]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*uintRegexpMapValue)(nil) - _ Value = (*uintRegexpMapValue)(nil) - _ Getter = (*uintRegexpMapValue)(nil) -) +var _ RepeatableFlag = (*uintRegexpMapValue)(nil) +var _ Value = (*uintRegexpMapValue)(nil) +var _ Getter = (*uintRegexpMapValue)(nil) -func newUintRegexpMapValue(m *map[uint]*regexp.Regexp) *uintRegexpMapValue { - return &uintRegexpMapValue{ +func newUintRegexpMapValue(m *map[uint]*regexp.Regexp, sep *string) *uintRegexpMapValue { + s := &uintRegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintRegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15804,10 +19623,11 @@ func (v *uintRegexpMapValue) Set(val string) error { return nil } -func (v *uintRegexpMapValue) Get() interface{} { +func (v *uintRegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15815,6 +19635,7 @@ func (v *uintRegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15826,23 +19647,37 @@ func (v *uintRegexpMapValue) IsCumulative() bool { // -- uint8RegexpMapValue. type uint8RegexpMapValue struct { - value *map[uint8]*regexp.Regexp + value *map[uint8]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*uint8RegexpMapValue)(nil) - _ Value = (*uint8RegexpMapValue)(nil) - _ Getter = (*uint8RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*uint8RegexpMapValue)(nil) +var _ Value = (*uint8RegexpMapValue)(nil) +var _ Getter = (*uint8RegexpMapValue)(nil) -func newUint8RegexpMapValue(m *map[uint8]*regexp.Regexp) *uint8RegexpMapValue { - return &uint8RegexpMapValue{ +func newUint8RegexpMapValue(m *map[uint8]*regexp.Regexp, sep *string) *uint8RegexpMapValue { + s := &uint8RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15874,10 +19709,11 @@ func (v *uint8RegexpMapValue) Set(val string) error { return nil } -func (v *uint8RegexpMapValue) Get() interface{} { +func (v *uint8RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15885,6 +19721,7 @@ func (v *uint8RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15896,23 +19733,37 @@ func (v *uint8RegexpMapValue) IsCumulative() bool { // -- uint16RegexpMapValue. type uint16RegexpMapValue struct { - value *map[uint16]*regexp.Regexp + value *map[uint16]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*uint16RegexpMapValue)(nil) - _ Value = (*uint16RegexpMapValue)(nil) - _ Getter = (*uint16RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*uint16RegexpMapValue)(nil) +var _ Value = (*uint16RegexpMapValue)(nil) +var _ Getter = (*uint16RegexpMapValue)(nil) -func newUint16RegexpMapValue(m *map[uint16]*regexp.Regexp) *uint16RegexpMapValue { - return &uint16RegexpMapValue{ +func newUint16RegexpMapValue(m *map[uint16]*regexp.Regexp, sep *string) *uint16RegexpMapValue { + s := &uint16RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -15944,10 +19795,11 @@ func (v *uint16RegexpMapValue) Set(val string) error { return nil } -func (v *uint16RegexpMapValue) Get() interface{} { +func (v *uint16RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -15955,6 +19807,7 @@ func (v *uint16RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -15966,23 +19819,37 @@ func (v *uint16RegexpMapValue) IsCumulative() bool { // -- uint32RegexpMapValue. type uint32RegexpMapValue struct { - value *map[uint32]*regexp.Regexp + value *map[uint32]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*uint32RegexpMapValue)(nil) - _ Value = (*uint32RegexpMapValue)(nil) - _ Getter = (*uint32RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*uint32RegexpMapValue)(nil) +var _ Value = (*uint32RegexpMapValue)(nil) +var _ Getter = (*uint32RegexpMapValue)(nil) -func newUint32RegexpMapValue(m *map[uint32]*regexp.Regexp) *uint32RegexpMapValue { - return &uint32RegexpMapValue{ +func newUint32RegexpMapValue(m *map[uint32]*regexp.Regexp, sep *string) *uint32RegexpMapValue { + s := &uint32RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16014,10 +19881,11 @@ func (v *uint32RegexpMapValue) Set(val string) error { return nil } -func (v *uint32RegexpMapValue) Get() interface{} { +func (v *uint32RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16025,6 +19893,7 @@ func (v *uint32RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16036,23 +19905,37 @@ func (v *uint32RegexpMapValue) IsCumulative() bool { // -- uint64RegexpMapValue. type uint64RegexpMapValue struct { - value *map[uint64]*regexp.Regexp + value *map[uint64]*regexp.Regexp + separator string } -var ( - _ RepeatableFlag = (*uint64RegexpMapValue)(nil) - _ Value = (*uint64RegexpMapValue)(nil) - _ Getter = (*uint64RegexpMapValue)(nil) -) +var _ RepeatableFlag = (*uint64RegexpMapValue)(nil) +var _ Value = (*uint64RegexpMapValue)(nil) +var _ Getter = (*uint64RegexpMapValue)(nil) -func newUint64RegexpMapValue(m *map[uint64]*regexp.Regexp) *uint64RegexpMapValue { - return &uint64RegexpMapValue{ +func newUint64RegexpMapValue(m *map[uint64]*regexp.Regexp, sep *string) *uint64RegexpMapValue { + s := &uint64RegexpMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64RegexpMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16084,10 +19967,11 @@ func (v *uint64RegexpMapValue) Set(val string) error { return nil } -func (v *uint64RegexpMapValue) Get() interface{} { +func (v *uint64RegexpMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16095,6 +19979,7 @@ func (v *uint64RegexpMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16109,35 +19994,42 @@ type tcpAddrValue struct { value *net.TCPAddr } -var ( - _ Value = (*tcpAddrValue)(nil) - _ Getter = (*tcpAddrValue)(nil) -) +var _ Value = (*tcpAddrValue)(nil) +var _ Getter = (*tcpAddrValue)(nil) func newTCPAddrValue(p *net.TCPAddr) *tcpAddrValue { return &tcpAddrValue{value: p} } func (v *tcpAddrValue) Set(s string) error { + parsed, err := parseTCPAddr(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *tcpAddrValue) Get() interface{} { +func (v *tcpAddrValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *tcpAddrValue) String() string { if v != nil && v.value != nil { + return v.value.String() } + return "" } @@ -16146,24 +20038,38 @@ func (v *tcpAddrValue) Type() string { return "tcpAddr" } // -- net.TCPAddrSlice Value type tcpAddrSliceValue struct { - value *[]net.TCPAddr - changed bool + value *[]net.TCPAddr + changed bool + separator string } -var ( - _ RepeatableFlag = (*tcpAddrSliceValue)(nil) - _ Value = (*tcpAddrSliceValue)(nil) - _ Getter = (*tcpAddrSliceValue)(nil) -) +var _ RepeatableFlag = (*tcpAddrSliceValue)(nil) +var _ Value = (*tcpAddrSliceValue)(nil) +var _ Getter = (*tcpAddrSliceValue)(nil) -func newTCPAddrSliceValue(slice *[]net.TCPAddr) *tcpAddrSliceValue { - return &tcpAddrSliceValue{ +func newTCPAddrSliceValue(slice *[]net.TCPAddr, sep *string) *tcpAddrSliceValue { + s := &tcpAddrSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *tcpAddrSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]net.TCPAddr, len(ss)) for i, s := range ss { @@ -16171,7 +20077,9 @@ func (v *tcpAddrSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -16180,24 +20088,29 @@ func (v *tcpAddrSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *tcpAddrSliceValue) Get() interface{} { +func (v *tcpAddrSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]net.TCPAddr)(nil) } func (v *tcpAddrSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newTCPAddrValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -16212,35 +20125,42 @@ type ipNetValue struct { value *net.IPNet } -var ( - _ Value = (*ipNetValue)(nil) - _ Getter = (*ipNetValue)(nil) -) +var _ Value = (*ipNetValue)(nil) +var _ Getter = (*ipNetValue)(nil) func newIPNetValue(p *net.IPNet) *ipNetValue { return &ipNetValue{value: p} } func (v *ipNetValue) Set(s string) error { + parsed, err := parseIPNet(s) if err == nil { + *v.value = parsed + return nil } + return err + } -func (v *ipNetValue) Get() interface{} { +func (v *ipNetValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return nil } func (v *ipNetValue) String() string { if v != nil && v.value != nil { + return v.value.String() } + return "" } @@ -16249,24 +20169,38 @@ func (v *ipNetValue) Type() string { return "ipNet" } // -- net.IPNetSlice Value type ipNetSliceValue struct { - value *[]net.IPNet - changed bool + value *[]net.IPNet + changed bool + separator string } -var ( - _ RepeatableFlag = (*ipNetSliceValue)(nil) - _ Value = (*ipNetSliceValue)(nil) - _ Getter = (*ipNetSliceValue)(nil) -) +var _ RepeatableFlag = (*ipNetSliceValue)(nil) +var _ Value = (*ipNetSliceValue)(nil) +var _ Getter = (*ipNetSliceValue)(nil) -func newIPNetSliceValue(slice *[]net.IPNet) *ipNetSliceValue { - return &ipNetSliceValue{ +func newIPNetSliceValue(slice *[]net.IPNet, sep *string) *ipNetSliceValue { + s := &ipNetSliceValue{ value: slice, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *ipNetSliceValue) Set(raw string) error { - ss := strings.Split(raw, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var ss []string + if separator == "none" { + ss = []string{raw} + } else { + ss = strings.Split(raw, separator) + } out := make([]net.IPNet, len(ss)) for i, s := range ss { @@ -16274,7 +20208,9 @@ func (v *ipNetSliceValue) Set(raw string) error { if err != nil { return err } + out[i] = parsed + } if !v.changed { @@ -16283,24 +20219,29 @@ func (v *ipNetSliceValue) Set(raw string) error { *v.value = append(*v.value, out...) } v.changed = true + return nil } -func (v *ipNetSliceValue) Get() interface{} { +func (v *ipNetSliceValue) Get() any { if v != nil && v.value != nil { + return *v.value } + return ([]net.IPNet)(nil) } func (v *ipNetSliceValue) String() string { if v == nil || v.value == nil { + return "[]" } out := make([]string, 0, len(*v.value)) for _, elem := range *v.value { out = append(out, newIPNetValue(&elem).String()) } + return "[" + strings.Join(out, ",") + "]" } @@ -16312,23 +20253,37 @@ func (v *ipNetSliceValue) IsCumulative() bool { // -- stringIPNetMapValue. type stringIPNetMapValue struct { - value *map[string]net.IPNet + value *map[string]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*stringIPNetMapValue)(nil) - _ Value = (*stringIPNetMapValue)(nil) - _ Getter = (*stringIPNetMapValue)(nil) -) +var _ RepeatableFlag = (*stringIPNetMapValue)(nil) +var _ Value = (*stringIPNetMapValue)(nil) +var _ Getter = (*stringIPNetMapValue)(nil) -func newStringIPNetMapValue(m *map[string]net.IPNet) *stringIPNetMapValue { - return &stringIPNetMapValue{ +func newStringIPNetMapValue(m *map[string]net.IPNet, sep *string) *stringIPNetMapValue { + s := &stringIPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *stringIPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16355,10 +20310,11 @@ func (v *stringIPNetMapValue) Set(val string) error { return nil } -func (v *stringIPNetMapValue) Get() interface{} { +func (v *stringIPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16366,6 +20322,7 @@ func (v *stringIPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16377,23 +20334,37 @@ func (v *stringIPNetMapValue) IsCumulative() bool { // -- intIPNetMapValue. type intIPNetMapValue struct { - value *map[int]net.IPNet + value *map[int]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*intIPNetMapValue)(nil) - _ Value = (*intIPNetMapValue)(nil) - _ Getter = (*intIPNetMapValue)(nil) -) +var _ RepeatableFlag = (*intIPNetMapValue)(nil) +var _ Value = (*intIPNetMapValue)(nil) +var _ Getter = (*intIPNetMapValue)(nil) -func newIntIPNetMapValue(m *map[int]net.IPNet) *intIPNetMapValue { - return &intIPNetMapValue{ +func newIntIPNetMapValue(m *map[int]net.IPNet, sep *string) *intIPNetMapValue { + s := &intIPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *intIPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16425,10 +20396,11 @@ func (v *intIPNetMapValue) Set(val string) error { return nil } -func (v *intIPNetMapValue) Get() interface{} { +func (v *intIPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16436,6 +20408,7 @@ func (v *intIPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16447,23 +20420,37 @@ func (v *intIPNetMapValue) IsCumulative() bool { // -- int8IPNetMapValue. type int8IPNetMapValue struct { - value *map[int8]net.IPNet + value *map[int8]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*int8IPNetMapValue)(nil) - _ Value = (*int8IPNetMapValue)(nil) - _ Getter = (*int8IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*int8IPNetMapValue)(nil) +var _ Value = (*int8IPNetMapValue)(nil) +var _ Getter = (*int8IPNetMapValue)(nil) -func newInt8IPNetMapValue(m *map[int8]net.IPNet) *int8IPNetMapValue { - return &int8IPNetMapValue{ +func newInt8IPNetMapValue(m *map[int8]net.IPNet, sep *string) *int8IPNetMapValue { + s := &int8IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int8IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16495,10 +20482,11 @@ func (v *int8IPNetMapValue) Set(val string) error { return nil } -func (v *int8IPNetMapValue) Get() interface{} { +func (v *int8IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16506,6 +20494,7 @@ func (v *int8IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16517,23 +20506,37 @@ func (v *int8IPNetMapValue) IsCumulative() bool { // -- int16IPNetMapValue. type int16IPNetMapValue struct { - value *map[int16]net.IPNet + value *map[int16]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*int16IPNetMapValue)(nil) - _ Value = (*int16IPNetMapValue)(nil) - _ Getter = (*int16IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*int16IPNetMapValue)(nil) +var _ Value = (*int16IPNetMapValue)(nil) +var _ Getter = (*int16IPNetMapValue)(nil) -func newInt16IPNetMapValue(m *map[int16]net.IPNet) *int16IPNetMapValue { - return &int16IPNetMapValue{ +func newInt16IPNetMapValue(m *map[int16]net.IPNet, sep *string) *int16IPNetMapValue { + s := &int16IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int16IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16565,10 +20568,11 @@ func (v *int16IPNetMapValue) Set(val string) error { return nil } -func (v *int16IPNetMapValue) Get() interface{} { +func (v *int16IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16576,6 +20580,7 @@ func (v *int16IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16587,23 +20592,37 @@ func (v *int16IPNetMapValue) IsCumulative() bool { // -- int32IPNetMapValue. type int32IPNetMapValue struct { - value *map[int32]net.IPNet + value *map[int32]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*int32IPNetMapValue)(nil) - _ Value = (*int32IPNetMapValue)(nil) - _ Getter = (*int32IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*int32IPNetMapValue)(nil) +var _ Value = (*int32IPNetMapValue)(nil) +var _ Getter = (*int32IPNetMapValue)(nil) -func newInt32IPNetMapValue(m *map[int32]net.IPNet) *int32IPNetMapValue { - return &int32IPNetMapValue{ +func newInt32IPNetMapValue(m *map[int32]net.IPNet, sep *string) *int32IPNetMapValue { + s := &int32IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int32IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16635,10 +20654,11 @@ func (v *int32IPNetMapValue) Set(val string) error { return nil } -func (v *int32IPNetMapValue) Get() interface{} { +func (v *int32IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16646,6 +20666,7 @@ func (v *int32IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16657,23 +20678,37 @@ func (v *int32IPNetMapValue) IsCumulative() bool { // -- int64IPNetMapValue. type int64IPNetMapValue struct { - value *map[int64]net.IPNet + value *map[int64]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*int64IPNetMapValue)(nil) - _ Value = (*int64IPNetMapValue)(nil) - _ Getter = (*int64IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*int64IPNetMapValue)(nil) +var _ Value = (*int64IPNetMapValue)(nil) +var _ Getter = (*int64IPNetMapValue)(nil) -func newInt64IPNetMapValue(m *map[int64]net.IPNet) *int64IPNetMapValue { - return &int64IPNetMapValue{ +func newInt64IPNetMapValue(m *map[int64]net.IPNet, sep *string) *int64IPNetMapValue { + s := &int64IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *int64IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16705,10 +20740,11 @@ func (v *int64IPNetMapValue) Set(val string) error { return nil } -func (v *int64IPNetMapValue) Get() interface{} { +func (v *int64IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16716,6 +20752,7 @@ func (v *int64IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16727,23 +20764,37 @@ func (v *int64IPNetMapValue) IsCumulative() bool { // -- uintIPNetMapValue. type uintIPNetMapValue struct { - value *map[uint]net.IPNet + value *map[uint]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*uintIPNetMapValue)(nil) - _ Value = (*uintIPNetMapValue)(nil) - _ Getter = (*uintIPNetMapValue)(nil) -) +var _ RepeatableFlag = (*uintIPNetMapValue)(nil) +var _ Value = (*uintIPNetMapValue)(nil) +var _ Getter = (*uintIPNetMapValue)(nil) -func newUintIPNetMapValue(m *map[uint]net.IPNet) *uintIPNetMapValue { - return &uintIPNetMapValue{ +func newUintIPNetMapValue(m *map[uint]net.IPNet, sep *string) *uintIPNetMapValue { + s := &uintIPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uintIPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16775,10 +20826,11 @@ func (v *uintIPNetMapValue) Set(val string) error { return nil } -func (v *uintIPNetMapValue) Get() interface{} { +func (v *uintIPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16786,6 +20838,7 @@ func (v *uintIPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16797,23 +20850,37 @@ func (v *uintIPNetMapValue) IsCumulative() bool { // -- uint8IPNetMapValue. type uint8IPNetMapValue struct { - value *map[uint8]net.IPNet + value *map[uint8]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*uint8IPNetMapValue)(nil) - _ Value = (*uint8IPNetMapValue)(nil) - _ Getter = (*uint8IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*uint8IPNetMapValue)(nil) +var _ Value = (*uint8IPNetMapValue)(nil) +var _ Getter = (*uint8IPNetMapValue)(nil) -func newUint8IPNetMapValue(m *map[uint8]net.IPNet) *uint8IPNetMapValue { - return &uint8IPNetMapValue{ +func newUint8IPNetMapValue(m *map[uint8]net.IPNet, sep *string) *uint8IPNetMapValue { + s := &uint8IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint8IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16845,10 +20912,11 @@ func (v *uint8IPNetMapValue) Set(val string) error { return nil } -func (v *uint8IPNetMapValue) Get() interface{} { +func (v *uint8IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16856,6 +20924,7 @@ func (v *uint8IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16867,23 +20936,37 @@ func (v *uint8IPNetMapValue) IsCumulative() bool { // -- uint16IPNetMapValue. type uint16IPNetMapValue struct { - value *map[uint16]net.IPNet + value *map[uint16]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*uint16IPNetMapValue)(nil) - _ Value = (*uint16IPNetMapValue)(nil) - _ Getter = (*uint16IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*uint16IPNetMapValue)(nil) +var _ Value = (*uint16IPNetMapValue)(nil) +var _ Getter = (*uint16IPNetMapValue)(nil) -func newUint16IPNetMapValue(m *map[uint16]net.IPNet) *uint16IPNetMapValue { - return &uint16IPNetMapValue{ +func newUint16IPNetMapValue(m *map[uint16]net.IPNet, sep *string) *uint16IPNetMapValue { + s := &uint16IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint16IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16915,10 +20998,11 @@ func (v *uint16IPNetMapValue) Set(val string) error { return nil } -func (v *uint16IPNetMapValue) Get() interface{} { +func (v *uint16IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16926,6 +21010,7 @@ func (v *uint16IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -16937,23 +21022,37 @@ func (v *uint16IPNetMapValue) IsCumulative() bool { // -- uint32IPNetMapValue. type uint32IPNetMapValue struct { - value *map[uint32]net.IPNet + value *map[uint32]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*uint32IPNetMapValue)(nil) - _ Value = (*uint32IPNetMapValue)(nil) - _ Getter = (*uint32IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*uint32IPNetMapValue)(nil) +var _ Value = (*uint32IPNetMapValue)(nil) +var _ Getter = (*uint32IPNetMapValue)(nil) -func newUint32IPNetMapValue(m *map[uint32]net.IPNet) *uint32IPNetMapValue { - return &uint32IPNetMapValue{ +func newUint32IPNetMapValue(m *map[uint32]net.IPNet, sep *string) *uint32IPNetMapValue { + s := &uint32IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint32IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -16985,10 +21084,11 @@ func (v *uint32IPNetMapValue) Set(val string) error { return nil } -func (v *uint32IPNetMapValue) Get() interface{} { +func (v *uint32IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -16996,6 +21096,7 @@ func (v *uint32IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } @@ -17007,23 +21108,37 @@ func (v *uint32IPNetMapValue) IsCumulative() bool { // -- uint64IPNetMapValue. type uint64IPNetMapValue struct { - value *map[uint64]net.IPNet + value *map[uint64]net.IPNet + separator string } -var ( - _ RepeatableFlag = (*uint64IPNetMapValue)(nil) - _ Value = (*uint64IPNetMapValue)(nil) - _ Getter = (*uint64IPNetMapValue)(nil) -) +var _ RepeatableFlag = (*uint64IPNetMapValue)(nil) +var _ Value = (*uint64IPNetMapValue)(nil) +var _ Getter = (*uint64IPNetMapValue)(nil) -func newUint64IPNetMapValue(m *map[uint64]net.IPNet) *uint64IPNetMapValue { - return &uint64IPNetMapValue{ +func newUint64IPNetMapValue(m *map[uint64]net.IPNet, sep *string) *uint64IPNetMapValue { + s := &uint64IPNetMapValue{ value: m, } + if sep != nil { + s.separator = *sep + } + + return s } func (v *uint64IPNetMapValue) Set(val string) error { - values := strings.Split(val, ",") + separator := v.separator + if separator == "" { + separator = "," // Default separator + } + + var values []string + if separator == "none" { + values = []string{val} + } else { + values = strings.Split(val, separator) + } for _, s := range values { ss := strings.Split(s, ":") @@ -17055,10 +21170,11 @@ func (v *uint64IPNetMapValue) Set(val string) error { return nil } -func (v *uint64IPNetMapValue) Get() interface{} { +func (v *uint64IPNetMapValue) Get() any { if v != nil && v.value != nil { return *v.value } + return nil } @@ -17066,6 +21182,7 @@ func (v *uint64IPNetMapValue) String() string { if v != nil && v.value != nil && len(*v.value) > 0 { return fmt.Sprintf("%v", *v.value) } + return "" } diff --git a/values_generated_test.go b/internal/values/values_generated_test.go similarity index 75% rename from values_generated_test.go rename to internal/values/values_generated_test.go index 00e4686..b953b37 100644 --- a/values_generated_test.go +++ b/internal/values/values_generated_test.go @@ -1,4 +1,4 @@ -package flags +package values // This file is autogenerated by "go generate .". Do not modify. @@ -14,10 +14,10 @@ import ( func TestStringValue_Zero(t *testing.T) { t.Parallel() nilValue := new(stringValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -27,13 +27,14 @@ func TestStringValue(t *testing.T) { t.Parallel() a := new(string) v := newStringValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("string") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "string", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "string", v.Type()) }) + } func TestStringSliceValue_Zero(t *testing.T) { @@ -49,110 +50,110 @@ func TestStringSliceValue_Zero(t *testing.T) { func TestStringStringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringStringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringStringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntStringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intStringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intStringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintStringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintStringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintStringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64StringMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64StringMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64StringMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -162,17 +163,18 @@ func TestStringSliceValue(t *testing.T) { t.Parallel() var err error a := new([]string) - v := newStringSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newStringSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("val1,val2") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("val3,val4") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[val1,val2,val3,val4]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "stringSlice", v.Type()) }) + } func TestStringStringMapValue(t *testing.T) { @@ -181,17 +183,17 @@ func TestStringStringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]string) - v := newStringStringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringStringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("XVlBzval1") + err = v.Set("QaEQNval1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("gbaiC:val1") - assert.Nil(t, err) - err = v.Set("MRAjWval2") + err = v.Set("HtFoP:val1") + assert.NoError(t, err) + err = v.Set("yXMXqval2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("whTHc:val2") - assert.Nil(t, err) + err = v.Set("NRXsf:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -200,13 +202,13 @@ func TestStringStringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]string) - v := newStringStringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringStringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("tcuAx") + err = v.Set("jXDfc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("hxKQF:") - assert.Nil(t, err) + err = v.Set("JOQHf:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -219,21 +221,21 @@ func TestIntStringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]string) - v := newIntStringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntStringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5val1") + err = v.Set("1val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("0:val1") - assert.Nil(t, err) - err = v.Set("3val2") + assert.Error(t, err) + err = v.Set("3:val1") + assert.NoError(t, err) + err = v.Set("1val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("7:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -242,15 +244,15 @@ func TestIntStringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]string) - v := newIntStringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntStringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("4:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -263,21 +265,21 @@ func TestInt8StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]string) - v := newInt8StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1val1") + err = v.Set("7val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("7:val1") - assert.Nil(t, err) - err = v.Set("5val2") + assert.Error(t, err) + err = v.Set("1:val1") + assert.NoError(t, err) + err = v.Set("4val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("2:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -286,15 +288,15 @@ func TestInt8StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]string) - v := newInt8StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("2:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -307,21 +309,21 @@ func TestInt16StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]string) - v := newInt16StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2val1") + err = v.Set("3val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("3:val1") - assert.Nil(t, err) - err = v.Set("1val2") + assert.Error(t, err) + err = v.Set("4:val1") + assert.NoError(t, err) + err = v.Set("2val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("3:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -330,15 +332,15 @@ func TestInt16StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]string) - v := newInt16StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6") + err = v.Set("0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("4:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -351,21 +353,21 @@ func TestInt32StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]string) - v := newInt32StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7val1") + err = v.Set("4val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("1:val1") - assert.Nil(t, err) - err = v.Set("5val2") + assert.Error(t, err) + err = v.Set("6:val1") + assert.NoError(t, err) + err = v.Set("7val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("1:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -374,15 +376,15 @@ func TestInt32StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]string) - v := newInt32StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5") + err = v.Set("6") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -395,21 +397,21 @@ func TestInt64StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]string) - v := newInt64StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0val1") + err = v.Set("5val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("1:val1") - assert.Nil(t, err) - err = v.Set("0val2") + assert.Error(t, err) + err = v.Set("5:val1") + assert.NoError(t, err) + err = v.Set("1val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("2:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -418,15 +420,15 @@ func TestInt64StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]string) - v := newInt64StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7") + err = v.Set("5") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("3:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -439,21 +441,21 @@ func TestUintStringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]string) - v := newUintStringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintStringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3val1") + err = v.Set("0val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("6:val1") - assert.Nil(t, err) - err = v.Set("5val2") + assert.Error(t, err) + err = v.Set("0:val1") + assert.NoError(t, err) + err = v.Set("6val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("4:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -462,15 +464,15 @@ func TestUintStringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]string) - v := newUintStringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintStringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2") + err = v.Set("1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -483,21 +485,21 @@ func TestUint8StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]string) - v := newUint8StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1val1") + err = v.Set("2val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("2:val1") - assert.Nil(t, err) - err = v.Set("7val2") + assert.Error(t, err) + err = v.Set("6:val1") + assert.NoError(t, err) + err = v.Set("2val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("2:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -506,15 +508,15 @@ func TestUint8StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]string) - v := newUint8StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3") + err = v.Set("2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("0:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -527,21 +529,21 @@ func TestUint16StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]string) - v := newUint16StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2val1") + err = v.Set("5val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("6:val1") - assert.Nil(t, err) - err = v.Set("7val2") + assert.NoError(t, err) + err = v.Set("5val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("6:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -550,15 +552,15 @@ func TestUint16StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]string) - v := newUint16StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1") + err = v.Set("0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("7:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -571,21 +573,21 @@ func TestUint32StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]string) - v := newUint32StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4val1") + err = v.Set("7val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("4:val1") - assert.Nil(t, err) - err = v.Set("7val2") + assert.Error(t, err) + err = v.Set("3:val1") + assert.NoError(t, err) + err = v.Set("6val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("1:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -594,15 +596,15 @@ func TestUint32StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]string) - v := newUint32StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1") + err = v.Set("0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -615,21 +617,21 @@ func TestUint64StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]string) - v := newUint64StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1val1") + err = v.Set("2val1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val1") - assert.NotNil(t, err) - err = v.Set("3:val1") - assert.Nil(t, err) - err = v.Set("1val2") + assert.Error(t, err) + err = v.Set("2:val1") + assert.NoError(t, err) + err = v.Set("5val2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":val2") - assert.NotNil(t, err) - err = v.Set("3:val2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:val2") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -638,15 +640,15 @@ func TestUint64StringMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]string) - v := newUint64StringMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64StringMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3") + err = v.Set("1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":") - assert.NotNil(t, err) - err = v.Set("2:") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]string", v.Type()) assert.NotEmpty(t, v.String()) @@ -656,10 +658,10 @@ func TestUint64StringMapValue(t *testing.T) { func TestBoolValue_Zero(t *testing.T) { t.Parallel() nilValue := new(boolValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*boolValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -669,9 +671,9 @@ func TestBoolValue(t *testing.T) { t.Parallel() a := new(bool) v := newBoolValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("true") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "true", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "bool", v.Type()) @@ -680,9 +682,9 @@ func TestBoolValue(t *testing.T) { t.Parallel() a := new(bool) v := newBoolValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("false") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "false", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "bool", v.Type()) @@ -691,9 +693,9 @@ func TestBoolValue(t *testing.T) { t.Parallel() a := new(bool) v := newBoolValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "true", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "bool", v.Type()) @@ -702,9 +704,9 @@ func TestBoolValue(t *testing.T) { t.Parallel() a := new(bool) v := newBoolValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "false", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "bool", v.Type()) @@ -713,13 +715,14 @@ func TestBoolValue(t *testing.T) { t.Parallel() a := new(bool) v := newBoolValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, "false", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "bool", v.Type()) }) + } func TestBoolSliceValue_Zero(t *testing.T) { @@ -735,110 +738,110 @@ func TestBoolSliceValue_Zero(t *testing.T) { func TestStringBoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringBoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringBoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntBoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intBoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intBoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintBoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintBoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintBoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64BoolMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64BoolMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64BoolMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -848,13 +851,13 @@ func TestBoolSliceValue(t *testing.T) { t.Parallel() var err error a := new([]bool) - v := newBoolSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newBoolSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("true,false") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("true") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[true,false,true]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "boolSlice", v.Type()) @@ -863,8 +866,8 @@ func TestBoolSliceValue(t *testing.T) { t.Parallel() var err error a := new([]bool) - v := newBoolSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newBoolSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("true,unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") @@ -872,6 +875,7 @@ func TestBoolSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "boolSlice", v.Type()) }) + } func TestStringBoolMapValue(t *testing.T) { @@ -880,17 +884,17 @@ func TestStringBoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]bool) - v := newStringBoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringBoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("gmotatrue") + err = v.Set("xeJortrue") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("FetHs:true") - assert.Nil(t, err) - err = v.Set("bZRjxfalse") + err = v.Set("yFUJA:true") + assert.NoError(t, err) + err = v.Set("CBJtJfalse") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("Awnwe:false") - assert.Nil(t, err) + err = v.Set("leCtA:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -899,12 +903,12 @@ func TestStringBoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]bool) - v := newStringBoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringBoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("krBEmunexpected") + err = v.Set("BzlBHunexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("fdzdc:unexpected") + err = v.Set("cLBRj:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]bool", v.Type()) @@ -918,21 +922,21 @@ func TestIntBoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]bool) - v := newIntBoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntBoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6true") + err = v.Set("5true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("2:true") - assert.Nil(t, err) - err = v.Set("5false") + assert.Error(t, err) + err = v.Set("4:true") + assert.NoError(t, err) + err = v.Set("3false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("7:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -941,14 +945,14 @@ func TestIntBoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]bool) - v := newIntBoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntBoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2unexpected") + err = v.Set("3unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("6:unexpected") + assert.Error(t, err) + err = v.Set("3:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]bool", v.Type()) @@ -962,21 +966,21 @@ func TestInt8BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]bool) - v := newInt8BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5true") + err = v.Set("3true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("6:true") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:true") + assert.NoError(t, err) err = v.Set("3false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("5:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -985,14 +989,14 @@ func TestInt8BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]bool) - v := newInt8BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4unexpected") + err = v.Set("1unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("7:unexpected") + assert.Error(t, err) + err = v.Set("4:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]bool", v.Type()) @@ -1006,21 +1010,21 @@ func TestInt16BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]bool) - v := newInt16BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5true") + err = v.Set("4true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("6:true") - assert.Nil(t, err) - err = v.Set("3false") + assert.Error(t, err) + err = v.Set("7:true") + assert.NoError(t, err) + err = v.Set("2false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("5:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1029,14 +1033,14 @@ func TestInt16BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]bool) - v := newInt16BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0unexpected") + err = v.Set("3unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("2:unexpected") + assert.Error(t, err) + err = v.Set("6:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]bool", v.Type()) @@ -1050,21 +1054,21 @@ func TestInt32BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]bool) - v := newInt32BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0true") + err = v.Set("1true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:true") - assert.Nil(t, err) - err = v.Set("0false") + assert.NoError(t, err) + err = v.Set("5false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:false") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1073,14 +1077,14 @@ func TestInt32BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]bool) - v := newInt32BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4unexpected") + err = v.Set("6unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("4:unexpected") + assert.Error(t, err) + err = v.Set("2:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]bool", v.Type()) @@ -1094,21 +1098,21 @@ func TestInt64BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]bool) - v := newInt64BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0true") + err = v.Set("2true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("7:true") - assert.Nil(t, err) - err = v.Set("4false") + assert.Error(t, err) + err = v.Set("2:true") + assert.NoError(t, err) + err = v.Set("0false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:false") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1117,14 +1121,14 @@ func TestInt64BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]bool) - v := newInt64BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3unexpected") + err = v.Set("4unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("4:unexpected") + assert.Error(t, err) + err = v.Set("7:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]bool", v.Type()) @@ -1138,21 +1142,21 @@ func TestUintBoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]bool) - v := newUintBoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintBoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0true") + err = v.Set("5true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("7:true") - assert.Nil(t, err) - err = v.Set("4false") + assert.Error(t, err) + err = v.Set("2:true") + assert.NoError(t, err) + err = v.Set("7false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("4:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1161,14 +1165,14 @@ func TestUintBoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]bool) - v := newUintBoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintBoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1unexpected") + err = v.Set("5unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("7:unexpected") + assert.Error(t, err) + err = v.Set("0:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]bool", v.Type()) @@ -1182,21 +1186,21 @@ func TestUint8BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]bool) - v := newUint8BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1true") + err = v.Set("4true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("2:true") - assert.Nil(t, err) - err = v.Set("2false") + assert.Error(t, err) + err = v.Set("6:true") + assert.NoError(t, err) + err = v.Set("3false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("2:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1205,14 +1209,14 @@ func TestUint8BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]bool) - v := newUint8BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("7unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("7:unexpected") + assert.Error(t, err) + err = v.Set("6:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]bool", v.Type()) @@ -1226,21 +1230,21 @@ func TestUint16BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]bool) - v := newUint16BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2true") + err = v.Set("4true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("2:true") - assert.Nil(t, err) - err = v.Set("6false") + assert.Error(t, err) + err = v.Set("4:true") + assert.NoError(t, err) + err = v.Set("4false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("7:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1249,14 +1253,14 @@ func TestUint16BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]bool) - v := newUint16BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6unexpected") + err = v.Set("1unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("0:unexpected") + assert.Error(t, err) + err = v.Set("6:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]bool", v.Type()) @@ -1270,21 +1274,21 @@ func TestUint32BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]bool) - v := newUint32BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7true") + err = v.Set("2true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("0:true") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:true") + assert.NoError(t, err) err = v.Set("6false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("6:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1293,13 +1297,13 @@ func TestUint32BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]bool) - v := newUint32BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7unexpected") + err = v.Set("4unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("0:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -1314,21 +1318,21 @@ func TestUint64BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]bool) - v := newUint64BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0true") + err = v.Set("5true") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":true") - assert.NotNil(t, err) - err = v.Set("2:true") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:true") + assert.NoError(t, err) err = v.Set("1false") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":false") - assert.NotNil(t, err) - err = v.Set("7:false") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:false") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]bool", v.Type()) assert.NotEmpty(t, v.String()) @@ -1337,14 +1341,14 @@ func TestUint64BoolMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]bool) - v := newUint64BoolMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64BoolMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3unexpected") + err = v.Set("6unexpected") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":unexpected") - assert.NotNil(t, err) - err = v.Set("7:unexpected") + assert.Error(t, err) + err = v.Set("0:unexpected") assert.EqualError(t, err, "strconv.ParseBool: parsing \"unexpected\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]bool", v.Type()) @@ -1355,10 +1359,10 @@ func TestUint64BoolMapValue(t *testing.T) { func TestUintValue_Zero(t *testing.T) { t.Parallel() nilValue := new(uintValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -1368,9 +1372,9 @@ func TestUintValue(t *testing.T) { t.Parallel() a := new(uint) v := newUintValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("18446744073709551615") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "18446744073709551615", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint", v.Type()) @@ -1379,7 +1383,7 @@ func TestUintValue(t *testing.T) { t.Parallel() a := new(uint) v := newUintValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("18446744073709551616") assert.EqualError(t, err, "strconv.ParseUint: parsing \"18446744073709551616\": value out of range") assert.Equal(t, "0", v.String()) @@ -1390,7 +1394,7 @@ func TestUintValue(t *testing.T) { t.Parallel() a := new(uint) v := newUintValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -1401,13 +1405,14 @@ func TestUintValue(t *testing.T) { t.Parallel() a := new(uint) v := newUintValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseUint: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint", v.Type()) }) + } func TestUintSliceValue_Zero(t *testing.T) { @@ -1423,110 +1428,110 @@ func TestUintSliceValue_Zero(t *testing.T) { func TestStringUintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringUintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringUintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntUintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intUintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intUintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintUintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintUintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintUintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64UintMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64UintMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64UintMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -1536,13 +1541,13 @@ func TestUintSliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint) - v := newUintSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUintSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,0]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uintSlice", v.Type()) @@ -1551,8 +1556,8 @@ func TestUintSliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint) - v := newUintSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUintSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("-1,0") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") @@ -1560,6 +1565,7 @@ func TestUintSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "uintSlice", v.Type()) }) + } func TestStringUintMapValue(t *testing.T) { @@ -1568,17 +1574,17 @@ func TestStringUintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint) - v := newStringUintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("sbOJi10") + err = v.Set("sYEZO10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("FQGZs:10") - assert.Nil(t, err) - err = v.Set("nwTKS20") + err = v.Set("DlnVn:10") + assert.NoError(t, err) + err = v.Set("nOknz20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("mVoiG:20") - assert.Nil(t, err) + err = v.Set("XPjEU:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1587,12 +1593,12 @@ func TestStringUintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint) - v := newStringUintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("LOpbU-1") + err = v.Set("Dnbch-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("OpEdK:-1") + err = v.Set("MCpTy:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint", v.Type()) @@ -1606,21 +1612,21 @@ func TestIntUintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint) - v := newIntUintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1629,14 +1635,14 @@ func TestIntUintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint) - v := newIntUintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint", v.Type()) @@ -1650,21 +1656,21 @@ func TestInt8UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint) - v := newInt8UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1673,14 +1679,14 @@ func TestInt8UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint) - v := newInt8UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("1:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint", v.Type()) @@ -1694,21 +1700,21 @@ func TestInt16UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint) - v := newInt16UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1717,14 +1723,14 @@ func TestInt16UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint) - v := newInt16UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("0-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("6:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint", v.Type()) @@ -1738,21 +1744,21 @@ func TestInt32UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint) - v := newInt32UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1761,14 +1767,14 @@ func TestInt32UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint) - v := newInt32UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint", v.Type()) @@ -1782,21 +1788,21 @@ func TestInt64UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint) - v := newInt64UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1805,13 +1811,13 @@ func TestInt64UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint) - v := newInt64UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2-1") + err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("0:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -1826,21 +1832,21 @@ func TestUintUintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint) - v := newUintUintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1849,14 +1855,14 @@ func TestUintUintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint) - v := newUintUintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint", v.Type()) @@ -1870,21 +1876,21 @@ func TestUint8UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint) - v := newUint8UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("5:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1893,14 +1899,14 @@ func TestUint8UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint) - v := newUint8UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint", v.Type()) @@ -1914,21 +1920,21 @@ func TestUint16UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint) - v := newUint16UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("6:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1937,14 +1943,14 @@ func TestUint16UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint) - v := newUint16UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("6:-1") + assert.Error(t, err) + err = v.Set("1:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint", v.Type()) @@ -1958,21 +1964,21 @@ func TestUint32UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint) - v := newUint32UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("420") - assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("320") + assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -1981,14 +1987,14 @@ func TestUint32UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint) - v := newUint32UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("3:-1") + assert.Error(t, err) + err = v.Set("7:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint", v.Type()) @@ -2002,21 +2008,21 @@ func TestUint64UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint) - v := newUint64UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint", v.Type()) assert.NotEmpty(t, v.String()) @@ -2025,14 +2031,14 @@ func TestUint64UintMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint) - v := newUint64UintMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64UintMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("1:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint", v.Type()) @@ -2043,10 +2049,10 @@ func TestUint64UintMapValue(t *testing.T) { func TestUint8Value_Zero(t *testing.T) { t.Parallel() nilValue := new(uint8Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -2056,9 +2062,9 @@ func TestUint8Value(t *testing.T) { t.Parallel() a := new(uint8) v := newUint8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("255") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "255", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint8", v.Type()) @@ -2067,7 +2073,7 @@ func TestUint8Value(t *testing.T) { t.Parallel() a := new(uint8) v := newUint8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("256") assert.EqualError(t, err, "strconv.ParseUint: parsing \"256\": value out of range") assert.Equal(t, "0", v.String()) @@ -2078,7 +2084,7 @@ func TestUint8Value(t *testing.T) { t.Parallel() a := new(uint8) v := newUint8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -2089,13 +2095,14 @@ func TestUint8Value(t *testing.T) { t.Parallel() a := new(uint8) v := newUint8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseUint: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint8", v.Type()) }) + } func TestUint8SliceValue_Zero(t *testing.T) { @@ -2111,110 +2118,110 @@ func TestUint8SliceValue_Zero(t *testing.T) { func TestStringUint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringUint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringUint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntUint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intUint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intUint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintUint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintUint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintUint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Uint8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Uint8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Uint8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -2224,13 +2231,13 @@ func TestUint8SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint8) - v := newUint8SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint8SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,0]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint8Slice", v.Type()) @@ -2239,8 +2246,8 @@ func TestUint8SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint8) - v := newUint8SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint8SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("-1,0") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") @@ -2248,6 +2255,7 @@ func TestUint8SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint8Slice", v.Type()) }) + } func TestStringUint8MapValue(t *testing.T) { @@ -2256,17 +2264,17 @@ func TestStringUint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint8) - v := newStringUint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("YCOhg10") + err = v.Set("rFZIP10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("HOvgS:10") - assert.Nil(t, err) - err = v.Set("eycJP20") + err = v.Set("Qvcxf:10") + assert.NoError(t, err) + err = v.Set("BnNmb20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("JHYNu:20") - assert.Nil(t, err) + err = v.Set("mOAOx:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2275,12 +2283,12 @@ func TestStringUint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint8) - v := newStringUint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("fNjJh-1") + err = v.Set("OIqpS-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("hjUVR:-1") + err = v.Set("wBOxZ:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint8", v.Type()) @@ -2294,21 +2302,21 @@ func TestIntUint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint8) - v := newIntUint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("510") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2317,14 +2325,14 @@ func TestIntUint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint8) - v := newIntUint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("0:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint8", v.Type()) @@ -2338,21 +2346,21 @@ func TestInt8Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint8) - v := newInt8Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2361,14 +2369,14 @@ func TestInt8Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint8) - v := newInt8Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("3:-1") + assert.Error(t, err) + err = v.Set("7:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint8", v.Type()) @@ -2382,21 +2390,21 @@ func TestInt16Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint8) - v := newInt16Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2405,14 +2413,14 @@ func TestInt16Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint8) - v := newInt16Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("3-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("7:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint8", v.Type()) @@ -2426,21 +2434,21 @@ func TestInt32Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint8) - v := newInt32Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2449,14 +2457,14 @@ func TestInt32Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint8) - v := newInt32Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("4-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint8", v.Type()) @@ -2470,21 +2478,21 @@ func TestInt64Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint8) - v := newInt64Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2493,14 +2501,14 @@ func TestInt64Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint8) - v := newInt64Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("6:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint8", v.Type()) @@ -2514,21 +2522,21 @@ func TestUintUint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint8) - v := newUintUint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2537,13 +2545,13 @@ func TestUintUint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint8) - v := newUintUint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -2558,21 +2566,21 @@ func TestUint8Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint8) - v := newUint8Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2581,14 +2589,14 @@ func TestUint8Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint8) - v := newUint8Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint8", v.Type()) @@ -2602,21 +2610,21 @@ func TestUint16Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint8) - v := newUint16Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2625,14 +2633,14 @@ func TestUint16Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint8) - v := newUint16Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("3-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint8", v.Type()) @@ -2646,21 +2654,21 @@ func TestUint32Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint8) - v := newUint32Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2669,14 +2677,14 @@ func TestUint32Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint8) - v := newUint32Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("1-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint8", v.Type()) @@ -2690,21 +2698,21 @@ func TestUint64Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint8) - v := newUint64Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint8", v.Type()) assert.NotEmpty(t, v.String()) @@ -2713,14 +2721,14 @@ func TestUint64Uint8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint8) - v := newUint64Uint8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("0-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("3:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint8", v.Type()) @@ -2731,10 +2739,10 @@ func TestUint64Uint8MapValue(t *testing.T) { func TestUint16Value_Zero(t *testing.T) { t.Parallel() nilValue := new(uint16Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -2744,9 +2752,9 @@ func TestUint16Value(t *testing.T) { t.Parallel() a := new(uint16) v := newUint16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("65535") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "65535", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint16", v.Type()) @@ -2755,7 +2763,7 @@ func TestUint16Value(t *testing.T) { t.Parallel() a := new(uint16) v := newUint16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("65536") assert.EqualError(t, err, "strconv.ParseUint: parsing \"65536\": value out of range") assert.Equal(t, "0", v.String()) @@ -2766,7 +2774,7 @@ func TestUint16Value(t *testing.T) { t.Parallel() a := new(uint16) v := newUint16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -2777,13 +2785,14 @@ func TestUint16Value(t *testing.T) { t.Parallel() a := new(uint16) v := newUint16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseUint: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint16", v.Type()) }) + } func TestUint16SliceValue_Zero(t *testing.T) { @@ -2799,110 +2808,110 @@ func TestUint16SliceValue_Zero(t *testing.T) { func TestStringUint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringUint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringUint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntUint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intUint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intUint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintUint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintUint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintUint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Uint16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Uint16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Uint16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -2912,13 +2921,13 @@ func TestUint16SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint16) - v := newUint16SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint16SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,0]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint16Slice", v.Type()) @@ -2927,8 +2936,8 @@ func TestUint16SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint16) - v := newUint16SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint16SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("-1,0") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") @@ -2936,6 +2945,7 @@ func TestUint16SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint16Slice", v.Type()) }) + } func TestStringUint16MapValue(t *testing.T) { @@ -2944,17 +2954,17 @@ func TestStringUint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint16) - v := newStringUint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("sdjSG10") + err = v.Set("lUwHd10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("pngCw:10") - assert.Nil(t, err) - err = v.Set("FkDif20") + err = v.Set("WwCRv:10") + assert.NoError(t, err) + err = v.Set("cquJS20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("IBuuf:20") - assert.Nil(t, err) + err = v.Set("ZbBXv:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -2963,12 +2973,12 @@ func TestStringUint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint16) - v := newStringUint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("FMoWd-1") + err = v.Set("OzYvb-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("iTskZ:-1") + err = v.Set("jiVJV:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint16", v.Type()) @@ -2982,21 +2992,21 @@ func TestIntUint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint16) - v := newIntUint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("6:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3005,14 +3015,14 @@ func TestIntUint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint16) - v := newIntUint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("6:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint16", v.Type()) @@ -3026,21 +3036,21 @@ func TestInt8Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint16) - v := newInt8Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3049,14 +3059,14 @@ func TestInt8Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint16) - v := newInt8Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2-1") + err = v.Set("1-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("3:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint16", v.Type()) @@ -3070,21 +3080,21 @@ func TestInt16Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint16) - v := newInt16Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3093,14 +3103,14 @@ func TestInt16Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint16) - v := newInt16Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint16", v.Type()) @@ -3114,21 +3124,21 @@ func TestInt32Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint16) - v := newInt32Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("420") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3137,14 +3147,14 @@ func TestInt32Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint16) - v := newInt32Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("6:-1") + assert.Error(t, err) + err = v.Set("0:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint16", v.Type()) @@ -3158,21 +3168,21 @@ func TestInt64Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint16) - v := newInt64Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3181,14 +3191,14 @@ func TestInt64Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint16) - v := newInt64Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1-1") + err = v.Set("2-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("3:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint16", v.Type()) @@ -3202,21 +3212,21 @@ func TestUintUint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint16) - v := newUintUint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3225,14 +3235,14 @@ func TestUintUint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint16) - v := newUintUint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("3:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint16", v.Type()) @@ -3246,21 +3256,21 @@ func TestUint8Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint16) - v := newUint8Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3269,14 +3279,14 @@ func TestUint8Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint16) - v := newUint8Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1-1") + err = v.Set("4-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("6:-1") + assert.Error(t, err) + err = v.Set("3:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint16", v.Type()) @@ -3290,21 +3300,21 @@ func TestUint16Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint16) - v := newUint16Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3313,14 +3323,14 @@ func TestUint16Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint16) - v := newUint16Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint16", v.Type()) @@ -3334,21 +3344,21 @@ func TestUint32Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint16) - v := newUint32Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3357,14 +3367,14 @@ func TestUint32Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint16) - v := newUint32Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("3:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint16", v.Type()) @@ -3378,21 +3388,21 @@ func TestUint64Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint16) - v := newUint64Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("6:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint16", v.Type()) assert.NotEmpty(t, v.String()) @@ -3401,14 +3411,14 @@ func TestUint64Uint16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint16) - v := newUint64Uint16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("1-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("7:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint16", v.Type()) @@ -3419,10 +3429,10 @@ func TestUint64Uint16MapValue(t *testing.T) { func TestUint32Value_Zero(t *testing.T) { t.Parallel() nilValue := new(uint32Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -3432,9 +3442,9 @@ func TestUint32Value(t *testing.T) { t.Parallel() a := new(uint32) v := newUint32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("4294967295") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "4294967295", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint32", v.Type()) @@ -3443,7 +3453,7 @@ func TestUint32Value(t *testing.T) { t.Parallel() a := new(uint32) v := newUint32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("4294967296") assert.EqualError(t, err, "strconv.ParseUint: parsing \"4294967296\": value out of range") assert.Equal(t, "0", v.String()) @@ -3454,7 +3464,7 @@ func TestUint32Value(t *testing.T) { t.Parallel() a := new(uint32) v := newUint32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -3465,13 +3475,14 @@ func TestUint32Value(t *testing.T) { t.Parallel() a := new(uint32) v := newUint32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseUint: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint32", v.Type()) }) + } func TestUint32SliceValue_Zero(t *testing.T) { @@ -3487,110 +3498,110 @@ func TestUint32SliceValue_Zero(t *testing.T) { func TestStringUint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringUint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringUint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntUint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intUint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intUint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintUint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintUint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintUint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Uint32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Uint32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Uint32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -3600,13 +3611,13 @@ func TestUint32SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint32) - v := newUint32SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint32SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,0]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint32Slice", v.Type()) @@ -3615,8 +3626,8 @@ func TestUint32SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint32) - v := newUint32SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint32SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("-1,0") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") @@ -3624,6 +3635,7 @@ func TestUint32SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint32Slice", v.Type()) }) + } func TestStringUint32MapValue(t *testing.T) { @@ -3632,17 +3644,17 @@ func TestStringUint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint32) - v := newStringUint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("VgzHb10") + err = v.Set("avDvP10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("lmYYt:10") - assert.Nil(t, err) - err = v.Set("EjVgw20") + err = v.Set("nRGFd:10") + assert.NoError(t, err) + err = v.Set("cBZJw20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("fFbbG:20") - assert.Nil(t, err) + err = v.Set("zveMw:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3651,12 +3663,12 @@ func TestStringUint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint32) - v := newStringUint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("Gcnqb-1") + err = v.Set("zoVYE-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("aEREu:-1") + err = v.Set("ftaXX:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint32", v.Type()) @@ -3670,21 +3682,21 @@ func TestIntUint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint32) - v := newIntUint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("720") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3693,14 +3705,14 @@ func TestIntUint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint32) - v := newIntUint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("1-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("1:-1") + assert.Error(t, err) + err = v.Set("3:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint32", v.Type()) @@ -3714,21 +3726,21 @@ func TestInt8Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint32) - v := newInt8Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3737,14 +3749,14 @@ func TestInt8Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint32) - v := newInt8Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("7:-1") + assert.Error(t, err) + err = v.Set("6:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint32", v.Type()) @@ -3758,21 +3770,21 @@ func TestInt16Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint32) - v := newInt16Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3781,14 +3793,14 @@ func TestInt16Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint32) - v := newInt16Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2-1") + err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint32", v.Type()) @@ -3802,21 +3814,21 @@ func TestInt32Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint32) - v := newInt32Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3825,13 +3837,13 @@ func TestInt32Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint32) - v := newInt32Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -3846,21 +3858,21 @@ func TestInt64Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint32) - v := newInt64Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("5:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3869,14 +3881,14 @@ func TestInt64Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint32) - v := newInt64Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7-1") + err = v.Set("4-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("6:-1") + assert.Error(t, err) + err = v.Set("7:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint32", v.Type()) @@ -3890,21 +3902,21 @@ func TestUintUint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint32) - v := newUintUint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3913,14 +3925,14 @@ func TestUintUint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint32) - v := newUintUint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("4:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint32", v.Type()) @@ -3934,21 +3946,21 @@ func TestUint8Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint32) - v := newUint8Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -3957,14 +3969,14 @@ func TestUint8Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint32) - v := newUint8Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint32", v.Type()) @@ -3978,21 +3990,21 @@ func TestUint16Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint32) - v := newUint16Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("510") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -4001,14 +4013,14 @@ func TestUint16Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint32) - v := newUint16Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("0-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("5:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint32", v.Type()) @@ -4022,21 +4034,21 @@ func TestUint32Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint32) - v := newUint32Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -4045,14 +4057,14 @@ func TestUint32Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint32) - v := newUint32Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3-1") + err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("3:-1") + assert.Error(t, err) + err = v.Set("0:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint32", v.Type()) @@ -4066,21 +4078,21 @@ func TestUint64Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint32) - v := newUint64Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("510") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint32", v.Type()) assert.NotEmpty(t, v.String()) @@ -4089,14 +4101,14 @@ func TestUint64Uint32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint32) - v := newUint64Uint32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0-1") + err = v.Set("6-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint32", v.Type()) @@ -4107,10 +4119,10 @@ func TestUint64Uint32MapValue(t *testing.T) { func TestUint64Value_Zero(t *testing.T) { t.Parallel() nilValue := new(uint64Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -4120,9 +4132,9 @@ func TestUint64Value(t *testing.T) { t.Parallel() a := new(uint64) v := newUint64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("18446744073709551615") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "18446744073709551615", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint64", v.Type()) @@ -4131,7 +4143,7 @@ func TestUint64Value(t *testing.T) { t.Parallel() a := new(uint64) v := newUint64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("18446744073709551616") assert.EqualError(t, err, "strconv.ParseUint: parsing \"18446744073709551616\": value out of range") assert.Equal(t, "0", v.String()) @@ -4142,7 +4154,7 @@ func TestUint64Value(t *testing.T) { t.Parallel() a := new(uint64) v := newUint64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -4153,13 +4165,14 @@ func TestUint64Value(t *testing.T) { t.Parallel() a := new(uint64) v := newUint64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseUint: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint64", v.Type()) }) + } func TestUint64SliceValue_Zero(t *testing.T) { @@ -4175,110 +4188,110 @@ func TestUint64SliceValue_Zero(t *testing.T) { func TestStringUint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringUint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringUint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntUint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intUint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intUint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintUint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintUint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintUint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Uint64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Uint64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Uint64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -4288,13 +4301,13 @@ func TestUint64SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint64) - v := newUint64SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint64SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,0]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint64Slice", v.Type()) @@ -4303,8 +4316,8 @@ func TestUint64SliceValue(t *testing.T) { t.Parallel() var err error a := new([]uint64) - v := newUint64SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newUint64SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("-1,0") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") @@ -4312,6 +4325,7 @@ func TestUint64SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "uint64Slice", v.Type()) }) + } func TestStringUint64MapValue(t *testing.T) { @@ -4320,17 +4334,17 @@ func TestStringUint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint64) - v := newStringUint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("Lpruc10") + err = v.Set("xGKvb10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("jiOgj:10") - assert.Nil(t, err) - err = v.Set("hYeVw20") + err = v.Set("ABcnd:10") + assert.NoError(t, err) + err = v.Set("OQdcE20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("BTCML:20") - assert.Nil(t, err) + err = v.Set("IIpvg:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4339,12 +4353,12 @@ func TestStringUint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]uint64) - v := newStringUint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringUint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("frDGX-1") + err = v.Set("ynhsq-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("qwpzw:-1") + err = v.Set("LhrJA:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]uint64", v.Type()) @@ -4358,21 +4372,21 @@ func TestIntUint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint64) - v := newIntUint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4381,14 +4395,14 @@ func TestIntUint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]uint64) - v := newIntUint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntUint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("1:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]uint64", v.Type()) @@ -4402,21 +4416,21 @@ func TestInt8Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint64) - v := newInt8Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4425,14 +4439,14 @@ func TestInt8Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]uint64) - v := newInt8Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("1-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("7:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]uint64", v.Type()) @@ -4446,21 +4460,21 @@ func TestInt16Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint64) - v := newInt16Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4469,14 +4483,14 @@ func TestInt16Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]uint64) - v := newInt16Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("2-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]uint64", v.Type()) @@ -4490,21 +4504,21 @@ func TestInt32Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint64) - v := newInt32Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4513,14 +4527,14 @@ func TestInt32Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]uint64) - v := newInt32Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2-1") + err = v.Set("5-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("6:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]uint64", v.Type()) @@ -4534,21 +4548,21 @@ func TestInt64Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint64) - v := newInt64Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4557,14 +4571,14 @@ func TestInt64Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]uint64) - v := newInt64Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1-1") + err = v.Set("3-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]uint64", v.Type()) @@ -4578,21 +4592,21 @@ func TestUintUint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint64) - v := newUintUint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4601,13 +4615,13 @@ func TestUintUint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]uint64) - v := newUintUint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintUint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1-1") + err = v.Set("0-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -4622,21 +4636,21 @@ func TestUint8Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint64) - v := newUint8Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4645,14 +4659,14 @@ func TestUint8Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]uint64) - v := newUint8Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1-1") + err = v.Set("0-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("2:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]uint64", v.Type()) @@ -4666,21 +4680,21 @@ func TestUint16Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint64) - v := newUint16Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4689,14 +4703,14 @@ func TestUint16Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]uint64) - v := newUint16Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6-1") + err = v.Set("7-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("0:-1") + assert.Error(t, err) + err = v.Set("3:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]uint64", v.Type()) @@ -4710,21 +4724,21 @@ func TestUint32Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint64) - v := newUint32Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4733,14 +4747,14 @@ func TestUint32Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]uint64) - v := newUint32Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4-1") + err = v.Set("2-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("1:-1") + assert.Error(t, err) + err = v.Set("2:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]uint64", v.Type()) @@ -4754,21 +4768,21 @@ func TestUint64Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint64) - v := newUint64Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint64", v.Type()) assert.NotEmpty(t, v.String()) @@ -4777,14 +4791,14 @@ func TestUint64Uint64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]uint64) - v := newUint64Uint64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Uint64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1-1") + err = v.Set("3-1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":-1") - assert.NotNil(t, err) - err = v.Set("4:-1") + assert.Error(t, err) + err = v.Set("5:-1") assert.EqualError(t, err, "strconv.ParseUint: parsing \"-1\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]uint64", v.Type()) @@ -4795,10 +4809,10 @@ func TestUint64Uint64MapValue(t *testing.T) { func TestIntValue_Zero(t *testing.T) { t.Parallel() nilValue := new(intValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -4808,9 +4822,9 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("9223372036854775807") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "9223372036854775807", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int", v.Type()) @@ -4819,9 +4833,9 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-9223372036854775808") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "-9223372036854775808", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int", v.Type()) @@ -4830,9 +4844,9 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("0x10") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "16", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int", v.Type()) @@ -4841,9 +4855,9 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("0210") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "136", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int", v.Type()) @@ -4852,9 +4866,9 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("0710") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "456", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int", v.Type()) @@ -4863,7 +4877,7 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-9223372036854775809") assert.EqualError(t, err, "strconv.ParseInt: parsing \"-9223372036854775809\": value out of range") assert.Equal(t, "0", v.String()) @@ -4874,7 +4888,7 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("9223372036854775808") assert.EqualError(t, err, "strconv.ParseInt: parsing \"9223372036854775808\": value out of range") assert.Equal(t, "0", v.String()) @@ -4885,13 +4899,14 @@ func TestIntValue(t *testing.T) { t.Parallel() a := new(int) v := newIntValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int", v.Type()) }) + } func TestIntSliceValue_Zero(t *testing.T) { @@ -4907,110 +4922,110 @@ func TestIntSliceValue_Zero(t *testing.T) { func TestStringIntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringIntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringIntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntIntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intIntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intIntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintIntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintIntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintIntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64IntMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64IntMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64IntMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -5020,13 +5035,13 @@ func TestIntSliceValue(t *testing.T) { t.Parallel() var err error a := new([]int) - v := newIntSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newIntSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("-1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,-1]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "intSlice", v.Type()) @@ -5035,8 +5050,8 @@ func TestIntSliceValue(t *testing.T) { t.Parallel() var err error a := new([]int) - v := newIntSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newIntSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") @@ -5044,6 +5059,7 @@ func TestIntSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "intSlice", v.Type()) }) + } func TestStringIntMapValue(t *testing.T) { @@ -5052,17 +5068,17 @@ func TestStringIntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int) - v := newStringIntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringIntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("aiIsN10") + err = v.Set("TOhNj10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("BakqS:10") - assert.Nil(t, err) - err = v.Set("wQpOQ20") + err = v.Set("CNYFa:10") + assert.NoError(t, err) + err = v.Set("RQAKJ20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("gNczg:20") - assert.Nil(t, err) + err = v.Set("GzprQ:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5071,12 +5087,12 @@ func TestStringIntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int) - v := newStringIntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringIntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("aczAIa") + err = v.Set("MAQfUa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("nLqLI:a") + err = v.Set("odLkT:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int", v.Type()) @@ -5090,21 +5106,21 @@ func TestIntIntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int) - v := newIntIntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntIntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5113,14 +5129,14 @@ func TestIntIntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int) - v := newIntIntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntIntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int", v.Type()) @@ -5134,21 +5150,21 @@ func TestInt8IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int) - v := newInt8IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5157,14 +5173,14 @@ func TestInt8IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int) - v := newInt8IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int", v.Type()) @@ -5178,21 +5194,21 @@ func TestInt16IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int) - v := newInt16IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5201,14 +5217,14 @@ func TestInt16IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int) - v := newInt16IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int", v.Type()) @@ -5222,21 +5238,21 @@ func TestInt32IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int) - v := newInt32IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5245,14 +5261,14 @@ func TestInt32IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int) - v := newInt32IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("5:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int", v.Type()) @@ -5266,21 +5282,21 @@ func TestInt64IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int) - v := newInt64IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5289,14 +5305,14 @@ func TestInt64IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int) - v := newInt64IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int", v.Type()) @@ -5310,21 +5326,21 @@ func TestUintIntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int) - v := newUintIntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintIntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5333,14 +5349,14 @@ func TestUintIntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int) - v := newUintIntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintIntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int", v.Type()) @@ -5354,21 +5370,21 @@ func TestUint8IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int) - v := newUint8IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5377,14 +5393,14 @@ func TestUint8IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int) - v := newUint8IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("0:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int", v.Type()) @@ -5398,21 +5414,21 @@ func TestUint16IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int) - v := newUint16IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5421,13 +5437,13 @@ func TestUint16IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int) - v := newUint16IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -5442,21 +5458,21 @@ func TestUint32IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int) - v := newUint32IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("220") + err = v.Set(":10") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5465,14 +5481,14 @@ func TestUint32IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int) - v := newUint32IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int", v.Type()) @@ -5486,21 +5502,21 @@ func TestUint64IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int) - v := newUint64IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int", v.Type()) assert.NotEmpty(t, v.String()) @@ -5509,13 +5525,13 @@ func TestUint64IntMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int) - v := newUint64IntMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64IntMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -5527,10 +5543,10 @@ func TestUint64IntMapValue(t *testing.T) { func TestInt8Value_Zero(t *testing.T) { t.Parallel() nilValue := new(int8Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -5540,9 +5556,9 @@ func TestInt8Value(t *testing.T) { t.Parallel() a := new(int8) v := newInt8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("127") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "127", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int8", v.Type()) @@ -5551,9 +5567,9 @@ func TestInt8Value(t *testing.T) { t.Parallel() a := new(int8) v := newInt8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-128") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "-128", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int8", v.Type()) @@ -5562,7 +5578,7 @@ func TestInt8Value(t *testing.T) { t.Parallel() a := new(int8) v := newInt8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-129") assert.EqualError(t, err, "strconv.ParseInt: parsing \"-129\": value out of range") assert.Equal(t, "0", v.String()) @@ -5573,7 +5589,7 @@ func TestInt8Value(t *testing.T) { t.Parallel() a := new(int8) v := newInt8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("128") assert.EqualError(t, err, "strconv.ParseInt: parsing \"128\": value out of range") assert.Equal(t, "0", v.String()) @@ -5584,13 +5600,14 @@ func TestInt8Value(t *testing.T) { t.Parallel() a := new(int8) v := newInt8Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int8", v.Type()) }) + } func TestInt8SliceValue_Zero(t *testing.T) { @@ -5606,110 +5623,110 @@ func TestInt8SliceValue_Zero(t *testing.T) { func TestStringInt8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringInt8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringInt8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntInt8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intInt8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intInt8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintInt8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintInt8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintInt8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Int8MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Int8MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Int8MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -5719,13 +5736,13 @@ func TestInt8SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int8) - v := newInt8SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt8SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("-1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,-1]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int8Slice", v.Type()) @@ -5734,8 +5751,8 @@ func TestInt8SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int8) - v := newInt8SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt8SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") @@ -5743,6 +5760,7 @@ func TestInt8SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "int8Slice", v.Type()) }) + } func TestStringInt8MapValue(t *testing.T) { @@ -5751,17 +5769,17 @@ func TestStringInt8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int8) - v := newStringInt8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("eBZBF10") + err = v.Set("equkl10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("elhXk:10") - assert.Nil(t, err) - err = v.Set("zzfNa20") + err = v.Set("QtgFY:10") + assert.NoError(t, err) + err = v.Set("HVYIO20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("VtAyy:20") - assert.Nil(t, err) + err = v.Set("Sktic:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -5770,12 +5788,12 @@ func TestStringInt8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int8) - v := newStringInt8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("qWzKqa") + err = v.Set("CYJsla") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("QFbuc:a") + err = v.Set("BQglk:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int8", v.Type()) @@ -5789,21 +5807,21 @@ func TestIntInt8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int8) - v := newIntInt8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("720") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -5812,14 +5830,14 @@ func TestIntInt8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int8) - v := newIntInt8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("1a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int8", v.Type()) @@ -5833,21 +5851,21 @@ func TestInt8Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int8) - v := newInt8Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -5856,14 +5874,14 @@ func TestInt8Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int8) - v := newInt8Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("5:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int8", v.Type()) @@ -5877,21 +5895,21 @@ func TestInt16Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int8) - v := newInt16Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -5900,14 +5918,14 @@ func TestInt16Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int8) - v := newInt16Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int8", v.Type()) @@ -5921,21 +5939,21 @@ func TestInt32Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int8) - v := newInt32Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -5944,13 +5962,13 @@ func TestInt32Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int8) - v := newInt32Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -5965,21 +5983,21 @@ func TestInt64Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int8) - v := newInt64Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -5988,14 +6006,14 @@ func TestInt64Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int8) - v := newInt64Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int8", v.Type()) @@ -6009,21 +6027,21 @@ func TestUintInt8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int8) - v := newUintInt8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("020") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -6032,14 +6050,14 @@ func TestUintInt8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int8) - v := newUintInt8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("0:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int8", v.Type()) @@ -6053,21 +6071,21 @@ func TestUint8Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int8) - v := newUint8Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -6076,14 +6094,14 @@ func TestUint8Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int8) - v := newUint8Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("1:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int8", v.Type()) @@ -6097,21 +6115,21 @@ func TestUint16Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int8) - v := newUint16Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -6120,14 +6138,14 @@ func TestUint16Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int8) - v := newUint16Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int8", v.Type()) @@ -6141,21 +6159,21 @@ func TestUint32Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int8) - v := newUint32Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -6164,14 +6182,14 @@ func TestUint32Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int8) - v := newUint32Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("5:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int8", v.Type()) @@ -6185,21 +6203,21 @@ func TestUint64Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int8) - v := newUint64Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int8", v.Type()) assert.NotEmpty(t, v.String()) @@ -6208,14 +6226,14 @@ func TestUint64Int8MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int8) - v := newUint64Int8MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int8MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int8", v.Type()) @@ -6226,10 +6244,10 @@ func TestUint64Int8MapValue(t *testing.T) { func TestInt16Value_Zero(t *testing.T) { t.Parallel() nilValue := new(int16Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -6239,9 +6257,9 @@ func TestInt16Value(t *testing.T) { t.Parallel() a := new(int16) v := newInt16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("32767") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "32767", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int16", v.Type()) @@ -6250,9 +6268,9 @@ func TestInt16Value(t *testing.T) { t.Parallel() a := new(int16) v := newInt16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-32768") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "-32768", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int16", v.Type()) @@ -6261,7 +6279,7 @@ func TestInt16Value(t *testing.T) { t.Parallel() a := new(int16) v := newInt16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-32769") assert.EqualError(t, err, "strconv.ParseInt: parsing \"-32769\": value out of range") assert.Equal(t, "0", v.String()) @@ -6272,7 +6290,7 @@ func TestInt16Value(t *testing.T) { t.Parallel() a := new(int16) v := newInt16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("32768") assert.EqualError(t, err, "strconv.ParseInt: parsing \"32768\": value out of range") assert.Equal(t, "0", v.String()) @@ -6283,13 +6301,14 @@ func TestInt16Value(t *testing.T) { t.Parallel() a := new(int16) v := newInt16Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int16", v.Type()) }) + } func TestInt16SliceValue_Zero(t *testing.T) { @@ -6305,110 +6324,110 @@ func TestInt16SliceValue_Zero(t *testing.T) { func TestStringInt16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringInt16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringInt16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntInt16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intInt16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intInt16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintInt16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintInt16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintInt16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Int16MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Int16MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Int16MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -6418,13 +6437,13 @@ func TestInt16SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int16) - v := newInt16SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt16SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("-1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,-1]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int16Slice", v.Type()) @@ -6433,8 +6452,8 @@ func TestInt16SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int16) - v := newInt16SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt16SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") @@ -6442,6 +6461,7 @@ func TestInt16SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "int16Slice", v.Type()) }) + } func TestStringInt16MapValue(t *testing.T) { @@ -6450,17 +6470,17 @@ func TestStringInt16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int16) - v := newStringInt16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("qcnCT10") + err = v.Set("Zbclu10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("uGZam:10") - assert.Nil(t, err) - err = v.Set("CToZv20") + err = v.Set("sGFSM:10") + assert.NoError(t, err) + err = v.Set("SzWWU20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("PynaE:20") - assert.Nil(t, err) + err = v.Set("rCuRU:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6469,12 +6489,12 @@ func TestStringInt16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int16) - v := newStringInt16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("phIdXa") + err = v.Set("kzwCUa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("aKUaq:a") + err = v.Set("oXNth:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int16", v.Type()) @@ -6488,21 +6508,21 @@ func TestIntInt16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int16) - v := newIntInt16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6511,13 +6531,13 @@ func TestIntInt16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int16) - v := newIntInt16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("1a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -6532,21 +6552,21 @@ func TestInt8Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int16) - v := newInt8Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6555,14 +6575,14 @@ func TestInt8Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int16) - v := newInt8Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("5:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int16", v.Type()) @@ -6576,21 +6596,21 @@ func TestInt16Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int16) - v := newInt16Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("120") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("220") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6599,14 +6619,14 @@ func TestInt16Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int16) - v := newInt16Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int16", v.Type()) @@ -6620,21 +6640,21 @@ func TestInt32Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int16) - v := newInt32Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6643,14 +6663,14 @@ func TestInt32Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int16) - v := newInt32Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int16", v.Type()) @@ -6664,21 +6684,21 @@ func TestInt64Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int16) - v := newInt64Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("6:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("0:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6687,14 +6707,14 @@ func TestInt64Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int16) - v := newInt64Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2a") + err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int16", v.Type()) @@ -6708,21 +6728,21 @@ func TestUintInt16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int16) - v := newUintInt16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6731,13 +6751,13 @@ func TestUintInt16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int16) - v := newUintInt16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -6752,21 +6772,21 @@ func TestUint8Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int16) - v := newUint8Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6775,14 +6795,14 @@ func TestUint8Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int16) - v := newUint8Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("0:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int16", v.Type()) @@ -6796,21 +6816,21 @@ func TestUint16Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int16) - v := newUint16Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("510") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("3:10") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6819,14 +6839,14 @@ func TestUint16Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int16) - v := newUint16Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("1:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int16", v.Type()) @@ -6840,21 +6860,21 @@ func TestUint32Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int16) - v := newUint32Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("5:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6863,14 +6883,14 @@ func TestUint32Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int16) - v := newUint32Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int16", v.Type()) @@ -6884,21 +6904,21 @@ func TestUint64Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int16) - v := newUint64Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int16", v.Type()) assert.NotEmpty(t, v.String()) @@ -6907,14 +6927,14 @@ func TestUint64Int16MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int16) - v := newUint64Int16MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int16MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int16", v.Type()) @@ -6925,10 +6945,10 @@ func TestUint64Int16MapValue(t *testing.T) { func TestInt32Value_Zero(t *testing.T) { t.Parallel() nilValue := new(int32Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -6938,9 +6958,9 @@ func TestInt32Value(t *testing.T) { t.Parallel() a := new(int32) v := newInt32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("2147483647") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "2147483647", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int32", v.Type()) @@ -6949,9 +6969,9 @@ func TestInt32Value(t *testing.T) { t.Parallel() a := new(int32) v := newInt32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-2147483648") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "-2147483648", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int32", v.Type()) @@ -6960,7 +6980,7 @@ func TestInt32Value(t *testing.T) { t.Parallel() a := new(int32) v := newInt32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-2147483649") assert.EqualError(t, err, "strconv.ParseInt: parsing \"-2147483649\": value out of range") assert.Equal(t, "0", v.String()) @@ -6971,7 +6991,7 @@ func TestInt32Value(t *testing.T) { t.Parallel() a := new(int32) v := newInt32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("2147483648") assert.EqualError(t, err, "strconv.ParseInt: parsing \"2147483648\": value out of range") assert.Equal(t, "0", v.String()) @@ -6982,13 +7002,14 @@ func TestInt32Value(t *testing.T) { t.Parallel() a := new(int32) v := newInt32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int32", v.Type()) }) + } func TestInt32SliceValue_Zero(t *testing.T) { @@ -7004,110 +7025,110 @@ func TestInt32SliceValue_Zero(t *testing.T) { func TestStringInt32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringInt32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringInt32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntInt32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intInt32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intInt32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintInt32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintInt32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintInt32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Int32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Int32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Int32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -7117,13 +7138,13 @@ func TestInt32SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int32) - v := newInt32SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt32SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("-1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,-1]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int32Slice", v.Type()) @@ -7132,8 +7153,8 @@ func TestInt32SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int32) - v := newInt32SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt32SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") @@ -7141,6 +7162,7 @@ func TestInt32SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "int32Slice", v.Type()) }) + } func TestStringInt32MapValue(t *testing.T) { @@ -7149,17 +7171,17 @@ func TestStringInt32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int32) - v := newStringInt32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("hGCMd10") + err = v.Set("Qseab10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("fLitT:10") - assert.Nil(t, err) - err = v.Set("qwLUe20") + err = v.Set("cheKa:10") + assert.NoError(t, err) + err = v.Set("QCUgr20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("cgOcz:20") - assert.Nil(t, err) + err = v.Set("yeEll:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7168,12 +7190,12 @@ func TestStringInt32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int32) - v := newStringInt32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("XTbRMa") + err = v.Set("tHLAfa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("GxqPe:a") + err = v.Set("eyhYZ:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int32", v.Type()) @@ -7187,21 +7209,21 @@ func TestIntInt32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int32) - v := newIntInt32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("1:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7210,14 +7232,14 @@ func TestIntInt32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int32) - v := newIntInt32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int32", v.Type()) @@ -7231,21 +7253,21 @@ func TestInt8Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int32) - v := newInt8Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("010") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("520") + err = v.Set(":10") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7254,13 +7276,13 @@ func TestInt8Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int32) - v := newInt8Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -7275,21 +7297,21 @@ func TestInt16Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int32) - v := newInt16Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) err = v.Set("420") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7298,14 +7320,14 @@ func TestInt16Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int32) - v := newInt16Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("0:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int32", v.Type()) @@ -7319,21 +7341,21 @@ func TestInt32Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int32) - v := newInt32Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7342,14 +7364,14 @@ func TestInt32Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int32) - v := newInt32Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int32", v.Type()) @@ -7363,21 +7385,21 @@ func TestInt64Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int32) - v := newInt64Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("5:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7386,14 +7408,14 @@ func TestInt64Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int32) - v := newInt64Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("1:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int32", v.Type()) @@ -7407,21 +7429,21 @@ func TestUintInt32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int32) - v := newUintInt32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("220") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7430,14 +7452,14 @@ func TestUintInt32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int32) - v := newUintInt32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int32", v.Type()) @@ -7451,21 +7473,21 @@ func TestUint8Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int32) - v := newUint8Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("5:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7474,14 +7496,14 @@ func TestUint8Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int32) - v := newUint8Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int32", v.Type()) @@ -7495,21 +7517,21 @@ func TestUint16Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int32) - v := newUint16Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("0:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("520") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7518,14 +7540,14 @@ func TestUint16Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int32) - v := newUint16Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4a") + err = v.Set("1a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("1:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int32", v.Type()) @@ -7539,21 +7561,21 @@ func TestUint32Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int32) - v := newUint32Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7562,14 +7584,14 @@ func TestUint32Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int32) - v := newUint32Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("1a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int32", v.Type()) @@ -7583,21 +7605,21 @@ func TestUint64Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int32) - v := newUint64Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:10") - assert.Nil(t, err) - err = v.Set("520") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int32", v.Type()) assert.NotEmpty(t, v.String()) @@ -7606,14 +7628,14 @@ func TestUint64Int32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int32) - v := newUint64Int32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("5:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int32", v.Type()) @@ -7624,10 +7646,10 @@ func TestUint64Int32MapValue(t *testing.T) { func TestInt64Value_Zero(t *testing.T) { t.Parallel() nilValue := new(int64Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -7637,9 +7659,9 @@ func TestInt64Value(t *testing.T) { t.Parallel() a := new(int64) v := newInt64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("3") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "3", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int64", v.Type()) @@ -7648,9 +7670,9 @@ func TestInt64Value(t *testing.T) { t.Parallel() a := new(int64) v := newInt64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-3") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "-3", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int64", v.Type()) @@ -7659,7 +7681,7 @@ func TestInt64Value(t *testing.T) { t.Parallel() a := new(int64) v := newInt64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("-9223372036854775809") assert.EqualError(t, err, "strconv.ParseInt: parsing \"-9223372036854775809\": value out of range") assert.Equal(t, "0", v.String()) @@ -7670,7 +7692,7 @@ func TestInt64Value(t *testing.T) { t.Parallel() a := new(int64) v := newInt64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("9223372036854775808") assert.EqualError(t, err, "strconv.ParseInt: parsing \"9223372036854775808\": value out of range") assert.Equal(t, "0", v.String()) @@ -7681,13 +7703,14 @@ func TestInt64Value(t *testing.T) { t.Parallel() a := new(int64) v := newInt64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int64", v.Type()) }) + } func TestInt64SliceValue_Zero(t *testing.T) { @@ -7703,110 +7726,110 @@ func TestInt64SliceValue_Zero(t *testing.T) { func TestStringInt64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringInt64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringInt64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntInt64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intInt64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intInt64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintInt64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintInt64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintInt64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Int64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Int64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Int64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -7816,13 +7839,13 @@ func TestInt64SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int64) - v := newInt64SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt64SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10,20") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("-1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10,20,-1]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "int64Slice", v.Type()) @@ -7831,8 +7854,8 @@ func TestInt64SliceValue(t *testing.T) { t.Parallel() var err error a := new([]int64) - v := newInt64SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newInt64SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") @@ -7840,6 +7863,7 @@ func TestInt64SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "int64Slice", v.Type()) }) + } func TestStringInt64MapValue(t *testing.T) { @@ -7848,17 +7872,17 @@ func TestStringInt64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int64) - v := newStringInt64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("ORvAU10") + err = v.Set("XIuHz10") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("kAwww:10") - assert.Nil(t, err) - err = v.Set("TndUJ20") + err = v.Set("xXMfK:10") + assert.NoError(t, err) + err = v.Set("NquMX20") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("HiQec:20") - assert.Nil(t, err) + err = v.Set("ZDtuX:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -7867,12 +7891,12 @@ func TestStringInt64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]int64) - v := newStringInt64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringInt64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("bxzvqa") + err = v.Set("hBojxa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("zlPWy:a") + err = v.Set("lfSZP:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]int64", v.Type()) @@ -7886,21 +7910,21 @@ func TestIntInt64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int64) - v := newIntInt64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("2:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -7909,14 +7933,14 @@ func TestIntInt64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]int64) - v := newIntInt64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntInt64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("1:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]int64", v.Type()) @@ -7930,21 +7954,21 @@ func TestInt8Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int64) - v := newInt8Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110") + err = v.Set("710") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("6:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("5:10") + assert.NoError(t, err) + err = v.Set("720") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -7953,14 +7977,14 @@ func TestInt8Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]int64) - v := newInt8Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]int64", v.Type()) @@ -7974,21 +7998,21 @@ func TestInt16Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int64) - v := newInt16Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("220") + assert.NoError(t, err) + err = v.Set("120") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -7997,14 +8021,14 @@ func TestInt16Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]int64) - v := newInt16Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4a") + err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]int64", v.Type()) @@ -8018,21 +8042,21 @@ func TestInt32Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int64) - v := newInt32Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("2:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("7:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8041,14 +8065,14 @@ func TestInt32Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]int64) - v := newInt32Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("1:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]int64", v.Type()) @@ -8062,21 +8086,21 @@ func TestInt64Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int64) - v := newInt64Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("310") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("420") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("020") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("4:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8085,14 +8109,14 @@ func TestInt64Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]int64) - v := newInt64Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]int64", v.Type()) @@ -8106,21 +8130,21 @@ func TestUintInt64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int64) - v := newUintInt64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("4:10") - assert.Nil(t, err) - err = v.Set("320") + assert.Error(t, err) + err = v.Set("7:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("5:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8129,14 +8153,14 @@ func TestUintInt64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]int64) - v := newUintInt64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintInt64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]int64", v.Type()) @@ -8150,21 +8174,21 @@ func TestUint8Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int64) - v := newUint8Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("410") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("220") + assert.Error(t, err) + err = v.Set("0:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:20") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8173,14 +8197,14 @@ func TestUint8Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]int64) - v := newUint8Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]int64", v.Type()) @@ -8194,21 +8218,21 @@ func TestUint16Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int64) - v := newUint16Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410") + err = v.Set("610") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("1:10") - assert.Nil(t, err) - err = v.Set("720") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("6:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8217,14 +8241,14 @@ func TestUint16Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]int64) - v := newUint16Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]int64", v.Type()) @@ -8238,21 +8262,21 @@ func TestUint32Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int64) - v := newUint32Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("610") + err = v.Set("110") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("3:10") - assert.Nil(t, err) - err = v.Set("520") + assert.Error(t, err) + err = v.Set("4:10") + assert.NoError(t, err) + err = v.Set("620") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("1:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8261,14 +8285,14 @@ func TestUint32Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]int64) - v := newUint32Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]int64", v.Type()) @@ -8282,21 +8306,21 @@ func TestUint64Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int64) - v := newUint64Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010") + err = v.Set("210") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10") - assert.NotNil(t, err) - err = v.Set("7:10") - assert.Nil(t, err) - err = v.Set("620") + assert.Error(t, err) + err = v.Set("2:10") + assert.NoError(t, err) + err = v.Set("320") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20") - assert.NotNil(t, err) - err = v.Set("3:20") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8305,14 +8329,14 @@ func TestUint64Int64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]int64) - v := newUint64Int64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Int64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseInt: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]int64", v.Type()) @@ -8323,10 +8347,10 @@ func TestUint64Int64MapValue(t *testing.T) { func TestFloat64Value_Zero(t *testing.T) { t.Parallel() nilValue := new(float64Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*float64Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -8336,9 +8360,9 @@ func TestFloat64Value(t *testing.T) { t.Parallel() a := new(float64) v := newFloat64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("11.11") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "11.11", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "float64", v.Type()) @@ -8347,7 +8371,7 @@ func TestFloat64Value(t *testing.T) { t.Parallel() a := new(float64) v := newFloat64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("11.11.11") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"11.11.11\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -8358,13 +8382,14 @@ func TestFloat64Value(t *testing.T) { t.Parallel() a := new(float64) v := newFloat64Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "float64", v.Type()) }) + } func TestFloat64SliceValue_Zero(t *testing.T) { @@ -8380,110 +8405,110 @@ func TestFloat64SliceValue_Zero(t *testing.T) { func TestStringFloat64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringFloat64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringFloat64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntFloat64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intFloat64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intFloat64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintFloat64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintFloat64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintFloat64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Float64MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Float64MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Float64MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -8493,13 +8518,13 @@ func TestFloat64SliceValue(t *testing.T) { t.Parallel() var err error a := new([]float64) - v := newFloat64SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newFloat64SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10.2,20.99") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("3.4") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10.2,20.99,3.4]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "float64Slice", v.Type()) @@ -8508,8 +8533,8 @@ func TestFloat64SliceValue(t *testing.T) { t.Parallel() var err error a := new([]float64) - v := newFloat64SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newFloat64SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") @@ -8517,6 +8542,7 @@ func TestFloat64SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "float64Slice", v.Type()) }) + } func TestStringFloat64MapValue(t *testing.T) { @@ -8525,17 +8551,17 @@ func TestStringFloat64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]float64) - v := newStringFloat64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringFloat64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("hTtUT10.2") + err = v.Set("AGboC10.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("uWJRG:10.2") - assert.Nil(t, err) - err = v.Set("iQjOT20.99") + err = v.Set("gaFek:10.2") + assert.NoError(t, err) + err = v.Set("wsLRS20.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("cVwHj:20.99") - assert.Nil(t, err) + err = v.Set("EkOTy:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8544,12 +8570,12 @@ func TestStringFloat64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]float64) - v := newStringFloat64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringFloat64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("KVtPoa") + err = v.Set("fxSjqa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("VVTYN:a") + err = v.Set("DXebP:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]float64", v.Type()) @@ -8563,21 +8589,21 @@ func TestIntFloat64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]float64) - v := newIntFloat64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntFloat64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110.2") + err = v.Set("610.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("5:10.2") - assert.Nil(t, err) - err = v.Set("520.99") + assert.Error(t, err) + err = v.Set("0:10.2") + assert.NoError(t, err) + err = v.Set("120.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("5:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8586,14 +8612,14 @@ func TestIntFloat64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]float64) - v := newIntFloat64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntFloat64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("6:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]float64", v.Type()) @@ -8607,21 +8633,21 @@ func TestInt8Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]float64) - v := newInt8Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("510.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("0:10.2") - assert.Nil(t, err) - err = v.Set("620.99") + assert.Error(t, err) + err = v.Set("2:10.2") + assert.NoError(t, err) + err = v.Set("020.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("4:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8630,14 +8656,14 @@ func TestInt8Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]float64) - v := newInt8Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]float64", v.Type()) @@ -8651,21 +8677,21 @@ func TestInt16Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]float64) - v := newInt16Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("710.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("0:10.2") - assert.Nil(t, err) - err = v.Set("520.99") + assert.Error(t, err) + err = v.Set("7:10.2") + assert.NoError(t, err) + err = v.Set("420.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:20.99") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8674,14 +8700,14 @@ func TestInt16Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]float64) - v := newInt16Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("0:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]float64", v.Type()) @@ -8695,21 +8721,21 @@ func TestInt32Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]float64) - v := newInt32Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510.2") + err = v.Set("210.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("2:10.2") - assert.Nil(t, err) - err = v.Set("220.99") + assert.Error(t, err) + err = v.Set("4:10.2") + assert.NoError(t, err) + err = v.Set("420.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("4:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8718,14 +8744,14 @@ func TestInt32Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]float64) - v := newInt32Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("3a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("5:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]float64", v.Type()) @@ -8739,21 +8765,21 @@ func TestInt64Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]float64) - v := newInt64Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("310.2") + err = v.Set("010.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("3:10.2") - assert.Nil(t, err) - err = v.Set("420.99") + assert.Error(t, err) + err = v.Set("0:10.2") + assert.NoError(t, err) + err = v.Set("120.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("3:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8762,13 +8788,13 @@ func TestInt64Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]float64) - v := newInt64Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -8783,21 +8809,21 @@ func TestUintFloat64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]float64) - v := newUintFloat64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintFloat64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("410.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("7:10.2") - assert.Nil(t, err) - err = v.Set("620.99") + assert.Error(t, err) + err = v.Set("2:10.2") + assert.NoError(t, err) + err = v.Set("320.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("3:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8806,14 +8832,14 @@ func TestUintFloat64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]float64) - v := newUintFloat64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintFloat64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]float64", v.Type()) @@ -8827,21 +8853,21 @@ func TestUint8Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]float64) - v := newUint8Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210.2") + err = v.Set("510.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("5:10.2") - assert.Nil(t, err) - err = v.Set("120.99") + assert.Error(t, err) + err = v.Set("4:10.2") + assert.NoError(t, err) + err = v.Set("720.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("2:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8850,13 +8876,13 @@ func TestUint8Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]float64) - v := newUint8Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("6a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("0:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) @@ -8871,21 +8897,21 @@ func TestUint16Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]float64) - v := newUint16Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010.2") + err = v.Set("310.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("2:10.2") - assert.Nil(t, err) - err = v.Set("420.99") + assert.Error(t, err) + err = v.Set("7:10.2") + assert.NoError(t, err) + err = v.Set("620.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("7:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8894,14 +8920,14 @@ func TestUint16Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]float64) - v := newUint16Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("7:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]float64", v.Type()) @@ -8915,21 +8941,21 @@ func TestUint32Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]float64) - v := newUint32Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("710.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("6:10.2") - assert.Nil(t, err) - err = v.Set("420.99") + assert.Error(t, err) + err = v.Set("0:10.2") + assert.NoError(t, err) + err = v.Set("220.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("1:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8938,14 +8964,14 @@ func TestUint32Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]float64) - v := newUint32Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]float64", v.Type()) @@ -8959,21 +8985,21 @@ func TestUint64Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]float64) - v := newUint64Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410.2") + err = v.Set("010.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("6:10.2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:10.2") + assert.NoError(t, err) err = v.Set("420.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("4:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]float64", v.Type()) assert.NotEmpty(t, v.String()) @@ -8982,14 +9008,14 @@ func TestUint64Float64MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]float64) - v := newUint64Float64MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Float64MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]float64", v.Type()) @@ -9000,10 +9026,10 @@ func TestUint64Float64MapValue(t *testing.T) { func TestFloat32Value_Zero(t *testing.T) { t.Parallel() nilValue := new(float32Value) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*float32Value)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -9013,9 +9039,9 @@ func TestFloat32Value(t *testing.T) { t.Parallel() a := new(float32) v := newFloat32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("11.11") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "11.11", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "float32", v.Type()) @@ -9024,7 +9050,7 @@ func TestFloat32Value(t *testing.T) { t.Parallel() a := new(float32) v := newFloat32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("11.11.11") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"11.11.11\": invalid syntax") assert.Equal(t, "0", v.String()) @@ -9035,13 +9061,14 @@ func TestFloat32Value(t *testing.T) { t.Parallel() a := new(float32) v := newFloat32Value(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, "0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "float32", v.Type()) }) + } func TestFloat32SliceValue_Zero(t *testing.T) { @@ -9057,110 +9084,110 @@ func TestFloat32SliceValue_Zero(t *testing.T) { func TestStringFloat32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringFloat32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringFloat32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntFloat32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue intFloat32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intFloat32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintFloat32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintFloat32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintFloat32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64Float32MapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64Float32MapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64Float32MapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -9170,13 +9197,13 @@ func TestFloat32SliceValue(t *testing.T) { t.Parallel() var err error a := new([]float32) - v := newFloat32SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newFloat32SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10.2,20.99") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("3.4") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10.2,20.99,3.4]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "float32Slice", v.Type()) @@ -9185,8 +9212,8 @@ func TestFloat32SliceValue(t *testing.T) { t.Parallel() var err error a := new([]float32) - v := newFloat32SliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newFloat32SliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1,a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") @@ -9194,6 +9221,7 @@ func TestFloat32SliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "float32Slice", v.Type()) }) + } func TestStringFloat32MapValue(t *testing.T) { @@ -9202,17 +9230,17 @@ func TestStringFloat32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]float32) - v := newStringFloat32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringFloat32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("aWlfV10.2") + err = v.Set("bdqfW10.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("cjYMc:10.2") - assert.Nil(t, err) - err = v.Set("wVxDr20.99") + err = v.Set("BBGyV:10.2") + assert.NoError(t, err) + err = v.Set("cQIEA20.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("nsfUr:20.99") - assert.Nil(t, err) + err = v.Set("fcrgC:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9221,12 +9249,12 @@ func TestStringFloat32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]float32) - v := newStringFloat32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringFloat32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("CFsVya") + err = v.Set("kJfOGa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("SzWtb:a") + err = v.Set("LKKPV:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]float32", v.Type()) @@ -9240,21 +9268,21 @@ func TestIntFloat32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]float32) - v := newIntFloat32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntFloat32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710.2") + err = v.Set("410.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("6:10.2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:10.2") + assert.NoError(t, err) err = v.Set("520.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("2:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9263,14 +9291,14 @@ func TestIntFloat32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]float32) - v := newIntFloat32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntFloat32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]float32", v.Type()) @@ -9284,21 +9312,21 @@ func TestInt8Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]float32) - v := newInt8Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("710.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("0:10.2") - assert.Nil(t, err) - err = v.Set("520.99") + assert.Error(t, err) + err = v.Set("1:10.2") + assert.NoError(t, err) + err = v.Set("220.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("2:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9307,14 +9335,14 @@ func TestInt8Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]float32) - v := newInt8Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("0a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]float32", v.Type()) @@ -9328,21 +9356,21 @@ func TestInt16Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]float32) - v := newInt16Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("010.2") + err = v.Set("310.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:10.2") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("020.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("2:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9351,14 +9379,14 @@ func TestInt16Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]float32) - v := newInt16Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]float32", v.Type()) @@ -9372,21 +9400,21 @@ func TestInt32Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]float32) - v := newInt32Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510.2") + err = v.Set("410.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("2:10.2") - assert.Nil(t, err) - err = v.Set("120.99") + assert.Error(t, err) + err = v.Set("4:10.2") + assert.NoError(t, err) + err = v.Set("020.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("4:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9395,14 +9423,14 @@ func TestInt32Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]float32) - v := newInt32Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]float32", v.Type()) @@ -9416,21 +9444,21 @@ func TestInt64Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]float32) - v := newInt64Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110.2") + err = v.Set("010.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("6:10.2") - assert.Nil(t, err) - err = v.Set("720.99") + assert.Error(t, err) + err = v.Set("0:10.2") + assert.NoError(t, err) + err = v.Set("020.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:20.99") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9439,14 +9467,14 @@ func TestInt64Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]float32) - v := newInt64Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("7a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("3:a") + assert.Error(t, err) + err = v.Set("4:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]float32", v.Type()) @@ -9460,21 +9488,21 @@ func TestUintFloat32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]float32) - v := newUintFloat32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintFloat32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410.2") + err = v.Set("110.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("0:10.2") - assert.Nil(t, err) - err = v.Set("420.99") + assert.Error(t, err) + err = v.Set("3:10.2") + assert.NoError(t, err) + err = v.Set("120.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:20.99") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9483,14 +9511,14 @@ func TestUintFloat32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]float32) - v := newUintFloat32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintFloat32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("7:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]float32", v.Type()) @@ -9504,21 +9532,21 @@ func TestUint8Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]float32) - v := newUint8Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("410.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("1:10.2") - assert.Nil(t, err) - err = v.Set("120.99") + assert.Error(t, err) + err = v.Set("0:10.2") + assert.NoError(t, err) + err = v.Set("320.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("1:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9527,14 +9555,14 @@ func TestUint8Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]float32) - v := newUint8Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3a") + err = v.Set("4a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("5:a") + assert.Error(t, err) + err = v.Set("3:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]float32", v.Type()) @@ -9548,21 +9576,21 @@ func TestUint16Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]float32) - v := newUint16Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510.2") + err = v.Set("710.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("5:10.2") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:10.2") + assert.NoError(t, err) err = v.Set("220.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("1:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9571,14 +9599,14 @@ func TestUint16Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]float32) - v := newUint16Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("6:a") + assert.Error(t, err) + err = v.Set("2:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]float32", v.Type()) @@ -9592,21 +9620,21 @@ func TestUint32Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]float32) - v := newUint32Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210.2") + err = v.Set("610.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:10.2") - assert.Nil(t, err) - err = v.Set("220.99") + assert.NoError(t, err) + err = v.Set("120.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("0:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9615,14 +9643,14 @@ func TestUint32Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]float32) - v := newUint32Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0a") + err = v.Set("2a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("4:a") + assert.Error(t, err) + err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]float32", v.Type()) @@ -9636,21 +9664,21 @@ func TestUint64Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]float32) - v := newUint64Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710.2") + err = v.Set("010.2") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10.2") - assert.NotNil(t, err) - err = v.Set("0:10.2") - assert.Nil(t, err) - err = v.Set("520.99") + assert.Error(t, err) + err = v.Set("2:10.2") + assert.NoError(t, err) + err = v.Set("720.99") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":20.99") - assert.NotNil(t, err) - err = v.Set("2:20.99") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:20.99") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]float32", v.Type()) assert.NotEmpty(t, v.String()) @@ -9659,14 +9687,14 @@ func TestUint64Float32MapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]float32) - v := newUint64Float32MapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64Float32MapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7a") + err = v.Set("5a") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":a") - assert.NotNil(t, err) - err = v.Set("2:a") + assert.Error(t, err) + err = v.Set("1:a") assert.EqualError(t, err, "strconv.ParseFloat: parsing \"a\": invalid syntax") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]float32", v.Type()) @@ -9677,10 +9705,10 @@ func TestUint64Float32MapValue(t *testing.T) { func TestDurationValue_Zero(t *testing.T) { t.Parallel() nilValue := new(durationValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*durationValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -9690,9 +9718,9 @@ func TestDurationValue(t *testing.T) { t.Parallel() a := new(time.Duration) v := newDurationValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("3s") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "3s", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "duration", v.Type()) @@ -9701,13 +9729,14 @@ func TestDurationValue(t *testing.T) { t.Parallel() a := new(time.Duration) v := newDurationValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, "0s", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "duration", v.Type()) }) + } func TestDurationSliceValue_Zero(t *testing.T) { @@ -9723,110 +9752,110 @@ func TestDurationSliceValue_Zero(t *testing.T) { func TestStringDurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringDurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringDurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntDurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intDurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intDurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintDurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintDurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintDurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64DurationMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64DurationMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64DurationMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -9836,13 +9865,13 @@ func TestDurationSliceValue(t *testing.T) { t.Parallel() var err error a := new([]time.Duration) - v := newDurationSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newDurationSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10s,30m") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("1ms") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[10s,30m0s,1ms]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "durationSlice", v.Type()) @@ -9851,8 +9880,8 @@ func TestDurationSliceValue(t *testing.T) { t.Parallel() var err error a := new([]time.Duration) - v := newDurationSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newDurationSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1s,3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") @@ -9860,6 +9889,7 @@ func TestDurationSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "durationSlice", v.Type()) }) + } func TestStringDurationMapValue(t *testing.T) { @@ -9868,17 +9898,17 @@ func TestStringDurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]time.Duration) - v := newStringDurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringDurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("oLEzi10s") + err = v.Set("JaNQt10s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("JiWmA:10s") - assert.Nil(t, err) - err = v.Set("PKvAT30m") + err = v.Set("nTAaJ:10s") + assert.NoError(t, err) + err = v.Set("gtMxv30m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("djZyE:30m") - assert.Nil(t, err) + err = v.Set("ZFtDR:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -9887,12 +9917,12 @@ func TestStringDurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]time.Duration) - v := newStringDurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringDurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("vvmsI3l") + err = v.Set("IfNUd3l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("DSJeK:3l") + err = v.Set("gbhVA:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]time.Duration", v.Type()) @@ -9906,21 +9936,21 @@ func TestIntDurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]time.Duration) - v := newIntDurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntDurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("210s") + err = v.Set("410s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("5:10s") - assert.Nil(t, err) - err = v.Set("130m") + assert.Error(t, err) + err = v.Set("2:10s") + assert.NoError(t, err) + err = v.Set("730m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("7:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -9929,14 +9959,14 @@ func TestIntDurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]time.Duration) - v := newIntDurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntDurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("63l") + err = v.Set("03l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("0:3l") + assert.Error(t, err) + err = v.Set("6:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]time.Duration", v.Type()) @@ -9950,21 +9980,21 @@ func TestInt8DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]time.Duration) - v := newInt8DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("510s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("0:10s") - assert.Nil(t, err) - err = v.Set("330m") + assert.Error(t, err) + err = v.Set("3:10s") + assert.NoError(t, err) + err = v.Set("430m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("0:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -9973,14 +10003,14 @@ func TestInt8DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]time.Duration) - v := newInt8DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("53l") + err = v.Set("33l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("5:3l") + assert.Error(t, err) + err = v.Set("4:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]time.Duration", v.Type()) @@ -9994,21 +10024,21 @@ func TestInt16DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]time.Duration) - v := newInt16DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("510s") + err = v.Set("010s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("4:10s") - assert.Nil(t, err) - err = v.Set("230m") + assert.Error(t, err) + err = v.Set("3:10s") + assert.NoError(t, err) + err = v.Set("030m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("7:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10017,14 +10047,14 @@ func TestInt16DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]time.Duration) - v := newInt16DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("53l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("1:3l") + assert.Error(t, err) + err = v.Set("0:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]time.Duration", v.Type()) @@ -10038,21 +10068,21 @@ func TestInt32DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]time.Duration) - v := newInt32DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("410s") + err = v.Set("310s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("7:10s") - assert.Nil(t, err) - err = v.Set("530m") + assert.Error(t, err) + err = v.Set("6:10s") + assert.NoError(t, err) + err = v.Set("230m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("0:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10061,14 +10091,14 @@ func TestInt32DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]time.Duration) - v := newInt32DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("63l") + err = v.Set("53l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("3:3l") + assert.Error(t, err) + err = v.Set("5:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]time.Duration", v.Type()) @@ -10082,21 +10112,21 @@ func TestInt64DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]time.Duration) - v := newInt64DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("110s") + err = v.Set("510s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("3:10s") - assert.Nil(t, err) - err = v.Set("130m") + assert.Error(t, err) + err = v.Set("5:10s") + assert.NoError(t, err) + err = v.Set("630m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("7:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10105,14 +10135,14 @@ func TestInt64DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]time.Duration) - v := newInt64DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("73l") + err = v.Set("33l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("1:3l") + assert.Error(t, err) + err = v.Set("5:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]time.Duration", v.Type()) @@ -10126,21 +10156,21 @@ func TestUintDurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]time.Duration) - v := newUintDurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintDurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710s") + err = v.Set("210s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("6:10s") - assert.Nil(t, err) - err = v.Set("730m") + assert.Error(t, err) + err = v.Set("5:10s") + assert.NoError(t, err) + err = v.Set("030m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("4:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10149,13 +10179,13 @@ func TestUintDurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]time.Duration) - v := newUintDurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintDurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("03l") + err = v.Set("63l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) @@ -10170,21 +10200,21 @@ func TestUint8DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]time.Duration) - v := newUint8DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710s") + err = v.Set("210s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("2:10s") - assert.Nil(t, err) - err = v.Set("730m") + assert.Error(t, err) + err = v.Set("3:10s") + assert.NoError(t, err) + err = v.Set("030m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("4:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10193,14 +10223,14 @@ func TestUint8DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]time.Duration) - v := newUint8DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("03l") + err = v.Set("63l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("6:3l") + assert.Error(t, err) + err = v.Set("0:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]time.Duration", v.Type()) @@ -10214,21 +10244,21 @@ func TestUint16DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]time.Duration) - v := newUint16DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710s") + err = v.Set("310s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("4:10s") - assert.Nil(t, err) - err = v.Set("230m") + assert.Error(t, err) + err = v.Set("2:10s") + assert.NoError(t, err) + err = v.Set("330m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("6:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10237,14 +10267,14 @@ func TestUint16DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]time.Duration) - v := newUint16DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("73l") + err = v.Set("33l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("4:3l") + assert.Error(t, err) + err = v.Set("2:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]time.Duration", v.Type()) @@ -10258,21 +10288,21 @@ func TestUint32DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]time.Duration) - v := newUint32DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710s") + err = v.Set("210s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("2:10s") - assert.Nil(t, err) - err = v.Set("630m") + assert.Error(t, err) + err = v.Set("6:10s") + assert.NoError(t, err) + err = v.Set("130m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("6:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10281,14 +10311,14 @@ func TestUint32DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]time.Duration) - v := newUint32DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("23l") + err = v.Set("03l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) - err = v.Set("1:3l") + assert.Error(t, err) + err = v.Set("2:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]time.Duration", v.Type()) @@ -10302,21 +10332,21 @@ func TestUint64DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]time.Duration) - v := newUint64DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("710s") + err = v.Set("310s") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":10s") - assert.NotNil(t, err) - err = v.Set("2:10s") - assert.Nil(t, err) - err = v.Set("330m") + assert.Error(t, err) + err = v.Set("5:10s") + assert.NoError(t, err) + err = v.Set("530m") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":30m") - assert.NotNil(t, err) - err = v.Set("5:30m") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:30m") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]time.Duration", v.Type()) assert.NotEmpty(t, v.String()) @@ -10325,13 +10355,13 @@ func TestUint64DurationMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]time.Duration) - v := newUint64DurationMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64DurationMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("33l") + err = v.Set("03l") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":3l") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:3l") assert.EqualError(t, err, "time: unknown unit \"l\" in duration \"3l\"") assert.Equal(t, a, v.Get()) @@ -10343,10 +10373,10 @@ func TestUint64DurationMapValue(t *testing.T) { func TestIPValue_Zero(t *testing.T) { t.Parallel() nilValue := new(ipValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*ipValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -10356,9 +10386,9 @@ func TestIPValue(t *testing.T) { t.Parallel() a := new(net.IP) v := newIPValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("127.0.0.1") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "127.0.0.1", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ip", v.Type()) @@ -10367,13 +10397,14 @@ func TestIPValue(t *testing.T) { t.Parallel() a := new(net.IP) v := newIPValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, "", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ip", v.Type()) }) + } func TestIPSliceValue_Zero(t *testing.T) { @@ -10389,110 +10420,110 @@ func TestIPSliceValue_Zero(t *testing.T) { func TestStringIPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringIPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringIPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntIPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intIPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intIPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintIPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintIPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintIPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64IPMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64IPMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64IPMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -10502,13 +10533,13 @@ func TestIPSliceValue(t *testing.T) { t.Parallel() var err error a := new([]net.IP) - v := newIPSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newIPSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("127.0.0.1,127.0.0.2") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("127.0.0.3") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[127.0.0.1,127.0.0.2,127.0.0.3]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipSlice", v.Type()) @@ -10517,8 +10548,8 @@ func TestIPSliceValue(t *testing.T) { t.Parallel() var err error a := new([]net.IP) - v := newIPSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newIPSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("127.0.0.3,127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") @@ -10526,6 +10557,7 @@ func TestIPSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipSlice", v.Type()) }) + } func TestStringIPMapValue(t *testing.T) { @@ -10534,17 +10566,17 @@ func TestStringIPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]net.IP) - v := newStringIPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringIPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("iyeoU127.0.0.1") + err = v.Set("Zuzkk127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("qzMJG:127.0.0.1") - assert.Nil(t, err) - err = v.Set("HOxYT127.0.0.3") + err = v.Set("KlLbg:127.0.0.1") + assert.NoError(t, err) + err = v.Set("BcXNN127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("sbfqA:127.0.0.3") - assert.Nil(t, err) + err = v.Set("MdbPA:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10553,12 +10585,12 @@ func TestStringIPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]net.IP) - v := newStringIPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringIPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("qtXjk127.0.0.1.3") + err = v.Set("gXHFs127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("VItIB:127.0.0.1.3") + err = v.Set("oxjXv:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]net.IP", v.Type()) @@ -10572,21 +10604,21 @@ func TestIntIPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]net.IP) - v := newIntIPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntIPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7127.0.0.1") + err = v.Set("2127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.1") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:127.0.0.1") + assert.NoError(t, err) err = v.Set("6127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("5:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10595,14 +10627,14 @@ func TestIntIPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]net.IP) - v := newIntIPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntIPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4127.0.0.1.3") + err = v.Set("0127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("1:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("0:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]net.IP", v.Type()) @@ -10616,21 +10648,21 @@ func TestInt8IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]net.IP) - v := newInt8IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2127.0.0.1") + err = v.Set("7127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("4:127.0.0.1") - assert.Nil(t, err) - err = v.Set("1127.0.0.3") + assert.Error(t, err) + err = v.Set("5:127.0.0.1") + assert.NoError(t, err) + err = v.Set("6127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("5:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10639,13 +10671,13 @@ func TestInt8IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]net.IP) - v := newInt8IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("7127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) @@ -10660,21 +10692,21 @@ func TestInt16IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]net.IP) - v := newInt16IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4127.0.0.1") + err = v.Set("1127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("1:127.0.0.1") - assert.Nil(t, err) - err = v.Set("2127.0.0.3") + assert.Error(t, err) + err = v.Set("4:127.0.0.1") + assert.NoError(t, err) + err = v.Set("4127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("1:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10683,14 +10715,14 @@ func TestInt16IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]net.IP) - v := newInt16IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5127.0.0.1.3") + err = v.Set("2127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("6:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("2:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]net.IP", v.Type()) @@ -10704,21 +10736,21 @@ func TestInt32IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]net.IP) - v := newInt32IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2127.0.0.1") + err = v.Set("7127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("3:127.0.0.1") - assert.Nil(t, err) - err = v.Set("5127.0.0.3") + assert.Error(t, err) + err = v.Set("4:127.0.0.1") + assert.NoError(t, err) + err = v.Set("3127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10727,14 +10759,14 @@ func TestInt32IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]net.IP) - v := newInt32IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7127.0.0.1.3") + err = v.Set("5127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("7:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]net.IP", v.Type()) @@ -10748,21 +10780,21 @@ func TestInt64IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]net.IP) - v := newInt64IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4127.0.0.1") + err = v.Set("5127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("7:127.0.0.1") - assert.Nil(t, err) - err = v.Set("7127.0.0.3") + assert.Error(t, err) + err = v.Set("4:127.0.0.1") + assert.NoError(t, err) + err = v.Set("0127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10771,14 +10803,14 @@ func TestInt64IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]net.IP) - v := newInt64IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6127.0.0.1.3") + err = v.Set("5127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("0:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]net.IP", v.Type()) @@ -10792,21 +10824,21 @@ func TestUintIPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]net.IP) - v := newUintIPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintIPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1127.0.0.1") + err = v.Set("2127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.1") - assert.Nil(t, err) - err = v.Set("7127.0.0.3") + assert.Error(t, err) + err = v.Set("4:127.0.0.1") + assert.NoError(t, err) + err = v.Set("0127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("1:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10815,14 +10847,14 @@ func TestUintIPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]net.IP) - v := newUintIPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintIPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2127.0.0.1.3") + err = v.Set("1127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("6:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("1:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]net.IP", v.Type()) @@ -10836,21 +10868,21 @@ func TestUint8IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]net.IP) - v := newUint8IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5127.0.0.1") + err = v.Set("1127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("6:127.0.0.1") - assert.Nil(t, err) - err = v.Set("5127.0.0.3") + assert.Error(t, err) + err = v.Set("5:127.0.0.1") + assert.NoError(t, err) + err = v.Set("0127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("4:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10859,14 +10891,14 @@ func TestUint8IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]net.IP) - v := newUint8IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2127.0.0.1.3") + err = v.Set("3127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("2:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("6:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]net.IP", v.Type()) @@ -10880,21 +10912,21 @@ func TestUint16IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]net.IP) - v := newUint16IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3127.0.0.1") + err = v.Set("6127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("0:127.0.0.1") - assert.Nil(t, err) - err = v.Set("3127.0.0.3") + assert.NoError(t, err) + err = v.Set("5127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("4:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10903,13 +10935,13 @@ func TestUint16IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]net.IP) - v := newUint16IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2127.0.0.1.3") + err = v.Set("4127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("0:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) @@ -10924,21 +10956,21 @@ func TestUint32IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]net.IP) - v := newUint32IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1127.0.0.1") + err = v.Set("6127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("6:127.0.0.1") - assert.Nil(t, err) - err = v.Set("2127.0.0.3") + assert.Error(t, err) + err = v.Set("0:127.0.0.1") + assert.NoError(t, err) + err = v.Set("3127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("1:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10947,14 +10979,14 @@ func TestUint32IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]net.IP) - v := newUint32IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7127.0.0.1.3") + err = v.Set("3127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("5:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("1:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]net.IP", v.Type()) @@ -10968,21 +11000,21 @@ func TestUint64IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]net.IP) - v := newUint64IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7127.0.0.1") + err = v.Set("0127.0.0.1") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1") - assert.NotNil(t, err) - err = v.Set("1:127.0.0.1") - assert.Nil(t, err) - err = v.Set("2127.0.0.3") + assert.Error(t, err) + err = v.Set("5:127.0.0.1") + assert.NoError(t, err) + err = v.Set("4127.0.0.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.3") - assert.NotNil(t, err) - err = v.Set("7:127.0.0.3") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:127.0.0.3") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]net.IP", v.Type()) assert.NotEmpty(t, v.String()) @@ -10991,14 +11023,14 @@ func TestUint64IPMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]net.IP) - v := newUint64IPMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64IPMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5127.0.0.1.3") + err = v.Set("3127.0.0.1.3") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":127.0.0.1.3") - assert.NotNil(t, err) - err = v.Set("7:127.0.0.1.3") + assert.Error(t, err) + err = v.Set("1:127.0.0.1.3") assert.EqualError(t, err, "failed to parse IP: \"127.0.0.1.3\"") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]net.IP", v.Type()) @@ -11009,10 +11041,10 @@ func TestUint64IPMapValue(t *testing.T) { func TestHexBytesValue_Zero(t *testing.T) { t.Parallel() nilValue := new(hexBytesValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*hexBytesValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -11022,9 +11054,9 @@ func TestHexBytesValue(t *testing.T) { t.Parallel() a := new(HexBytes) v := newHexBytesValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("ffffff") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "ffffff", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "hexBytes", v.Type()) @@ -11033,9 +11065,9 @@ func TestHexBytesValue(t *testing.T) { t.Parallel() a := new(HexBytes) v := newHexBytesValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("FFFFFF") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "ffffff", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "hexBytes", v.Type()) @@ -11044,10 +11076,10 @@ func TestHexBytesValue(t *testing.T) { t.Parallel() a := new(HexBytes) v := newHexBytesValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("a") assert.EqualError(t, err, "encoding/hex: odd length hex string") - assert.Equal(t, "", v.String()) + assert.Empty(t, v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "hexBytes", v.Type()) }) @@ -11055,13 +11087,14 @@ func TestHexBytesValue(t *testing.T) { t.Parallel() a := new(HexBytes) v := newHexBytesValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") - assert.Equal(t, "", v.String()) + assert.Empty(t, v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "hexBytes", v.Type()) }) + } func TestHexBytesSliceValue_Zero(t *testing.T) { @@ -11077,110 +11110,110 @@ func TestHexBytesSliceValue_Zero(t *testing.T) { func TestStringHexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringHexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringHexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntHexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intHexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intHexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintHexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintHexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintHexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64HexBytesMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64HexBytesMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64HexBytesMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -11190,13 +11223,13 @@ func TestHexBytesSliceValue(t *testing.T) { t.Parallel() var err error a := new([]HexBytes) - v := newHexBytesSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newHexBytesSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("ff,aa,bb") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("cc") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[ff,aa,bb,cc]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "hexBytesSlice", v.Type()) @@ -11205,8 +11238,8 @@ func TestHexBytesSliceValue(t *testing.T) { t.Parallel() var err error a := new([]HexBytes) - v := newHexBytesSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newHexBytesSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("ff,gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") @@ -11214,6 +11247,7 @@ func TestHexBytesSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "hexBytesSlice", v.Type()) }) + } func TestStringHexBytesMapValue(t *testing.T) { @@ -11222,17 +11256,17 @@ func TestStringHexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]HexBytes) - v := newStringHexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringHexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("OxKmRff") + err = v.Set("AwoScff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("NwKDO:ff") - assert.Nil(t, err) - err = v.Set("UnXzmaa") + err = v.Set("GszOh:ff") + assert.NoError(t, err) + err = v.Set("anwiwaa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("DikdJ:aa") - assert.Nil(t, err) + err = v.Set("gJxWw:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11241,12 +11275,12 @@ func TestStringHexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]HexBytes) - v := newStringHexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringHexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("PukQLgg") + err = v.Set("CewYwgg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("axAHz:gg") + err = v.Set("jrqpd:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]HexBytes", v.Type()) @@ -11260,21 +11294,21 @@ func TestIntHexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]HexBytes) - v := newIntHexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntHexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3ff") + err = v.Set("0ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("4:ff") - assert.Nil(t, err) - err = v.Set("5aa") + assert.Error(t, err) + err = v.Set("0:ff") + assert.NoError(t, err) + err = v.Set("7aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("6:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11283,14 +11317,14 @@ func TestIntHexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]HexBytes) - v := newIntHexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntHexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7gg") + err = v.Set("4gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("7:gg") + assert.Error(t, err) + err = v.Set("3:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]HexBytes", v.Type()) @@ -11304,21 +11338,21 @@ func TestInt8HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]HexBytes) - v := newInt8HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4ff") + err = v.Set("7ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("0:ff") - assert.Nil(t, err) - err = v.Set("3aa") + assert.Error(t, err) + err = v.Set("6:ff") + assert.NoError(t, err) + err = v.Set("1aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("6:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11327,14 +11361,14 @@ func TestInt8HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]HexBytes) - v := newInt8HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1gg") + err = v.Set("5gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("5:gg") + assert.Error(t, err) + err = v.Set("2:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]HexBytes", v.Type()) @@ -11348,21 +11382,21 @@ func TestInt16HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]HexBytes) - v := newInt16HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4ff") + err = v.Set("2ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:ff") - assert.Nil(t, err) - err = v.Set("2aa") + assert.NoError(t, err) + err = v.Set("7aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("6:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11371,14 +11405,14 @@ func TestInt16HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]HexBytes) - v := newInt16HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6gg") + err = v.Set("4gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("2:gg") + assert.Error(t, err) + err = v.Set("3:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]HexBytes", v.Type()) @@ -11392,21 +11426,21 @@ func TestInt32HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]HexBytes) - v := newInt32HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2ff") + err = v.Set("3ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("6:ff") - assert.Nil(t, err) - err = v.Set("4aa") + assert.Error(t, err) + err = v.Set("3:ff") + assert.NoError(t, err) + err = v.Set("1aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:aa") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11415,14 +11449,14 @@ func TestInt32HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]HexBytes) - v := newInt32HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7gg") + err = v.Set("1gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("3:gg") + assert.Error(t, err) + err = v.Set("7:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]HexBytes", v.Type()) @@ -11436,21 +11470,21 @@ func TestInt64HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]HexBytes) - v := newInt64HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6ff") + err = v.Set("4ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("5:ff") - assert.Nil(t, err) - err = v.Set("0aa") + assert.Error(t, err) + err = v.Set("3:ff") + assert.NoError(t, err) + err = v.Set("6aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("5:aa") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11459,14 +11493,14 @@ func TestInt64HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]HexBytes) - v := newInt64HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2gg") + err = v.Set("1gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("6:gg") + assert.Error(t, err) + err = v.Set("7:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]HexBytes", v.Type()) @@ -11480,21 +11514,21 @@ func TestUintHexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]HexBytes) - v := newUintHexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintHexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("4ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:ff") - assert.Nil(t, err) - err = v.Set("7aa") + assert.NoError(t, err) + err = v.Set("0aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("6:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11503,14 +11537,14 @@ func TestUintHexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]HexBytes) - v := newUintHexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintHexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4gg") + err = v.Set("5gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("6:gg") + assert.Error(t, err) + err = v.Set("4:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]HexBytes", v.Type()) @@ -11524,21 +11558,21 @@ func TestUint8HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]HexBytes) - v := newUint8HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2ff") + err = v.Set("3ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("1:ff") - assert.Nil(t, err) - err = v.Set("5aa") + assert.Error(t, err) + err = v.Set("7:ff") + assert.NoError(t, err) + err = v.Set("4aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("1:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11547,14 +11581,14 @@ func TestUint8HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]HexBytes) - v := newUint8HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4gg") + err = v.Set("6gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("5:gg") + assert.Error(t, err) + err = v.Set("3:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]HexBytes", v.Type()) @@ -11568,21 +11602,21 @@ func TestUint16HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]HexBytes) - v := newUint16HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3ff") + err = v.Set("2ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("4:ff") - assert.Nil(t, err) - err = v.Set("6aa") + assert.Error(t, err) + err = v.Set("0:ff") + assert.NoError(t, err) + err = v.Set("0aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("5:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11591,14 +11625,14 @@ func TestUint16HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]HexBytes) - v := newUint16HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3gg") + err = v.Set("6gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("6:gg") + assert.Error(t, err) + err = v.Set("5:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]HexBytes", v.Type()) @@ -11612,21 +11646,21 @@ func TestUint32HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]HexBytes) - v := newUint32HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0ff") + err = v.Set("4ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("7:ff") - assert.Nil(t, err) - err = v.Set("5aa") + assert.Error(t, err) + err = v.Set("6:ff") + assert.NoError(t, err) + err = v.Set("6aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("6:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11635,14 +11669,14 @@ func TestUint32HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]HexBytes) - v := newUint32HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("6gg") + err = v.Set("3gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("5:gg") + assert.Error(t, err) + err = v.Set("7:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]HexBytes", v.Type()) @@ -11656,21 +11690,21 @@ func TestUint64HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]HexBytes) - v := newUint64HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1ff") + err = v.Set("3ff") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":ff") - assert.NotNil(t, err) - err = v.Set("2:ff") - assert.Nil(t, err) - err = v.Set("6aa") + assert.Error(t, err) + err = v.Set("5:ff") + assert.NoError(t, err) + err = v.Set("7aa") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":aa") - assert.NotNil(t, err) - err = v.Set("4:aa") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:aa") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]HexBytes", v.Type()) assert.NotEmpty(t, v.String()) @@ -11679,14 +11713,14 @@ func TestUint64HexBytesMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]HexBytes) - v := newUint64HexBytesMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64HexBytesMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5gg") + err = v.Set("1gg") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":gg") - assert.NotNil(t, err) - err = v.Set("3:gg") + assert.Error(t, err) + err = v.Set("6:gg") assert.EqualError(t, err, "encoding/hex: invalid byte: U+0067 'g'") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]HexBytes", v.Type()) @@ -11697,10 +11731,10 @@ func TestUint64HexBytesMapValue(t *testing.T) { func TestRegexpValue_Zero(t *testing.T) { t.Parallel() nilValue := new(regexpValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*regexpValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -11710,9 +11744,9 @@ func TestRegexpValue(t *testing.T) { t.Parallel() a := new(regexp.Regexp) v := newRegexpValue(&a) - assert.Equal(t, parseGeneratedPtrs(&a), v) + assert.Equal(t, ParseGeneratedPtrs(&a), v) err := v.Set("abcdef.*") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "abcdef.*", v.String()) assert.Equal(t, a, v.Get()) assert.Equal(t, "regexp", v.Type()) @@ -11721,13 +11755,14 @@ func TestRegexpValue(t *testing.T) { t.Parallel() a := new(regexp.Regexp) v := newRegexpValue(&a) - assert.Equal(t, parseGeneratedPtrs(&a), v) + assert.Equal(t, ParseGeneratedPtrs(&a), v) err := v.Set("[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") - assert.Equal(t, "", v.String()) + assert.Empty(t, v.String()) assert.Equal(t, a, v.Get()) assert.Equal(t, "regexp", v.Type()) }) + } func TestRegexpSliceValue_Zero(t *testing.T) { @@ -11743,110 +11778,110 @@ func TestRegexpSliceValue_Zero(t *testing.T) { func TestStringRegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringRegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringRegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntRegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intRegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intRegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintRegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintRegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintRegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64RegexpMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64RegexpMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64RegexpMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -11856,13 +11891,13 @@ func TestRegexpSliceValue(t *testing.T) { t.Parallel() var err error a := new([]*regexp.Regexp) - v := newRegexpSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newRegexpSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("abc.*,def.*") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("xyz.*") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[abc.*,def.*,xyz.*]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "regexpSlice", v.Type()) @@ -11871,8 +11906,8 @@ func TestRegexpSliceValue(t *testing.T) { t.Parallel() var err error a := new([]*regexp.Regexp) - v := newRegexpSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newRegexpSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("[abc,def") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") @@ -11880,6 +11915,7 @@ func TestRegexpSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "regexpSlice", v.Type()) }) + } func TestStringRegexpMapValue(t *testing.T) { @@ -11888,17 +11924,17 @@ func TestStringRegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]*regexp.Regexp) - v := newStringRegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringRegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("LLBLbabc.*") + err = v.Set("HIkvKabc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("uEhZF:abc.*") - assert.Nil(t, err) - err = v.Set("xQuvAxyz.*") + err = v.Set("QYiML:abc.*") + assert.NoError(t, err) + err = v.Set("mMgIXxyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("pLIPk:xyz.*") - assert.Nil(t, err) + err = v.Set("Xjsuh:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -11907,12 +11943,12 @@ func TestStringRegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]*regexp.Regexp) - v := newStringRegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringRegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("PzXDP[abc") + err = v.Set("lOcJN[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("izdhp:[abc") + err = v.Set("KvSIl:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]*regexp.Regexp", v.Type()) @@ -11926,21 +11962,21 @@ func TestIntRegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]*regexp.Regexp) - v := newIntRegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntRegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2abc.*") + err = v.Set("1abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("3:abc.*") - assert.Nil(t, err) - err = v.Set("2xyz.*") + assert.Error(t, err) + err = v.Set("7:abc.*") + assert.NoError(t, err) + err = v.Set("5xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("1:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -11949,13 +11985,13 @@ func TestIntRegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]*regexp.Regexp) - v := newIntRegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntRegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0[abc") + err = v.Set("2[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) @@ -11970,21 +12006,21 @@ func TestInt8RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]*regexp.Regexp) - v := newInt8RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0abc.*") + err = v.Set("2abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:abc.*") - assert.Nil(t, err) - err = v.Set("2xyz.*") + assert.NoError(t, err) + err = v.Set("1xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("7:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -11993,14 +12029,14 @@ func TestInt8RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]*regexp.Regexp) - v := newInt8RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0[abc") + err = v.Set("1[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("0:[abc") + assert.Error(t, err) + err = v.Set("1:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]*regexp.Regexp", v.Type()) @@ -12014,21 +12050,21 @@ func TestInt16RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]*regexp.Regexp) - v := newInt16RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("5abc.*") + err = v.Set("2abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("0:abc.*") - assert.Nil(t, err) - err = v.Set("3xyz.*") + assert.NoError(t, err) + err = v.Set("1xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("3:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12037,14 +12073,14 @@ func TestInt16RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]*regexp.Regexp) - v := newInt16RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("2[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("4:[abc") + assert.Error(t, err) + err = v.Set("2:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]*regexp.Regexp", v.Type()) @@ -12058,21 +12094,21 @@ func TestInt32RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]*regexp.Regexp) - v := newInt32RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("3abc.*") + err = v.Set("0abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("6:abc.*") - assert.Nil(t, err) - err = v.Set("2xyz.*") + assert.Error(t, err) + err = v.Set("1:abc.*") + assert.NoError(t, err) + err = v.Set("1xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("4:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12081,14 +12117,14 @@ func TestInt32RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]*regexp.Regexp) - v := newInt32RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7[abc") + err = v.Set("5[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("2:[abc") + assert.Error(t, err) + err = v.Set("3:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]*regexp.Regexp", v.Type()) @@ -12102,21 +12138,21 @@ func TestInt64RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]*regexp.Regexp) - v := newInt64RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2abc.*") + err = v.Set("5abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("4:abc.*") - assert.Nil(t, err) - err = v.Set("4xyz.*") + assert.Error(t, err) + err = v.Set("1:abc.*") + assert.NoError(t, err) + err = v.Set("1xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("7:xyz.*") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12125,14 +12161,14 @@ func TestInt64RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]*regexp.Regexp) - v := newInt64RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("7[abc") + err = v.Set("6[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("0:[abc") + assert.Error(t, err) + err = v.Set("7:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]*regexp.Regexp", v.Type()) @@ -12146,21 +12182,21 @@ func TestUintRegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]*regexp.Regexp) - v := newUintRegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintRegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("1abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("5:abc.*") - assert.Nil(t, err) - err = v.Set("6xyz.*") + assert.Error(t, err) + err = v.Set("6:abc.*") + assert.NoError(t, err) + err = v.Set("7xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("4:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12169,14 +12205,14 @@ func TestUintRegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]*regexp.Regexp) - v := newUintRegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintRegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("2[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("2:[abc") + assert.Error(t, err) + err = v.Set("6:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]*regexp.Regexp", v.Type()) @@ -12190,21 +12226,21 @@ func TestUint8RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]*regexp.Regexp) - v := newUint8RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("1abc.*") + err = v.Set("5abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("0:abc.*") - assert.Nil(t, err) - err = v.Set("6xyz.*") + assert.Error(t, err) + err = v.Set("7:abc.*") + assert.NoError(t, err) + err = v.Set("2xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("5:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12213,14 +12249,14 @@ func TestUint8RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]*regexp.Regexp) - v := newUint8RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("5[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("5:[abc") + assert.Error(t, err) + err = v.Set("6:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]*regexp.Regexp", v.Type()) @@ -12234,21 +12270,21 @@ func TestUint16RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]*regexp.Regexp) - v := newUint16RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("6abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("2:abc.*") - assert.Nil(t, err) - err = v.Set("4xyz.*") + assert.Error(t, err) + err = v.Set("3:abc.*") + assert.NoError(t, err) + err = v.Set("0xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("1:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12257,13 +12293,13 @@ func TestUint16RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]*regexp.Regexp) - v := newUint16RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("3[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("3:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) @@ -12278,21 +12314,21 @@ func TestUint32RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]*regexp.Regexp) - v := newUint32RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4abc.*") + err = v.Set("3abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("2:abc.*") - assert.Nil(t, err) - err = v.Set("3xyz.*") + assert.Error(t, err) + err = v.Set("0:abc.*") + assert.NoError(t, err) + err = v.Set("5xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("6:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12301,14 +12337,14 @@ func TestUint32RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]*regexp.Regexp) - v := newUint32RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("4[abc") + err = v.Set("5[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("3:[abc") + assert.Error(t, err) + err = v.Set("1:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]*regexp.Regexp", v.Type()) @@ -12322,21 +12358,21 @@ func TestUint64RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]*regexp.Regexp) - v := newUint64RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("0abc.*") + err = v.Set("3abc.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":abc.*") - assert.NotNil(t, err) - err = v.Set("6:abc.*") - assert.Nil(t, err) - err = v.Set("3xyz.*") + assert.Error(t, err) + err = v.Set("5:abc.*") + assert.NoError(t, err) + err = v.Set("1xyz.*") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":xyz.*") - assert.NotNil(t, err) - err = v.Set("5:xyz.*") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:xyz.*") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]*regexp.Regexp", v.Type()) assert.NotEmpty(t, v.String()) @@ -12345,14 +12381,14 @@ func TestUint64RegexpMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]*regexp.Regexp) - v := newUint64RegexpMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64RegexpMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("2[abc") + err = v.Set("4[abc") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":[abc") - assert.NotNil(t, err) - err = v.Set("4:[abc") + assert.Error(t, err) + err = v.Set("3:[abc") assert.EqualError(t, err, "error parsing regexp: missing closing ]: `[abc`") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]*regexp.Regexp", v.Type()) @@ -12363,10 +12399,10 @@ func TestUint64RegexpMapValue(t *testing.T) { func TestTCPAddrValue_Zero(t *testing.T) { t.Parallel() nilValue := new(tcpAddrValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*tcpAddrValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -12376,9 +12412,9 @@ func TestTCPAddrValue(t *testing.T) { t.Parallel() a := new(net.TCPAddr) v := newTCPAddrValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("127.0.0.1:8000") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "127.0.0.1:8000", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "tcpAddr", v.Type()) @@ -12387,9 +12423,9 @@ func TestTCPAddrValue(t *testing.T) { t.Parallel() a := new(net.TCPAddr) v := newTCPAddrValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("localhost:80") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "127.0.0.1:80", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "tcpAddr", v.Type()) @@ -12398,7 +12434,7 @@ func TestTCPAddrValue(t *testing.T) { t.Parallel() a := new(net.TCPAddr) v := newTCPAddrValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("127.0.0.1") assert.EqualError(t, err, "failed to parse TCPAddr: \"127.0.0.1\"") assert.Equal(t, ":0", v.String()) @@ -12409,13 +12445,14 @@ func TestTCPAddrValue(t *testing.T) { t.Parallel() a := new(net.TCPAddr) v := newTCPAddrValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("127.0.0.1.3:8000") assert.EqualError(t, err, "failed to parse TCPAddr: \"127.0.0.1.3:8000\"") assert.Equal(t, ":0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "tcpAddr", v.Type()) }) + } func TestTCPAddrSliceValue_Zero(t *testing.T) { @@ -12434,13 +12471,13 @@ func TestTCPAddrSliceValue(t *testing.T) { t.Parallel() var err error a := new([]net.TCPAddr) - v := newTCPAddrSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newTCPAddrSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("127.0.0.1:80,127.0.0.2:80") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("127.0.0.3:8800") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[127.0.0.1:80,127.0.0.2:80,127.0.0.3:8800]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "tcpAddrSlice", v.Type()) @@ -12449,8 +12486,8 @@ func TestTCPAddrSliceValue(t *testing.T) { t.Parallel() var err error a := new([]net.TCPAddr) - v := newTCPAddrSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newTCPAddrSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("127.0.0.3:8000,127.0.0.1.3:8000") assert.EqualError(t, err, "failed to parse TCPAddr: \"127.0.0.1.3:8000\"") @@ -12458,15 +12495,16 @@ func TestTCPAddrSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "tcpAddrSlice", v.Type()) }) + } func TestIPNetValue_Zero(t *testing.T) { t.Parallel() nilValue := new(ipNetValue) - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*ipNetValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -12476,9 +12514,9 @@ func TestIPNetValue(t *testing.T) { t.Parallel() a := new(net.IPNet) v := newIPNetValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("0.0.0.0/0") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "0.0.0.0/0", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNet", v.Type()) @@ -12487,9 +12525,9 @@ func TestIPNetValue(t *testing.T) { t.Parallel() a := new(net.IPNet) v := newIPNetValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("1.2.3.4/8") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "1.0.0.0/8", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNet", v.Type()) @@ -12498,9 +12536,9 @@ func TestIPNetValue(t *testing.T) { t.Parallel() a := new(net.IPNet) v := newIPNetValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("255.255.255.255/19") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "255.255.224.0/19", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNet", v.Type()) @@ -12509,9 +12547,9 @@ func TestIPNetValue(t *testing.T) { t.Parallel() a := new(net.IPNet) v := newIPNetValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("255.255.255.255/32") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "255.255.255.255/32", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNet", v.Type()) @@ -12520,7 +12558,7 @@ func TestIPNetValue(t *testing.T) { t.Parallel() a := new(net.IPNet) v := newIPNetValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("") assert.EqualError(t, err, "invalid CIDR address: ") assert.Equal(t, "", v.String()) @@ -12531,13 +12569,14 @@ func TestIPNetValue(t *testing.T) { t.Parallel() a := new(net.IPNet) v := newIPNetValue(a) - assert.Equal(t, parseGenerated(a), v) + assert.Equal(t, ParseGenerated(a, nil), v) err := v.Set("0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, "", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNet", v.Type()) }) + } func TestIPNetSliceValue_Zero(t *testing.T) { @@ -12553,110 +12592,110 @@ func TestIPNetSliceValue_Zero(t *testing.T) { func TestStringIPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue stringIPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*stringIPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestIntIPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue intIPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*intIPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt8IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int8IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int8IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt16IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int16IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int16IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt32IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int32IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int32IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestInt64IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue int64IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*int64IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUintIPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uintIPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uintIPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint8IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint8IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint8IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint16IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint16IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint16IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint32IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint32IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint32IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } func TestUint64IPNetMapValue_Zero(t *testing.T) { t.Parallel() var nilValue uint64IPNetMapValue - assert.Equal(t, "", nilValue.String()) + assert.Empty(t, nilValue.String()) assert.Nil(t, nilValue.Get()) nilObj := (*uint64IPNetMapValue)(nil) - assert.Equal(t, "", nilObj.String()) + assert.Empty(t, nilObj.String()) assert.Nil(t, nilObj.Get()) } @@ -12666,13 +12705,13 @@ func TestIPNetSliceValue(t *testing.T) { t.Parallel() var err error a := new([]net.IPNet) - v := newIPNetSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newIPNetSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("0.0.0.0/0,1.2.3.4/8") - assert.Nil(t, err) + assert.NoError(t, err) err = v.Set("255.255.255.255/19") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, "[0.0.0.0/0,1.0.0.0/8,255.255.224.0/19]", v.String()) assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNetSlice", v.Type()) @@ -12681,8 +12720,8 @@ func TestIPNetSliceValue(t *testing.T) { t.Parallel() var err error a := new([]net.IPNet) - v := newIPNetSliceValue(a) - assert.Equal(t, parseGenerated(a), v) + v := newIPNetSliceValue(a, nil) + assert.Equal(t, ParseGenerated(a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("0.0.0.0/0,0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") @@ -12690,6 +12729,7 @@ func TestIPNetSliceValue(t *testing.T) { assert.Equal(t, *a, v.Get()) assert.Equal(t, "ipNetSlice", v.Type()) }) + } func TestStringIPNetMapValue(t *testing.T) { @@ -12698,17 +12738,17 @@ func TestStringIPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]net.IPNet) - v := newStringIPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringIPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("EqCuP0.0.0.0/0") + err = v.Set("EbvTK0.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("DMNeu:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("iKTxR255.255.255.255/19") + err = v.Set("vJZMa:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("xLaSR255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("INKSz:255.255.255.255/19") - assert.Nil(t, err) + err = v.Set("uCEUU:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12717,12 +12757,12 @@ func TestStringIPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[string]net.IPNet) - v := newStringIPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newStringIPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("jAIvx0.0.0.256/16") + err = v.Set("WkslE0.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") - err = v.Set("BRDRL:0.0.0.256/16") + err = v.Set("RmQMo:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[string]net.IPNet", v.Type()) @@ -12736,21 +12776,21 @@ func TestIntIPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]net.IPNet) - v := newIntIPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntIPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("00.0.0.0/0") + err = v.Set("50.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("6:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("0255.255.255.255/19") + assert.Error(t, err) + err = v.Set("0:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("2255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("3:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("5:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12759,13 +12799,13 @@ func TestIntIPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int]net.IPNet) - v := newIntIPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newIntIPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("60.0.0.256/16") + err = v.Set("40.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("4:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) @@ -12780,21 +12820,21 @@ func TestInt8IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]net.IPNet) - v := newInt8IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("70.0.0.0/0") + err = v.Set("00.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("6:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("6255.255.255.255/19") + assert.Error(t, err) + err = v.Set("2:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("3255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("5:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("4:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12803,14 +12843,14 @@ func TestInt8IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int8]net.IPNet) - v := newInt8IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt8IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("10.0.0.256/16") + err = v.Set("20.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("7:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("1:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int8]net.IPNet", v.Type()) @@ -12824,21 +12864,21 @@ func TestInt16IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]net.IPNet) - v := newInt16IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("10.0.0.0/0") + err = v.Set("40.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("0:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("5255.255.255.255/19") + assert.Error(t, err) + err = v.Set("6:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("6255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("7:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int16]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12847,13 +12887,13 @@ func TestInt16IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int16]net.IPNet) - v := newInt16IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt16IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("40.0.0.256/16") + err = v.Set("30.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) @@ -12868,21 +12908,21 @@ func TestInt32IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]net.IPNet) - v := newInt32IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("00.0.0.0/0") + err = v.Set("60.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("2:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("7255.255.255.255/19") + assert.Error(t, err) + err = v.Set("7:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("5255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("1:255.255.255.255/19") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int32]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12891,13 +12931,13 @@ func TestInt32IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int32]net.IPNet) - v := newInt32IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt32IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("10.0.0.256/16") + err = v.Set("20.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) @@ -12912,21 +12952,21 @@ func TestInt64IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]net.IPNet) - v := newInt64IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("10.0.0.0/0") + err = v.Set("20.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("5:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("5255.255.255.255/19") + assert.Error(t, err) + err = v.Set("2:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("4255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) + assert.Error(t, err) err = v.Set("2:255.255.255.255/19") - assert.Nil(t, err) + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12935,14 +12975,14 @@ func TestInt64IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[int64]net.IPNet) - v := newInt64IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newInt64IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("10.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("1:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("2:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[int64]net.IPNet", v.Type()) @@ -12956,21 +12996,21 @@ func TestUintIPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]net.IPNet) - v := newUintIPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintIPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("40.0.0.0/0") + err = v.Set("60.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("7:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("1255.255.255.255/19") + assert.Error(t, err) + err = v.Set("6:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("2255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("7:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("2:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -12979,14 +13019,14 @@ func TestUintIPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint]net.IPNet) - v := newUintIPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUintIPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("60.0.0.256/16") + err = v.Set("50.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("2:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("1:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint]net.IPNet", v.Type()) @@ -13000,21 +13040,21 @@ func TestUint8IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]net.IPNet) - v := newUint8IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) err = v.Set("70.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("1:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("4255.255.255.255/19") + assert.Error(t, err) + err = v.Set("3:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("0255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("5:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("7:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -13023,14 +13063,14 @@ func TestUint8IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint8]net.IPNet) - v := newUint8IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint8IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("10.0.0.256/16") + err = v.Set("30.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("6:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("5:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint8]net.IPNet", v.Type()) @@ -13044,21 +13084,21 @@ func TestUint16IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]net.IPNet) - v := newUint16IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("40.0.0.0/0") + err = v.Set("50.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("7:0.0.0.0/0") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("1:0.0.0.0/0") + assert.NoError(t, err) err = v.Set("6255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("2:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -13067,14 +13107,14 @@ func TestUint16IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint16]net.IPNet) - v := newUint16IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint16IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("40.0.0.256/16") + err = v.Set("30.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("4:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("1:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint16]net.IPNet", v.Type()) @@ -13088,21 +13128,21 @@ func TestUint32IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]net.IPNet) - v := newUint32IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("70.0.0.0/0") + err = v.Set("10.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("4:0.0.0.0/0") - assert.Nil(t, err) - err = v.Set("1255.255.255.255/19") + assert.Error(t, err) + err = v.Set("2:0.0.0.0/0") + assert.NoError(t, err) + err = v.Set("5255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("2:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("6:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -13111,14 +13151,14 @@ func TestUint32IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint32]net.IPNet) - v := newUint32IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint32IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("50.0.0.256/16") + err = v.Set("40.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("5:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("4:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint32]net.IPNet", v.Type()) @@ -13132,21 +13172,21 @@ func TestUint64IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]net.IPNet) - v := newUint64IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("30.0.0.0/0") + err = v.Set("60.0.0.0/0") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.0/0") - assert.NotNil(t, err) - err = v.Set("1:0.0.0.0/0") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("3:0.0.0.0/0") + assert.NoError(t, err) err = v.Set("2255.255.255.255/19") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":255.255.255.255/19") - assert.NotNil(t, err) - err = v.Set("7:255.255.255.255/19") - assert.Nil(t, err) + assert.Error(t, err) + err = v.Set("0:255.255.255.255/19") + assert.NoError(t, err) assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]net.IPNet", v.Type()) assert.NotEmpty(t, v.String()) @@ -13155,14 +13195,14 @@ func TestUint64IPNetMapValue(t *testing.T) { t.Parallel() var err error a := make(map[uint64]net.IPNet) - v := newUint64IPNetMapValue(&a) - assert.Equal(t, parseGeneratedMap(&a), v) + v := newUint64IPNetMapValue(&a, nil) + assert.Equal(t, ParseGeneratedMap(&a, nil), v) assert.True(t, v.IsCumulative()) - err = v.Set("50.0.0.256/16") + err = v.Set("60.0.0.256/16") assert.EqualError(t, err, "invalid map flag syntax, use -map=key1:val1") err = v.Set(":0.0.0.256/16") - assert.NotNil(t, err) - err = v.Set("1:0.0.0.256/16") + assert.Error(t, err) + err = v.Set("7:0.0.0.256/16") assert.EqualError(t, err, "invalid CIDR address: 0.0.0.256/16") assert.Equal(t, a, v.Get()) assert.Equal(t, "map[uint64]net.IPNet", v.Type()) @@ -13173,6 +13213,6 @@ func TestUint64IPNetMapValue(t *testing.T) { func TestParseGeneratedMap_NilDefault(t *testing.T) { t.Parallel() a := new(bool) - v := parseGeneratedMap(a) + v := ParseGeneratedMap(a, nil) assert.Nil(t, v) } diff --git a/internal/values/values_test.go b/internal/values/values_test.go new file mode 100644 index 0000000..f29a793 --- /dev/null +++ b/internal/values/values_test.go @@ -0,0 +1,100 @@ +package values + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/reeflective/flags/types" +) + +func TestCounter_Set(t *testing.T) { + t.Parallel() + var err error + + initial := 0 + counter := (*types.Counter)(&initial) + + require.Equal(t, 0, initial) + require.Equal(t, "0", counter.String()) + require.Equal(t, 0, counter.Get()) + require.True(t, counter.IsBoolFlag()) + require.True(t, counter.IsCumulative()) + + err = counter.Set("") + require.NoError(t, err) + require.Equal(t, 1, initial) + require.Equal(t, "1", counter.String()) + + err = counter.Set("10") + require.NoError(t, err) + require.Equal(t, 10, initial) + require.Equal(t, "10", counter.String()) + + err = counter.Set("-1") + require.NoError(t, err) + require.Equal(t, 11, initial) + require.Equal(t, "11", counter.String()) + + err = counter.Set("b") + require.Error(t, err, "strconv.ParseInt: parsing \"b\": invalid syntax") + require.Equal(t, 11, initial) + require.Equal(t, "11", counter.String()) +} + +func TestBoolValue_IsBoolFlag(t *testing.T) { + t.Parallel() + b := &boolValue{} + require.True(t, b.IsBoolFlag()) +} + +func TestValidateValue_IsBoolFlag(t *testing.T) { + t.Parallel() + boolV := true + v := &validateValue{Value: newBoolValue(&boolV)} + require.True(t, v.IsBoolFlag()) + + v = &validateValue{Value: newStringValue(strP("stringValue"))} + require.False(t, v.IsBoolFlag()) +} + +func TestValidateValue_IsCumulative(t *testing.T) { + t.Parallel() + v := &validateValue{Value: newStringValue(strP("stringValue"))} + require.False(t, v.IsCumulative()) + + v = &validateValue{Value: newStringSliceValue(&[]string{}, nil)} + require.True(t, v.IsCumulative()) +} + +func TestValidateValue_String(t *testing.T) { + t.Parallel() + v := &validateValue{Value: newStringValue(strP("stringValue"))} + require.Equal(t, "stringValue", v.String()) + + v = &validateValue{Value: nil} + require.Empty(t, v.String()) +} + +func TestValidateValue_Set(t *testing.T) { + t.Parallel() + sV := strP("stringValue") + v := &validateValue{Value: newStringValue(sV)} + require.NoError(t, v.Set("newVal")) + require.Equal(t, "newVal", *sV) + + v.validateFunc = func(_ string) error { + return nil + } + require.NoError(t, v.Set("newVal")) + + v.validateFunc = func(val string) error { + return fmt.Errorf("invalid %s", val) + } + require.EqualError(t, v.Set("newVal"), "invalid newVal") +} + +func strP(value string) *string { + return &value +} diff --git a/options.go b/options.go deleted file mode 100644 index e3f05ca..0000000 --- a/options.go +++ /dev/null @@ -1,60 +0,0 @@ -package flags - -import ( - "github.com/reeflective/flags/internal/scan" -) - -// ValidateFunc describes a validation func, that takes string val for flag from command line, -// field that's associated with this flag in structure cfg. Also works for positional arguments. -// Should return error if validation fails. -type ValidateFunc scan.ValidateFunc - -// FlagFunc is a generic function that can be applied to each -// value that will end up being a flags *Flag, so that users -// can perform more arbitrary operations on each, such as checking -// for completer implementations, bind to viper configurations, etc. -type FlagFunc scan.FlagFunc - -// OptFunc sets values in opts structure. -type OptFunc scan.OptFunc - -type opts scan.Opts - -// DescTag sets custom description tag. It is "desc" by default. -func DescTag(val string) OptFunc { return func(opt *scan.Opts) { opt.DescTag = val } } - -// FlagTag sets custom flag tag. It is "flag" be default. -func FlagTag(val string) OptFunc { return func(opt *scan.Opts) { opt.FlagTag = val } } - -// Prefix sets prefix that will be applied for all flags (if they are not marked as ~). -func Prefix(val string) OptFunc { return func(opt *scan.Opts) { opt.Prefix = val } } - -// EnvPrefix sets prefix that will be applied for all environment variables (if they are not marked as ~). -func EnvPrefix(val string) OptFunc { return func(opt *scan.Opts) { opt.EnvPrefix = val } } - -// FlagDivider sets custom divider for flags. It is dash by default. e.g. "flag-name". -func FlagDivider(val string) OptFunc { return func(opt *scan.Opts) { opt.FlagDivider = val } } - -// EnvDivider sets custom divider for environment variables. -// It is underscore by default. e.g. "ENV_NAME". -func EnvDivider(val string) OptFunc { return func(opt *scan.Opts) { opt.EnvDivider = val } } - -// Flatten set flatten option. -// Set to false if you don't want anonymous structure fields to be flatten. -func Flatten(val bool) OptFunc { return func(opt *scan.Opts) { opt.Flatten = val } } - -// ParseAll orders the parser to generate a flag for all struct fields, -// even if there isn't a struct tag attached to them. -func ParseAll() OptFunc { return func(opt *scan.Opts) { opt.ParseAll = true } } - -// Validator sets validator function for flags. -// Check existing validators in flags/validator and flags/validator/govalidator packages. -func Validator(val ValidateFunc) OptFunc { - return func(opt *scan.Opts) { opt.Validator = scan.ValidateFunc(val) } -} - -// FlagHandler sets the handler function for flags, in order to perform arbitrary -// operations on the value of the flag identified by the name parameter of FlagFunc. -func FlagHandler(val FlagFunc) OptFunc { - return func(opt *scan.Opts) { opt.FlagFunc = scan.FlagFunc(val) } -} diff --git a/parser.go b/parser.go deleted file mode 100644 index c603b5e..0000000 --- a/parser.go +++ /dev/null @@ -1,286 +0,0 @@ -package flags - -import ( - "fmt" - "reflect" - "unicode/utf8" - - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" - "github.com/reeflective/flags/internal/validation" -) - -// ParseStruct parses structure and returns list of flags based on this structure. -// This list of flags can be used by generators for flag, kingpin, cobra, pflag, urfave/cli. -func ParseStruct(cfg interface{}, optFuncs ...OptFunc) ([]*Flag, error) { - // what we want is Ptr to Structure - if cfg == nil { - return nil, ErrObjectIsNil - } - - v := reflect.ValueOf(cfg) - - if v.Kind() != reflect.Ptr { - return nil, ErrNotPointerToStruct - } - - if v.IsNil() { - return nil, ErrObjectIsNil - } - - switch e := v.Elem(); e.Kind() { - case reflect.Struct: - return parseStruct(e, optFuncs...) - default: - return nil, ErrNotPointerToStruct - } -} - -// ParseField parses a single struct field as a list (often only made of only one) flags. -// This function can be used when you want to scan only some fields for which you want a flag. -func ParseField(value reflect.Value, field reflect.StructField, optFuncs ...OptFunc) ([]*Flag, bool, error) { - // Check struct tags, parse the field value if needed, and return the whole. - flag, tag, scanOpts, err := parseInfo(field, optFuncs...) - if err != nil { - return nil, true, err - } - - if flag == nil { - return nil, false, nil - } - - options := OptFunc(scan.CopyOpts(scanOpts)) - - // We might have to scan for an arbitrarily nested structure of flags - flagSet, val, err := parseVal(value, options) - if err != nil { - return flagSet, true, err - } - - // The flag value, at this point, should always implement the flag Value interface, - // otherwise it is not considered a valid flag - if markedFlagNotImplementing(*tag, val) { - errImpl := fmt.Errorf("%w: field %s (tagged flag '%s') does not implement Value interface", - ErrNotValue, field.Name, flag.Name) - - return flagSet, true, errImpl - } - - // If our value is nil, we don't have to perform further validations on it, - // and we only add flags if we have parsed some on our struct field value. - if val == nil { - return flagSet, true, nil - } - - // Set validators if any, user-defined or builtin - if validator := validation.Bind(value, field, flag.Choices, scanOpts); validator != nil { - val = &validateValue{ - Value: val, - validateFunc: validator, - } - } - - flag.Value = val - flagSet = append(flagSet, flag) - - // The default value, if set through tags, is always - // overridden by the current value of the field. - if val.String() != "" { - flag.DefValue = append(flag.DefValue, val.String()) - } - - // If the user provided some custom flag - // value handlers/scanners, run on it. - if scanOpts.FlagFunc != nil { - var name string - if flag.Name != "" { - name = flag.Name - } else { - name = flag.Short - } - - // Any failure to apply a flag handler is reported and will lead to exit - if err := scanOpts.FlagFunc(name, *tag, value); err != nil { - return flagSet, true, fmt.Errorf("%w on flag %s: %s", ErrFlagHandler, name, err.Error()) - } - } - - return flagSet, true, nil -} - -// parseInfo parses the struct field tag, adapts for any scan options that would have been modified by tags. -func parseInfo(fld reflect.StructField, optFuncs ...OptFunc) (*Flag, *tag.MultiTag, scan.Opts, error) { - var scanOpts []scan.OptFunc - for _, optFunc := range optFuncs { - scanOpts = append(scanOpts, scan.OptFunc(optFunc)) - } - scanOptions := scan.DefOpts().Apply(scanOpts...) - options := opts(scanOptions) - - // skip unexported and non anonymous fields - if fld.PkgPath != "" && !fld.Anonymous { - return nil, nil, scanOptions, nil - } - - // We should have a flag and a tag, legacy or not, and with valid values. - flag, tag, err := parseFlagTag(fld, options) - if flag == nil || err != nil { - return flag, tag, scanOptions, err - } - - // Various prefixing checks and steps - flag.EnvName = parseEnvTag(flag.Name, fld, options) - prefix := flag.Name + options.FlagDivider - - if fld.Anonymous && options.Flatten { - prefix = options.Prefix - } - - scanOpts = append(scanOpts, scan.OptFunc(Prefix(prefix))) - - // Return an update list of scan options, - // which might have been influenced by the tags. - scanOptions = scanOptions.Apply(scanOpts...) - - return flag, tag, scanOptions, err -} - -func parseVal(value reflect.Value, optFuncs ...OptFunc) ([]*Flag, Value, error) { - // value is addressable, let's check if we can parse it - if value.CanAddr() && value.Addr().CanInterface() { - valueInterface := value.Addr().Interface() - val := parseGenerated(valueInterface) - - if val != nil { - return nil, val, nil - } - // check if field implements Value interface - if val, casted := valueInterface.(Value); casted { - return nil, val, nil - } - } - - switch value.Kind() { - case reflect.Ptr: - if value.IsNil() { - value.Set(reflect.New(value.Type().Elem())) - } - - val := parseGeneratedPtrs(value.Addr().Interface()) - - if val != nil { - return nil, val, nil - } - - return parseVal(value.Elem(), optFuncs...) - - case reflect.Struct: - flags, err := parseStruct(value, optFuncs...) - - return flags, nil, err - - case reflect.Map: - val := parseMap(value) - - return nil, val, nil - } - - return nil, nil, nil -} - -func parseStruct(value reflect.Value, optFuncs ...OptFunc) ([]*Flag, error) { - flags := []*Flag{} - - valueType := value.Type() -fields: - for i := 0; i < value.NumField(); i++ { - field := valueType.Field(i) - fieldValue := value.Field(i) - // skip unexported and non anonymous fields - if field.PkgPath != "" && !field.Anonymous { - continue fields - } - - // Scan the field, potentially a structure, any error stops the process - fieldFlags, found, err := ParseField(fieldValue, field, optFuncs...) - if err != nil { - return flags, err - } - - if !found || len(fieldFlags) == 0 { - continue fields - } - - // And append the flag(s) if we have found some. - flags = append(flags, fieldFlags...) - - continue fields - } - - return flags, nil -} - -func parseMap(value reflect.Value) Value { - mapType := value.Type() - keyKind := value.Type().Key().Kind() - - // check that map key is string or integer - if !anyOf(MapAllowedKinds, keyKind) { - return nil - } - - if value.IsNil() { - value.Set(reflect.MakeMap(mapType)) - } - - valueInterface := value.Addr().Interface() - val := parseGeneratedMap(valueInterface) - - return val -} - -// Tells us if a struct field tagged as a flag does not implement the Value interface. -func markedFlagNotImplementing(tag tag.MultiTag, val Value) bool { - _, flagOld := tag.Get("flag") - _, short := tag.Get("short") - _, long := tag.Get("long") - - if (flagOld || short || long) && val == nil { - return true - } - - return false -} - -func anyOf(kinds []reflect.Kind, needle reflect.Kind) bool { - for _, kind := range kinds { - if kind == needle { - return true - } - } - - return false -} - -func isStringFalsy(s string) bool { - return s == "" || s == "false" || s == "no" || s == "0" -} - -func getShortName(name string) (rune, error) { - short := rune(0) - runeCount := utf8.RuneCountInString(name) - - // Either an invalid option name - if runeCount > 1 { - msg := fmt.Sprintf("flag `%s'", name) - - return short, newError(ErrShortNameTooLong, msg) - } - - // Or we have to decode and return - if runeCount == 1 { - short, _ = utf8.DecodeRuneInString(name) - } - - return short, nil -} diff --git a/parser_test.go b/parser_test.go deleted file mode 100644 index 9a4b6c3..0000000 --- a/parser_test.go +++ /dev/null @@ -1,503 +0,0 @@ -package flags - -import ( - "errors" - "net" - "reflect" - "regexp" - "testing" - - "github.com/reeflective/flags/internal/scan" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func strP(value string) *string { - return &value -} - -type simple struct { - Name string -} - -func TestParseStruct(t *testing.T) { - simpleCfg := &struct { - Name string `desc:"name description" env:"-"` - Name2 string `flag:"name_two t,hidden,deprecated"` - Name3 string `env:"NAME_THREE"` - Name4 *string - Name5 string `flag:"-"` - name6 string - - Addr *net.TCPAddr - - Map map[string]int - }{ - Name: "name_value", - Name2: "name2_value", - Name4: strP("name_value4"), - Addr: &net.TCPAddr{ - IP: net.ParseIP("127.0.0.1"), - }, - name6: "name6_value", - Map: map[string]int{"test": 15}, - } - diffTypesCfg := &struct { - StringValue string - ByteValue byte - StringSliceValue []string - BoolSliceValue []bool - CounterValue Counter - RegexpValue *regexp.Regexp - FuncValue func() // will be ignored - MapInt8Bool map[int8]bool - MapInt16Int8 map[int16]int8 - MapStringInt64 map[string]int64 - MapStringString map[string]string - MapBoolString map[bool]string - }{ - StringValue: "string", - ByteValue: 10, - StringSliceValue: []string{}, - BoolSliceValue: []bool{}, - CounterValue: 10, - RegexpValue: ®exp.Regexp{}, - MapStringInt64: map[string]int64{"test": 888}, - MapStringString: map[string]string{"test": "test-val"}, - } - nestedCfg := &struct { - Sub struct { - Name string `desc:"name description"` - Name2 string `env:"NAME_TWO"` - Name3 string `flag:"~name3" env:"~NAME_THREE"` - SUB2 *struct { - Name4 string - Name5 string `env:"name_five"` - } - } - }{ - Sub: struct { - Name string `desc:"name description"` - Name2 string `env:"NAME_TWO"` - Name3 string `flag:"~name3" env:"~NAME_THREE"` - SUB2 *struct { - Name4 string - Name5 string `env:"name_five"` - } - }{ - Name: "name_value", - Name2: "name2_value", - SUB2: &struct { - Name4 string - Name5 string `env:"name_five"` - }{ - Name4: "name4_value", - }, - }, - } - descCfg := &struct { - Name string `desc:"name description"` - Name2 string `description:"name2 description"` - }{} - anonymousCfg := &struct { - Name1 string - simple - }{ - simple: simple{ - Name: "name_value", - }, - } - - tt := []struct { - name string - - cfg interface{} - optFuncs []OptFunc - expFlagSet []*Flag - expErr error - }{ - { - name: "SimpleCfg test", - cfg: simpleCfg, - optFuncs: []OptFunc{ParseAll()}, - expFlagSet: []*Flag{ - { - Name: "name", - EnvName: "", - DefValue: []string{"name_value"}, - Value: newStringValue(&simpleCfg.Name), - Usage: "name description", - }, - { - Name: "name_two", - Short: "t", - EnvName: "NAME_TWO", - DefValue: []string{"name2_value"}, - Value: newStringValue(&simpleCfg.Name2), - Hidden: true, - Deprecated: true, - }, - { - Name: "name3", - EnvName: "NAME_THREE", - DefValue: []string{""}, - Value: newStringValue(&simpleCfg.Name3), - }, - { - Name: "name4", - EnvName: "NAME4", - DefValue: []string{"name_value4"}, - Value: newStringValue(simpleCfg.Name4), - }, - { - Name: "addr", - EnvName: "ADDR", - DefValue: []string{"127.0.0.1:0"}, - Value: newTCPAddrValue(simpleCfg.Addr), - }, - { - Name: "map", - EnvName: "MAP", - DefValue: []string{"map[test:15]"}, - Value: newStringIntMapValue(&simpleCfg.Map), - }, - }, - }, - { - name: "SimpleCfg test with custom env_prefix and divider", - cfg: simpleCfg, - optFuncs: []OptFunc{EnvPrefix("PP|"), EnvDivider("|"), ParseAll()}, - expFlagSet: []*Flag{ - { - Name: "name", - EnvName: "", - DefValue: []string{"name_value"}, - Value: newStringValue(&simpleCfg.Name), - Usage: "name description", - }, - { - Name: "name_two", - Short: "t", - EnvName: "PP|NAME_TWO", - DefValue: []string{"name2_value"}, - Value: newStringValue(&simpleCfg.Name2), - Hidden: true, - Deprecated: true, - }, - { - Name: "name3", - EnvName: "PP|NAME_THREE", - DefValue: []string{""}, - Value: newStringValue(&simpleCfg.Name3), - }, - { - Name: "name4", - EnvName: "PP|NAME4", - DefValue: []string{"name_value4"}, - Value: newStringValue(simpleCfg.Name4), - }, - { - Name: "addr", - EnvName: "PP|ADDR", - DefValue: []string{"127.0.0.1:0"}, - Value: newTCPAddrValue(simpleCfg.Addr), - }, - { - Name: "map", - EnvName: "PP|MAP", - DefValue: []string{"map[test:15]"}, - Value: newStringIntMapValue(&simpleCfg.Map), - }, - }, - expErr: nil, - }, - { - name: "DifferentTypesCfg", - cfg: diffTypesCfg, - optFuncs: []OptFunc{ParseAll()}, - expFlagSet: []*Flag{ - { - Name: "string-value", - EnvName: "STRING_VALUE", - DefValue: []string{"string"}, - Value: newStringValue(&diffTypesCfg.StringValue), - Usage: "", - }, - { - Name: "byte-value", - EnvName: "BYTE_VALUE", - DefValue: []string{"10"}, - Value: newUint8Value(&diffTypesCfg.ByteValue), - Usage: "", - }, - { - Name: "string-slice-value", - EnvName: "STRING_SLICE_VALUE", - DefValue: []string{"[]"}, - Value: newStringSliceValue(&diffTypesCfg.StringSliceValue), - Usage: "", - }, - { - Name: "bool-slice-value", - EnvName: "BOOL_SLICE_VALUE", - DefValue: []string{"[]"}, - Value: newBoolSliceValue(&diffTypesCfg.BoolSliceValue), - Usage: "", - }, - { - Name: "counter-value", - EnvName: "COUNTER_VALUE", - DefValue: []string{"10"}, - Value: &diffTypesCfg.CounterValue, - Usage: "", - }, - { - Name: "regexp-value", - EnvName: "REGEXP_VALUE", - DefValue: []string{""}, - Value: newRegexpValue(&diffTypesCfg.RegexpValue), - Usage: "", - }, - { - Name: "map-int8-bool", - EnvName: "MAP_INT8_BOOL", - DefValue: []string{""}, - Value: newInt8BoolMapValue(&diffTypesCfg.MapInt8Bool), - }, - { - Name: "map-int16-int8", - EnvName: "MAP_INT16_INT8", - DefValue: []string{""}, - Value: newInt16Int8MapValue(&diffTypesCfg.MapInt16Int8), - }, - { - Name: "map-string-int64", - EnvName: "MAP_STRING_INT64", - DefValue: []string{"map[test:888]"}, - Value: newStringInt64MapValue(&diffTypesCfg.MapStringInt64), - }, - { - Name: "map-string-string", - EnvName: "MAP_STRING_STRING", - DefValue: []string{"map[test:test-val]"}, - Value: newStringStringMapValue(&diffTypesCfg.MapStringString), - }, - }, - }, - { - name: "NestedCfg", - cfg: nestedCfg, - optFuncs: []OptFunc{ParseAll()}, - expFlagSet: []*Flag{ - { - Name: "sub-name", - EnvName: "SUB_NAME", - DefValue: []string{"name_value"}, - Value: newStringValue(&nestedCfg.Sub.Name), - Usage: "name description", - }, - { - Name: "sub-name2", - EnvName: "SUB_NAME_TWO", - DefValue: []string{"name2_value"}, - Value: newStringValue(&nestedCfg.Sub.Name2), - }, - { - Name: "name3", - EnvName: "NAME_THREE", - DefValue: []string{""}, - Value: newStringValue(&nestedCfg.Sub.Name3), - }, - { - Name: "sub-sub2-name4", - EnvName: "SUB_SUB2_NAME4", - DefValue: []string{"name4_value"}, - Value: newStringValue(&nestedCfg.Sub.SUB2.Name4), - }, - { - Name: "sub-sub2-name5", - EnvName: "SUB_SUB2_name_five", - DefValue: []string{""}, - Value: newStringValue(&nestedCfg.Sub.SUB2.Name5), - }, - }, - expErr: nil, - }, - { - name: "DescCfg with custom desc tag", - cfg: descCfg, - optFuncs: []OptFunc{DescTag("description")}, - expFlagSet: []*Flag{ - { - Name: "name", - EnvName: "NAME", - Value: newStringValue(&descCfg.Name), - Usage: "name description", - }, - { - Name: "name2", - EnvName: "NAME2", - Value: newStringValue(&descCfg.Name2), - Usage: "name2 description", - }, - }, - }, - { - name: "Anonymoust cfg with disabled flatten", - cfg: anonymousCfg, - optFuncs: []OptFunc{ParseAll()}, - expFlagSet: []*Flag{ - { - Name: "name1", - EnvName: "NAME1", - Value: newStringValue(&anonymousCfg.Name1), - }, - { - Name: "name", - EnvName: "NAME", - DefValue: []string{"name_value"}, - Value: newStringValue(&anonymousCfg.Name), - }, - }, - }, - { - name: "Anonymoust cfg with enabled flatten", - cfg: anonymousCfg, - optFuncs: []OptFunc{Flatten(false), ParseAll()}, - expFlagSet: []*Flag{ - { - Name: "name1", - EnvName: "NAME1", - Value: newStringValue(&anonymousCfg.Name1), - }, - { - Name: "simple-name", - EnvName: "SIMPLE_NAME", - DefValue: []string{"name_value"}, - Value: newStringValue(&anonymousCfg.Name), - }, - }, - }, - { - name: "We need pointer to structure", - cfg: struct{}{}, - expErr: errors.New("object must be a pointer to struct or interface"), - }, - { - name: "We need pointer to structure 2", - cfg: strP("something"), - expErr: errors.New("object must be a pointer to struct or interface"), - }, - { - name: "We need non nil object", - cfg: nil, - expErr: errors.New("object cannot be nil"), - }, - { - name: "We need non nil value", - cfg: (*simple)(nil), - expErr: errors.New("object cannot be nil"), - }, - } - for _, test := range tt { - t.Run(test.name, func(t *testing.T) { - t.Parallel() - flagSet, err := ParseStruct(test.cfg, test.optFuncs...) - if test.expErr == nil { - require.NoError(t, err) - } else { - require.Equal(t, test.expErr, err) - } - assert.Equal(t, test.expFlagSet, flagSet) - }) - } -} - -func TestParseStruct_NilValue(t *testing.T) { - t.Parallel() - name2Value := "name2_value" - cfg := struct { - Name1 *string - Name2 *string - Regexp *regexp.Regexp - }{ - Name2: &name2Value, - } - assert.Nil(t, cfg.Name1) - assert.Nil(t, cfg.Regexp) - assert.NotNil(t, cfg.Name2) - - flags, err := ParseStruct(&cfg, ParseAll()) - require.NoError(t, err) - require.Equal(t, 3, len(flags)) - assert.NotNil(t, cfg.Name1) - assert.NotNil(t, cfg.Name2) - assert.NotNil(t, cfg.Regexp) - assert.Equal(t, name2Value, flags[1].Value.(Getter).Get()) - - err = flags[0].Value.Set("name1value") - require.NoError(t, err) - assert.Equal(t, "name1value", *cfg.Name1) - - err = flags[2].Value.Set("aabbcc") - require.NoError(t, err) - assert.Equal(t, "aabbcc", cfg.Regexp.String()) -} - -func TestParseStruct_WithValidator(t *testing.T) { - t.Parallel() - var cfg simple - - testErr := errors.New("validator test error") - - validator := Validator(func(val string, field reflect.StructField, cfg interface{}) error { - return testErr - }) - - flags, err := ParseStruct(&cfg, validator, ParseAll()) - require.NoError(t, err) - require.Equal(t, 1, len(flags)) - assert.NotNil(t, cfg.Name) - - err = flags[0].Value.Set("aabbcc") - require.Error(t, err) - assert.Equal(t, testErr, err) -} - -func TestFlagDivider(t *testing.T) { - t.Parallel() - opt := scan.Opts{ - FlagDivider: "-", - } - FlagDivider("_")(&opt) - assert.Equal(t, "_", opt.FlagDivider) -} - -func TestFlagTag(t *testing.T) { - t.Parallel() - opt := scan.Opts{ - FlagTag: "flags", - } - FlagTag("superflag")(&opt) - assert.Equal(t, "superflag", opt.FlagTag) -} - -func TestValidator(t *testing.T) { - t.Parallel() - opt := scan.Opts{ - Validator: nil, - } - Validator(func(string, reflect.StructField, interface{}) error { - return nil - })(&opt) - assert.NotNil(t, opt.Validator) -} - -func TestFlatten(t *testing.T) { - t.Parallel() - opt := scan.Opts{ - Flatten: true, - } - Flatten(false)(&opt) - assert.Equal(t, false, opt.Flatten) -} diff --git a/tag.go b/tag.go deleted file mode 100644 index 8b2d908..0000000 --- a/tag.go +++ /dev/null @@ -1,227 +0,0 @@ -package flags - -import ( - "fmt" - "reflect" - "strings" - - "github.com/reeflective/flags/internal/scan" - "github.com/reeflective/flags/internal/tag" -) - -// parseFlagTag now also handles some of the tags used in jessevdk/go-flags. -func parseFlagTag(field reflect.StructField, options opts) (*Flag, *tag.MultiTag, error) { - flag := &Flag{} - - ignorePrefix := false - flag.Name = camelToFlag(field.Name, options.FlagDivider) - - // Parse the struct tag - flagTags, skip, err := getFlagTags(field, options) - if err != nil { - return nil, nil, err - } - - if skip { - return nil, nil, nil - } - - // Parse all base struct tag flags attributes and populate the flag object. - if skip, ignorePrefix = parseBaseAttributes(flagTags, flag, options); skip { - return nil, flagTags, nil - } - - setFlagDefaultValues(flag, flagTags.GetMany("default")) - setFlagChoices(flag, flagTags.GetMany("choice")) - setFlagOptionalValues(flag, flagTags.GetMany("optional-value")) - - if options.Prefix != "" && !ignorePrefix { - flag.Name = options.Prefix + flag.Name - } - - hidden, _ := flagTags.Get("hidden") - flag.Hidden = hidden != "" - - return flag, flagTags, nil -} - -// getFlagTags tries to parse any struct tag we need, and tells the caller if -// we should actually build a flag object out of the struct field, or skip it. -func getFlagTags(field reflect.StructField, options opts) (*tag.MultiTag, bool, error) { - flagTags, none, err := tag.GetFieldTag(field) - if err != nil { - return nil, true, fmt.Errorf("%w: %s", ErrTag, err.Error()) - } - - // If the global options specify that we must build a flag - // out of each struct field, regardless of them being tagged. - if options.ParseAll { - return &flagTags, false, nil - } - - // Else we skip this field only if there's not tag on it - if none { - return &flagTags, true, nil - } - - // Or if there is a "no-flag" tag - if noFlag, _ := flagTags.Get("no-flag"); noFlag != "" { - return &flagTags, true, nil - } - - return &flagTags, false, nil -} - -// parseBaseAttributes checks which type of struct tags we found, parses them -// accordingly (legacy, or not), taking into account any global config settings. -func parseBaseAttributes(flagTags *tag.MultiTag, flag *Flag, options opts) (skip, ignorePrefix bool) { - sflagsTag, _ := flagTags.Get(options.FlagTag) - sflagValues := strings.Split(sflagsTag, ",") - - if sflagsTag != "" && len(sflagValues) > 0 { - // Either we have found the legacy flags tag value. - skip, ignorePrefix = parseflagsTag(sflagsTag, flag) - if skip { - return true, false - } - } else { - // Or we try for the go-flags tags. - parseGoFlagsTag(flagTags, flag) - } - - // Descriptions - if desc, isSet := flagTags.Get("desc"); isSet && desc != "" { - flag.Usage = desc - } else if desc, isSet := flagTags.Get("description"); isSet && desc != "" { - flag.Usage = desc - } - - // Requirements - if required, _ := flagTags.Get("required"); !isStringFalsy(required) { - flag.Required = true - } - - return false, ignorePrefix -} - -// parseflagsTag parses only the original tag values of this library flags. -func parseflagsTag(flagsTag string, flag *Flag) (skip, ignorePrefix bool) { - values := strings.Split(flagsTag, ",") - - // Base / legacy flags tag - switch fName := values[0]; fName { - case "-": - return true, ignorePrefix - case "": - default: - fNameSplitted := strings.Split(fName, " ") - if len(fNameSplitted) > 1 { - fName = fNameSplitted[0] - flag.Short = fNameSplitted[1] - } - - if strings.HasPrefix(fName, "~") { - flag.Name = fName[1:] - ignorePrefix = true - } else { - flag.Name = fName - } - } - - flag.Hidden = hasOption(values[1:], "hidden") - flag.Deprecated = hasOption(values[1:], "deprecated") - - return false, ignorePrefix -} - -// parseGoFlagsTag parses only the tags used by jessevdk/go-flags. -func parseGoFlagsTag(flagTags *tag.MultiTag, flag *Flag) { - if short, found := flagTags.Get("short"); found && short != "" { - shortR, err := getShortName(short) - if err == nil { - flag.Short = string(shortR) - } - if long, found := flagTags.Get("long"); found && long != "" { - flag.Name, _ = flagTags.Get("long") - } - } else if long, found := flagTags.Get("long"); found && long != "" { - // Or we have only a short tag being specified. - flag.Name = long - } -} - -func parseEnvTag(flagName string, field reflect.StructField, options opts) string { - ignoreEnvPrefix := false - envVar := flagToEnv(flagName, options.FlagDivider, options.EnvDivider) - - if envTags := strings.Split(field.Tag.Get(scan.DefaultEnvTag), ","); len(envTags) > 0 { - switch envName := envTags[0]; envName { - case "-": - // if tag is `env:"-"` then won't fill flag from environment - envVar = "" - case "": - // if tag is `env:""` then env var will be taken from flag name - default: - // if tag is `env:"NAME"` then env var is envPrefix_flagPrefix_NAME - // if tag is `env:"~NAME"` then env var is NAME - if strings.HasPrefix(envName, "~") { - envVar = envName[1:] - ignoreEnvPrefix = true - } else { - envVar = envName - if options.Prefix != "" { - envVar = flagToEnv( - options.Prefix, - options.FlagDivider, - options.EnvDivider) + envVar - } - } - } - } - - if envVar != "" && options.EnvPrefix != "" && !ignoreEnvPrefix { - envVar = options.EnvPrefix + envVar - } - - return envVar -} - -func setFlagDefaultValues(flag *Flag, choices []string) { - var allChoices []string - - for _, choice := range choices { - allChoices = append(allChoices, strings.Split(choice, " ")...) - } - - flag.DefValue = allChoices -} - -func setFlagChoices(flag *Flag, choices []string) { - var allChoices []string - - for _, choice := range choices { - allChoices = append(allChoices, strings.Split(choice, " ")...) - } - - flag.Choices = allChoices -} - -func setFlagOptionalValues(flag *Flag, choices []string) { - var allChoices []string - - for _, choice := range choices { - allChoices = append(allChoices, strings.Split(choice, " ")...) - } - - flag.OptionalValue = allChoices -} - -func hasOption(options []string, option string) bool { - for _, opt := range options { - if opt == option { - return true - } - } - - return false -} diff --git a/types/types.go b/types/types.go new file mode 100644 index 0000000..188dcfc --- /dev/null +++ b/types/types.go @@ -0,0 +1,50 @@ +// Package types provides useful, pre-built implementations of the flags.Value +// interface for common use cases. +package types + +import ( + "fmt" + "strconv" +) + +// Counter is a flag type that increments its value each time it appears on the +// command line. It can be used as a boolean flag (`-vvv`) or with a value +// (`--verbose=3`). +type Counter int + +// Set implements the flags.Value interface. +func (c *Counter) Set(val string) error { + if val == "" || val == "true" { + *c++ + + return nil + } + + parsed, err := strconv.ParseInt(val, 0, 0) + if err != nil { + return fmt.Errorf("invalid value for counter: %w", err) + } + + if parsed == -1 { + *c++ + } else { + *c = Counter(parsed) + } + + return nil +} + +// Get returns inner value for Counter. +func (c *Counter) Get() any { return int(*c) } + +// IsBoolFlag returns true, because Counter might be used without value. +func (c *Counter) IsBoolFlag() bool { return true } + +// String implements the flags.Value interface. +func (c *Counter) String() string { return strconv.Itoa(int(*c)) } + +// IsCumulative returns true, because Counter might be used multiple times. +func (c *Counter) IsCumulative() bool { return true } + +// Type implements the flags.Value interface. +func (c *Counter) Type() string { return "count" } diff --git a/validator/govalidator/govalidator.go b/validator/govalidator/govalidator.go deleted file mode 100644 index e0ebc9e..0000000 --- a/validator/govalidator/govalidator.go +++ /dev/null @@ -1,187 +0,0 @@ -// Package govalidator adds support for govalidator library. -// Part of this package was taken from govalidator private api -// and covered by MIT license. -// -// The MIT License (MIT) -// -// Copyright (c) 2014 Alex Saskevich -// -// 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. -package govalidator - -import ( - "fmt" - "reflect" - "strings" - "unicode" - - "github.com/asaskevich/govalidator" -) - -const ( - validTag = "valid" // tag isn't optional in govalidator -) - -type tagOptionsMap map[string]string - -func isValidTag(s string) bool { - if s == "" { - return false - } - - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - - return true -} - -// parseTagIntoMap parses a struct tag `valid:"required~Some error message,length(2|3)"` into map[string]string{"required": "Some error message", "length(2|3)": ""}. -func parseTagIntoMap(tag string) tagOptionsMap { - optionsMap := make(tagOptionsMap) - - options := strings.Split(tag, ",") - - for _, option := range options { - validationOptions := strings.Split(option, "~") - if !isValidTag(validationOptions[0]) { - continue - } - - if len(validationOptions) == 2 { - optionsMap[validationOptions[0]] = validationOptions[1] - } else { - optionsMap[validationOptions[0]] = "" - } - } - - return optionsMap -} - -// New returns ValidateFunc for govalidator library. -// Supports default String validators in TagMap and ParamTagMap. -// Doesn't support custom type validators and required filters. -// Please check all available functions at https://github.com/asaskevich/govalidator. -func New() func(val string, field reflect.StructField, obj interface{}) error { - return func(val string, field reflect.StructField, obj interface{}) error { - options := parseTagIntoMap(field.Tag.Get(validTag)) - return validateFunc(val, options) - } -} - -func validateFunc(val string, options tagOptionsMap) error { - // for each tag option check the map of validator functions - for validator, customErrorMessage := range options { - var negate bool - - customMsgExists := len(customErrorMessage) > 0 - - // Check wether the tag looks like '!something' or 'something' - if validator[0] == '!' { - validator = validator[1:] - negate = true - } - - // Check for param validators - if err := findParamValidators(customMsgExists, negate, val, validator, customErrorMessage); err != nil { - return err - } - - // Or return with the builtin govalidator tag map - if err := validateWithTagMap(customMsgExists, negate, val, validator, customErrorMessage); err != nil { - return err - } - } - - return nil -} - -func findParamValidators(customError, negate bool, val, validator, customMsg string) error { - for key, value := range govalidator.ParamTagRegexMap { - ps := value.FindStringSubmatch(validator) - - if len(ps) == 0 { - continue - } - - validatefunc, ok := govalidator.ParamTagMap[key] - if !ok { - continue - } - - if result := validatefunc(val, ps[1:]...); (!result && !negate) || (result && negate) { - var err error - - if !negate { - if customError { - err = fmt.Errorf(customMsg) - } else { - err = fmt.Errorf("`%s` does not validate as %s", val, validator) - } - } else { - if customError { - err = fmt.Errorf(customMsg) - } else { - err = fmt.Errorf("`%s` does validate as %s", val, validator) - } - } - - return err - } - } - return nil -} - -func validateWithTagMap(customMsgExists, negate bool, val, validator, customErrorMessage string) error { - validatefunc, ok := govalidator.TagMap[validator] - if !ok { - return nil - } - - if result := validatefunc(val); !result && !negate || result && negate { - var err error - - if !negate { - if customMsgExists { - err = fmt.Errorf(customErrorMessage) - } else { - err = fmt.Errorf("`%s` does not validate as %s", val, validator) - } - } else { - if customMsgExists { - err = fmt.Errorf(customErrorMessage) - } else { - err = fmt.Errorf("`%s` does validate as %s", val, validator) - } - } - - return err - } - - return nil -} diff --git a/validator/govalidator/govalidator_test.go b/validator/govalidator/govalidator_test.go deleted file mode 100644 index c72eb70..0000000 --- a/validator/govalidator/govalidator_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package govalidator - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func Test_isValidTag(t *testing.T) { - t.Parallel() - - tests := []struct { - arg string - want bool - }{ - {"simple", true}, - {"", false}, - {"!#$%&()*+-./:<=>?@[]^_{|}~ ", true}, - {"абв", true}, - {"`", false}, - } - for _, tt := range tests { - assert.Equal(t, tt.want, isValidTag(tt.arg), "for %v", tt.arg) - } -} - -func Test_parseTagIntoMap(t *testing.T) { - t.Parallel() - - tests := []struct { - tag string - want tagOptionsMap - }{ - { - tag: "required~Some error message,length(2|3)", - want: tagOptionsMap{ - "required": "Some error message", - "length(2|3)": "", - }, - }, - { - tag: "required~Some error message~other", - want: tagOptionsMap{ - "required": "", - }, - }, - { - tag: "bad`tag,good_tag", - want: tagOptionsMap{ - "good_tag": "", - }, - }, - } - for _, tt := range tests { - assert.Equal(t, tt.want, parseTagIntoMap(tt.tag), "for %v", tt.tag) - } -} - -func Test_validateFunc(t *testing.T) { - t.Parallel() - - tests := []struct { - val string - options tagOptionsMap - - expErr string - }{ - { - val: "not a host", - options: tagOptionsMap{"host": ""}, - expErr: "`not a host` does not validate as host", - }, - { - val: "localhost", - options: tagOptionsMap{"host": ""}, - expErr: "", - }, - { - val: "localhost", - options: tagOptionsMap{"!host": ""}, - expErr: "`localhost` does validate as host", - }, - { - val: "not a host", - options: tagOptionsMap{"host": "wrong host value"}, - expErr: "wrong host value", - }, - { - val: "localhost", - options: tagOptionsMap{"!host": "shouldn't be a host"}, - expErr: "shouldn't be a host", - }, - { - val: "localhost", - options: tagOptionsMap{"length(2|10)": ""}, - expErr: "", - }, - { - val: "localhostlong", - options: tagOptionsMap{"length(2|10)": ""}, - expErr: "`localhostlong` does not validate as length(2|10)", - }, - { - val: "localhostlong", - options: tagOptionsMap{"length(2|10)": "too long!"}, - expErr: "too long!", - }, - { - val: "localhost", - options: tagOptionsMap{"!length(2|10)": ""}, - expErr: "`localhost` does validate as length(2|10)", - }, - { - val: "localhost", - options: tagOptionsMap{"!length(2|10)": "should be longer"}, - expErr: "should be longer", - }, - } - for _, tt := range tests { - err := validateFunc(tt.val, tt.options) - if tt.expErr != "" { - if assert.Error(t, err) { - assert.EqualError(t, err, tt.expErr) - } - } else { - assert.NoError(t, err) - } - } -} diff --git a/validator/validator.go b/validator/validator.go deleted file mode 100644 index e6f2010..0000000 --- a/validator/validator.go +++ /dev/null @@ -1,86 +0,0 @@ -package validator - -import ( - "fmt" - "reflect" - "regexp" - "strings" - - "github.com/go-playground/validator/v10" -) - -const ( - validTag = "validate" -) - -// invalidVarError wraps an error raised by validator on a struct field, -// and automatically modifies the error string for more efficient ones. -type invalidVarError struct { - fieldName string - fieldValue string - validatorErr error -} - -// Error implements the Error interface, but replacing some identifiable -// validation errors with more efficient messages, more adapted to CLI. -func (err *invalidVarError) Error() string { - var tagname string - - // Match the part containing the tag name - retag := regexp.MustCompile(`the '.*' tag`) - - matched := retag.FindString(err.validatorErr.Error()) - if matched != "" { - parts := strings.Split(matched, " ") - if len(parts) > 1 { - tagname = strings.Trim(parts[1], "'") - } - - return fmt.Sprintf("`%s` is not a valid %s", err.fieldValue, tagname) - } - - // Or simply replace the empty key with the field name. - return strings.ReplaceAll(err.validatorErr.Error(), "''", fmt.Sprintf("'%s'", err.fieldName)) -} - -// New returns a validation function to be applied on all flag struct fields of your command tree. -// It makes use of a singleton validator object, not exposed for customizations. If you want to add -// some validations or make any other customizations on the validator, use NewWith(custom) method. -func New() func(val string, field reflect.StructField, cfg interface{}) error { - valid := validator.New() - - // We wrap this singleton is a correct ValidateFunc - validation := func(val string, field reflect.StructField, obj interface{}) error { - validationTag := field.Tag.Get(validTag) - if err := valid.Var(val, validationTag); err != nil { - return &invalidVarError{field.Name, val, err} - } - - return nil - } - - return validation -} - -// NewWith returns a validation function to be applied on all flag struct fields. It takes a go-playground/validator -// object (meant to be used as a singleton), on which the user can prealably register any custom validation routines. -func NewWith(custom *validator.Validate) func(val string, field reflect.StructField, cfg interface{}) error { - if custom == nil { - return nil - } - - // We wrap this singleton is a correct ValidateFunc - validation := func(val string, field reflect.StructField, obj interface{}) error { - validationTag := field.Tag.Get(validTag) - - // The val string parameter is probably not needed as we will have to apply / Set() the value - // on the flag first before validating its value (var interface{} here) - if err := custom.Var(obj, validationTag); err != nil { - return &invalidVarError{field.Name, val, err} - } - - return nil - } - - return validation -} diff --git a/values_test.go b/values_test.go deleted file mode 100644 index 6d668f3..0000000 --- a/values_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package flags - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestCounter_Set(t *testing.T) { - var err error - initial := 0 - counter := (*Counter)(&initial) - - assert.Equal(t, 0, initial) - assert.Equal(t, "0", counter.String()) - assert.Equal(t, 0, counter.Get()) - assert.Equal(t, "count", counter.Type()) - assert.Equal(t, true, counter.IsBoolFlag()) - assert.Equal(t, true, counter.IsCumulative()) - - err = counter.Set("") - assert.NoError(t, err) - assert.Equal(t, 1, initial) - assert.Equal(t, "1", counter.String()) - - err = counter.Set("10") - assert.NoError(t, err) - assert.Equal(t, 10, initial) - assert.Equal(t, "10", counter.String()) - - err = counter.Set("-1") - assert.NoError(t, err) - assert.Equal(t, 11, initial) - assert.Equal(t, "11", counter.String()) - - err = counter.Set("b") - assert.Error(t, err, "strconv.ParseInt: parsing \"b\": invalid syntax") - assert.Equal(t, 11, initial) - assert.Equal(t, "11", counter.String()) -} - -func TestBoolValue_IsBoolFlag(t *testing.T) { - b := &boolValue{} - assert.True(t, b.IsBoolFlag()) -} - -func TestValidateValue_IsBoolFlag(t *testing.T) { - boolV := true - v := &validateValue{Value: newBoolValue(&boolV)} - assert.True(t, v.IsBoolFlag()) - - v = &validateValue{Value: newStringValue(strP("stringValue"))} - assert.False(t, v.IsBoolFlag()) -} - -func TestValidateValue_IsCumulative(t *testing.T) { - v := &validateValue{Value: newStringValue(strP("stringValue"))} - assert.False(t, v.IsCumulative()) - - v = &validateValue{Value: newStringSliceValue(&[]string{})} - assert.True(t, v.IsCumulative()) -} - -func TestValidateValue_String(t *testing.T) { - v := &validateValue{Value: newStringValue(strP("stringValue"))} - assert.Equal(t, "stringValue", v.String()) - - v = &validateValue{Value: nil} - assert.Equal(t, "", v.String()) -} - -func TestValidateValue_Set(t *testing.T) { - sV := strP("stringValue") - v := &validateValue{Value: newStringValue(sV)} - assert.NoError(t, v.Set("newVal")) - assert.Equal(t, "newVal", *sV) - - v.validateFunc = func(val string) error { - return nil - } - assert.NoError(t, v.Set("newVal")) - - v.validateFunc = func(val string) error { - return fmt.Errorf("invalid %s", val) - } - assert.EqualError(t, v.Set("newVal"), "invalid newVal") -} diff --git a/vendor/github.com/asaskevich/govalidator/.gitignore b/vendor/github.com/asaskevich/govalidator/.gitignore deleted file mode 100644 index 8d69a94..0000000 --- a/vendor/github.com/asaskevich/govalidator/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -bin/ -.idea/ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, built with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - diff --git a/vendor/github.com/asaskevich/govalidator/.travis.yml b/vendor/github.com/asaskevich/govalidator/.travis.yml deleted file mode 100644 index bb83c66..0000000 --- a/vendor/github.com/asaskevich/govalidator/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -dist: xenial -go: - - '1.10' - - '1.11' - - '1.12' - - '1.13' - - 'tip' - -script: - - go test -coverpkg=./... -coverprofile=coverage.info -timeout=5s - - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md b/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md deleted file mode 100644 index 4b462b0..0000000 --- a/vendor/github.com/asaskevich/govalidator/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,43 +0,0 @@ -# Contributor Code of Conduct - -This project adheres to [The Code Manifesto](http://codemanifesto.com) -as its guidelines for contributor interactions. - -## The Code Manifesto - -We want to work in an ecosystem that empowers developers to reach their -potential — one that encourages growth and effective collaboration. A space -that is safe for all. - -A space such as this benefits everyone that participates in it. It encourages -new developers to enter our field. It is through discussion and collaboration -that we grow, and through growth that we improve. - -In the effort to create such a place, we hold to these values: - -1. **Discrimination limits us.** This includes discrimination on the basis of - race, gender, sexual orientation, gender identity, age, nationality, - technology and any other arbitrary exclusion of a group of people. -2. **Boundaries honor us.** Your comfort levels are not everyone’s comfort - levels. Remember that, and if brought to your attention, heed it. -3. **We are our biggest assets.** None of us were born masters of our trade. - Each of us has been helped along the way. Return that favor, when and where - you can. -4. **We are resources for the future.** As an extension of #3, share what you - know. Make yourself a resource to help those that come after you. -5. **Respect defines us.** Treat others as you wish to be treated. Make your - discussions, criticisms and debates from a position of respectfulness. Ask - yourself, is it true? Is it necessary? Is it constructive? Anything less is - unacceptable. -6. **Reactions require grace.** Angry responses are valid, but abusive language - and vindictive actions are toxic. When something happens that offends you, - handle it assertively, but be respectful. Escalate reasonably, and try to - allow the offender an opportunity to explain themselves, and possibly - correct the issue. -7. **Opinions are just that: opinions.** Each and every one of us, due to our - background and upbringing, have varying opinions. That is perfectly - acceptable. Remember this: if you respect your own opinions, you should - respect the opinions of others. -8. **To err is human.** You might not intend it, but mistakes do happen and - contribute to build experience. Tolerate honest mistakes, and don't - hesitate to apologize if you make one yourself. diff --git a/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md b/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md deleted file mode 100644 index 7ed268a..0000000 --- a/vendor/github.com/asaskevich/govalidator/CONTRIBUTING.md +++ /dev/null @@ -1,63 +0,0 @@ -#### Support -If you do have a contribution to the package, feel free to create a Pull Request or an Issue. - -#### What to contribute -If you don't know what to do, there are some features and functions that need to be done - -- [ ] Refactor code -- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check -- [ ] Create actual list of contributors and projects that currently using this package -- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) -- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) -- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new -- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc -- [x] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) -- [ ] Implement fuzzing testing -- [ ] Implement some struct/map/array utilities -- [ ] Implement map/array validation -- [ ] Implement benchmarking -- [ ] Implement batch of examples -- [ ] Look at forks for new features and fixes - -#### Advice -Feel free to create what you want, but keep in mind when you implement new features: -- Code must be clear and readable, names of variables/constants clearly describes what they are doing -- Public functions must be documented and described in source file and added to README.md to the list of available functions -- There are must be unit-tests for any new functions and improvements - -## Financial contributions - -We also welcome financial contributions in full transparency on our [open collective](https://opencollective.com/govalidator). -Anyone can file an expense. If the expense makes sense for the development of the community, it will be "merged" in the ledger of our open collective by the core contributors and the person who filed the expense will be reimbursed. - - -## Credits - - -### Contributors - -Thank you to all the people who have already contributed to govalidator! - - - -### Backers - -Thank you to all our backers! [[Become a backer](https://opencollective.com/govalidator#backer)] - - - - -### Sponsors - -Thank you to all our sponsors! (please ask your company to also support this open source project by [becoming a sponsor](https://opencollective.com/govalidator#sponsor)) - - - - - - - - - - - \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/LICENSE b/vendor/github.com/asaskevich/govalidator/LICENSE deleted file mode 100644 index cacba91..0000000 --- a/vendor/github.com/asaskevich/govalidator/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2020 Alex Saskevich - -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. \ No newline at end of file diff --git a/vendor/github.com/asaskevich/govalidator/README.md b/vendor/github.com/asaskevich/govalidator/README.md deleted file mode 100644 index 2c3fc35..0000000 --- a/vendor/github.com/asaskevich/govalidator/README.md +++ /dev/null @@ -1,622 +0,0 @@ -govalidator -=========== -[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/asaskevich/govalidator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![GoDoc](https://godoc.org/github.com/asaskevich/govalidator?status.png)](https://godoc.org/github.com/asaskevich/govalidator) -[![Build Status](https://travis-ci.org/asaskevich/govalidator.svg?branch=master)](https://travis-ci.org/asaskevich/govalidator) -[![Coverage](https://codecov.io/gh/asaskevich/govalidator/branch/master/graph/badge.svg)](https://codecov.io/gh/asaskevich/govalidator) [![Go Report Card](https://goreportcard.com/badge/github.com/asaskevich/govalidator)](https://goreportcard.com/report/github.com/asaskevich/govalidator) [![GoSearch](http://go-search.org/badge?id=github.com%2Fasaskevich%2Fgovalidator)](http://go-search.org/view?id=github.com%2Fasaskevich%2Fgovalidator) [![Backers on Open Collective](https://opencollective.com/govalidator/backers/badge.svg)](#backers) [![Sponsors on Open Collective](https://opencollective.com/govalidator/sponsors/badge.svg)](#sponsors) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_shield) - -A package of validators and sanitizers for strings, structs and collections. Based on [validator.js](https://github.com/chriso/validator.js). - -#### Installation -Make sure that Go is installed on your computer. -Type the following command in your terminal: - - go get github.com/asaskevich/govalidator - -or you can get specified release of the package with `gopkg.in`: - - go get gopkg.in/asaskevich/govalidator.v10 - -After it the package is ready to use. - - -#### Import package in your project -Add following line in your `*.go` file: -```go -import "github.com/asaskevich/govalidator" -``` -If you are unhappy to use long `govalidator`, you can do something like this: -```go -import ( - valid "github.com/asaskevich/govalidator" -) -``` - -#### Activate behavior to require all fields have a validation tag by default -`SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function. - -`SetNilPtrAllowedByRequired` causes validation to pass when struct fields marked by `required` are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between `nil` and `zero value` state can use this. If disabled, both `nil` and `zero` values cause validation errors. - -```go -import "github.com/asaskevich/govalidator" - -func init() { - govalidator.SetFieldsRequiredByDefault(true) -} -``` - -Here's some code to explain it: -```go -// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): -type exampleStruct struct { - Name string `` - Email string `valid:"email"` -} - -// this, however, will only fail when Email is empty or an invalid email address: -type exampleStruct2 struct { - Name string `valid:"-"` - Email string `valid:"email"` -} - -// lastly, this will only fail when Email is an invalid email address but not when it's empty: -type exampleStruct2 struct { - Name string `valid:"-"` - Email string `valid:"email,optional"` -} -``` - -#### Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123)) -##### Custom validator function signature -A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible. -```go -import "github.com/asaskevich/govalidator" - -// old signature -func(i interface{}) bool - -// new signature -func(i interface{}, o interface{}) bool -``` - -##### Adding a custom validator -This was changed to prevent data races when accessing custom validators. -```go -import "github.com/asaskevich/govalidator" - -// before -govalidator.CustomTypeTagMap["customByteArrayValidator"] = func(i interface{}, o interface{}) bool { - // ... -} - -// after -govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, o interface{}) bool { - // ... -}) -``` - -#### List of functions: -```go -func Abs(value float64) float64 -func BlackList(str, chars string) string -func ByteLength(str string, params ...string) bool -func CamelCaseToUnderscore(str string) string -func Contains(str, substring string) bool -func Count(array []interface{}, iterator ConditionIterator) int -func Each(array []interface{}, iterator Iterator) -func ErrorByField(e error, field string) string -func ErrorsByField(e error) map[string]string -func Filter(array []interface{}, iterator ConditionIterator) []interface{} -func Find(array []interface{}, iterator ConditionIterator) interface{} -func GetLine(s string, index int) (string, error) -func GetLines(s string) []string -func HasLowerCase(str string) bool -func HasUpperCase(str string) bool -func HasWhitespace(str string) bool -func HasWhitespaceOnly(str string) bool -func InRange(value interface{}, left interface{}, right interface{}) bool -func InRangeFloat32(value, left, right float32) bool -func InRangeFloat64(value, left, right float64) bool -func InRangeInt(value, left, right interface{}) bool -func IsASCII(str string) bool -func IsAlpha(str string) bool -func IsAlphanumeric(str string) bool -func IsBase64(str string) bool -func IsByteLength(str string, min, max int) bool -func IsCIDR(str string) bool -func IsCRC32(str string) bool -func IsCRC32b(str string) bool -func IsCreditCard(str string) bool -func IsDNSName(str string) bool -func IsDataURI(str string) bool -func IsDialString(str string) bool -func IsDivisibleBy(str, num string) bool -func IsEmail(str string) bool -func IsExistingEmail(email string) bool -func IsFilePath(str string) (bool, int) -func IsFloat(str string) bool -func IsFullWidth(str string) bool -func IsHalfWidth(str string) bool -func IsHash(str string, algorithm string) bool -func IsHexadecimal(str string) bool -func IsHexcolor(str string) bool -func IsHost(str string) bool -func IsIP(str string) bool -func IsIPv4(str string) bool -func IsIPv6(str string) bool -func IsISBN(str string, version int) bool -func IsISBN10(str string) bool -func IsISBN13(str string) bool -func IsISO3166Alpha2(str string) bool -func IsISO3166Alpha3(str string) bool -func IsISO4217(str string) bool -func IsISO693Alpha2(str string) bool -func IsISO693Alpha3b(str string) bool -func IsIn(str string, params ...string) bool -func IsInRaw(str string, params ...string) bool -func IsInt(str string) bool -func IsJSON(str string) bool -func IsLatitude(str string) bool -func IsLongitude(str string) bool -func IsLowerCase(str string) bool -func IsMAC(str string) bool -func IsMD4(str string) bool -func IsMD5(str string) bool -func IsMagnetURI(str string) bool -func IsMongoID(str string) bool -func IsMultibyte(str string) bool -func IsNatural(value float64) bool -func IsNegative(value float64) bool -func IsNonNegative(value float64) bool -func IsNonPositive(value float64) bool -func IsNotNull(str string) bool -func IsNull(str string) bool -func IsNumeric(str string) bool -func IsPort(str string) bool -func IsPositive(value float64) bool -func IsPrintableASCII(str string) bool -func IsRFC3339(str string) bool -func IsRFC3339WithoutZone(str string) bool -func IsRGBcolor(str string) bool -func IsRegex(str string) bool -func IsRequestURI(rawurl string) bool -func IsRequestURL(rawurl string) bool -func IsRipeMD128(str string) bool -func IsRipeMD160(str string) bool -func IsRsaPub(str string, params ...string) bool -func IsRsaPublicKey(str string, keylen int) bool -func IsSHA1(str string) bool -func IsSHA256(str string) bool -func IsSHA384(str string) bool -func IsSHA512(str string) bool -func IsSSN(str string) bool -func IsSemver(str string) bool -func IsTiger128(str string) bool -func IsTiger160(str string) bool -func IsTiger192(str string) bool -func IsTime(str string, format string) bool -func IsType(v interface{}, params ...string) bool -func IsURL(str string) bool -func IsUTFDigit(str string) bool -func IsUTFLetter(str string) bool -func IsUTFLetterNumeric(str string) bool -func IsUTFNumeric(str string) bool -func IsUUID(str string) bool -func IsUUIDv3(str string) bool -func IsUUIDv4(str string) bool -func IsUUIDv5(str string) bool -func IsULID(str string) bool -func IsUnixTime(str string) bool -func IsUpperCase(str string) bool -func IsVariableWidth(str string) bool -func IsWhole(value float64) bool -func LeftTrim(str, chars string) string -func Map(array []interface{}, iterator ResultIterator) []interface{} -func Matches(str, pattern string) bool -func MaxStringLength(str string, params ...string) bool -func MinStringLength(str string, params ...string) bool -func NormalizeEmail(str string) (string, error) -func PadBoth(str string, padStr string, padLen int) string -func PadLeft(str string, padStr string, padLen int) string -func PadRight(str string, padStr string, padLen int) string -func PrependPathToErrors(err error, path string) error -func Range(str string, params ...string) bool -func RemoveTags(s string) string -func ReplacePattern(str, pattern, replace string) string -func Reverse(s string) string -func RightTrim(str, chars string) string -func RuneLength(str string, params ...string) bool -func SafeFileName(str string) string -func SetFieldsRequiredByDefault(value bool) -func SetNilPtrAllowedByRequired(value bool) -func Sign(value float64) float64 -func StringLength(str string, params ...string) bool -func StringMatches(s string, params ...string) bool -func StripLow(str string, keepNewLines bool) string -func ToBoolean(str string) (bool, error) -func ToFloat(str string) (float64, error) -func ToInt(value interface{}) (res int64, err error) -func ToJSON(obj interface{}) (string, error) -func ToString(obj interface{}) string -func Trim(str, chars string) string -func Truncate(str string, length int, ending string) string -func TruncatingErrorf(str string, args ...interface{}) error -func UnderscoreToCamelCase(s string) string -func ValidateMap(inputMap map[string]interface{}, validationMap map[string]interface{}) (bool, error) -func ValidateStruct(s interface{}) (bool, error) -func WhiteList(str, chars string) string -type ConditionIterator -type CustomTypeValidator -type Error -func (e Error) Error() string -type Errors -func (es Errors) Error() string -func (es Errors) Errors() []error -type ISO3166Entry -type ISO693Entry -type InterfaceParamValidator -type Iterator -type ParamValidator -type ResultIterator -type UnsupportedTypeError -func (e *UnsupportedTypeError) Error() string -type Validator -``` - -#### Examples -###### IsURL -```go -println(govalidator.IsURL(`http://user@pass:domain.com/path/page`)) -``` -###### IsType -```go -println(govalidator.IsType("Bob", "string")) -println(govalidator.IsType(1, "int")) -i := 1 -println(govalidator.IsType(&i, "*int")) -``` - -IsType can be used through the tag `type` which is essential for map validation: -```go -type User struct { - Name string `valid:"type(string)"` - Age int `valid:"type(int)"` - Meta interface{} `valid:"type(string)"` -} -result, err := govalidator.ValidateStruct(User{"Bob", 20, "meta"}) -if err != nil { - println("error: " + err.Error()) -} -println(result) -``` -###### ToString -```go -type User struct { - FirstName string - LastName string -} - -str := govalidator.ToString(&User{"John", "Juan"}) -println(str) -``` -###### Each, Map, Filter, Count for slices -Each iterates over the slice/array and calls Iterator for every item -```go -data := []interface{}{1, 2, 3, 4, 5} -var fn govalidator.Iterator = func(value interface{}, index int) { - println(value.(int)) -} -govalidator.Each(data, fn) -``` -```go -data := []interface{}{1, 2, 3, 4, 5} -var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} { - return value.(int) * 3 -} -_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15} -``` -```go -data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -var fn govalidator.ConditionIterator = func(value interface{}, index int) bool { - return value.(int)%2 == 0 -} -_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10} -_ = govalidator.Count(data, fn) // result = 5 -``` -###### ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2) -If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this: -```go -govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { - return str == "duck" -}) -``` -For completely custom validators (interface-based), see below. - -Here is a list of available validators for struct fields (validator - used function): -```go -"email": IsEmail, -"url": IsURL, -"dialstring": IsDialString, -"requrl": IsRequestURL, -"requri": IsRequestURI, -"alpha": IsAlpha, -"utfletter": IsUTFLetter, -"alphanum": IsAlphanumeric, -"utfletternum": IsUTFLetterNumeric, -"numeric": IsNumeric, -"utfnumeric": IsUTFNumeric, -"utfdigit": IsUTFDigit, -"hexadecimal": IsHexadecimal, -"hexcolor": IsHexcolor, -"rgbcolor": IsRGBcolor, -"lowercase": IsLowerCase, -"uppercase": IsUpperCase, -"int": IsInt, -"float": IsFloat, -"null": IsNull, -"uuid": IsUUID, -"uuidv3": IsUUIDv3, -"uuidv4": IsUUIDv4, -"uuidv5": IsUUIDv5, -"creditcard": IsCreditCard, -"isbn10": IsISBN10, -"isbn13": IsISBN13, -"json": IsJSON, -"multibyte": IsMultibyte, -"ascii": IsASCII, -"printableascii": IsPrintableASCII, -"fullwidth": IsFullWidth, -"halfwidth": IsHalfWidth, -"variablewidth": IsVariableWidth, -"base64": IsBase64, -"datauri": IsDataURI, -"ip": IsIP, -"port": IsPort, -"ipv4": IsIPv4, -"ipv6": IsIPv6, -"dns": IsDNSName, -"host": IsHost, -"mac": IsMAC, -"latitude": IsLatitude, -"longitude": IsLongitude, -"ssn": IsSSN, -"semver": IsSemver, -"rfc3339": IsRFC3339, -"rfc3339WithoutZone": IsRFC3339WithoutZone, -"ISO3166Alpha2": IsISO3166Alpha2, -"ISO3166Alpha3": IsISO3166Alpha3, -"ulid": IsULID, -``` -Validators with parameters - -```go -"range(min|max)": Range, -"length(min|max)": ByteLength, -"runelength(min|max)": RuneLength, -"stringlength(min|max)": StringLength, -"matches(pattern)": StringMatches, -"in(string1|string2|...|stringN)": IsIn, -"rsapub(keylength)" : IsRsaPub, -"minstringlength(int): MinStringLength, -"maxstringlength(int): MaxStringLength, -``` -Validators with parameters for any type - -```go -"type(type)": IsType, -``` - -And here is small example of usage: -```go -type Post struct { - Title string `valid:"alphanum,required"` - Message string `valid:"duck,ascii"` - Message2 string `valid:"animal(dog)"` - AuthorIP string `valid:"ipv4"` - Date string `valid:"-"` -} -post := &Post{ - Title: "My Example Post", - Message: "duck", - Message2: "dog", - AuthorIP: "123.234.54.3", -} - -// Add your own struct validation tags -govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { - return str == "duck" -}) - -// Add your own struct validation tags with parameter -govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool { - species := params[0] - return str == species -}) -govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$") - -result, err := govalidator.ValidateStruct(post) -if err != nil { - println("error: " + err.Error()) -} -println(result) -``` -###### ValidateMap [#2](https://github.com/asaskevich/govalidator/pull/338) -If you want to validate maps, you can use the map to be validated and a validation map that contain the same tags used in ValidateStruct, both maps have to be in the form `map[string]interface{}` - -So here is small example of usage: -```go -var mapTemplate = map[string]interface{}{ - "name":"required,alpha", - "family":"required,alpha", - "email":"required,email", - "cell-phone":"numeric", - "address":map[string]interface{}{ - "line1":"required,alphanum", - "line2":"alphanum", - "postal-code":"numeric", - }, -} - -var inputMap = map[string]interface{}{ - "name":"Bob", - "family":"Smith", - "email":"foo@bar.baz", - "address":map[string]interface{}{ - "line1":"", - "line2":"", - "postal-code":"", - }, -} - -result, err := govalidator.ValidateMap(inputMap, mapTemplate) -if err != nil { - println("error: " + err.Error()) -} -println(result) -``` - -###### WhiteList -```go -// Remove all characters from string ignoring characters between "a" and "z" -println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa") -``` - -###### Custom validation functions -Custom validation using your own domain specific validators is also available - here's an example of how to use it: -```go -import "github.com/asaskevich/govalidator" - -type CustomByteArray [6]byte // custom types are supported and can be validated - -type StructWithCustomByteArray struct { - ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence - Email string `valid:"email"` - CustomMinLength int `valid:"-"` -} - -govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, context interface{}) bool { - switch v := context.(type) { // you can type switch on the context interface being validated - case StructWithCustomByteArray: - // you can check and validate against some other field in the context, - // return early or not validate against the context at all – your choice - case SomeOtherType: - // ... - default: - // expecting some other type? Throw/panic here or continue - } - - switch v := i.(type) { // type switch on the struct field being validated - case CustomByteArray: - for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes - if e != 0 { - return true - } - } - } - return false -}) -govalidator.CustomTypeTagMap.Set("customMinLengthValidator", func(i interface{}, context interface{}) bool { - switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation - case StructWithCustomByteArray: - return len(v.ID) >= v.CustomMinLength - } - return false -}) -``` - -###### Loop over Error() -By default .Error() returns all errors in a single String. To access each error you can do this: -```go - if err != nil { - errs := err.(govalidator.Errors).Errors() - for _, e := range errs { - fmt.Println(e.Error()) - } - } -``` - -###### Custom error messages -Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it: -```go -type Ticket struct { - Id int64 `json:"id"` - FirstName string `json:"firstname" valid:"required~First name is blank"` -} -``` - -#### Notes -Documentation is available here: [godoc.org](https://godoc.org/github.com/asaskevich/govalidator). -Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/asaskevich/govalidator). - -#### Support -If you do have a contribution to the package, feel free to create a Pull Request or an Issue. - -#### What to contribute -If you don't know what to do, there are some features and functions that need to be done - -- [ ] Refactor code -- [ ] Edit docs and [README](https://github.com/asaskevich/govalidator/README.md): spellcheck, grammar and typo check -- [ ] Create actual list of contributors and projects that currently using this package -- [ ] Resolve [issues and bugs](https://github.com/asaskevich/govalidator/issues) -- [ ] Update actual [list of functions](https://github.com/asaskevich/govalidator#list-of-functions) -- [ ] Update [list of validators](https://github.com/asaskevich/govalidator#validatestruct-2) that available for `ValidateStruct` and add new -- [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc -- [x] Implement [validation by maps](https://github.com/asaskevich/govalidator/issues/224) -- [ ] Implement fuzzing testing -- [ ] Implement some struct/map/array utilities -- [ ] Implement map/array validation -- [ ] Implement benchmarking -- [ ] Implement batch of examples -- [ ] Look at forks for new features and fixes - -#### Advice -Feel free to create what you want, but keep in mind when you implement new features: -- Code must be clear and readable, names of variables/constants clearly describes what they are doing -- Public functions must be documented and described in source file and added to README.md to the list of available functions -- There are must be unit-tests for any new functions and improvements - -## Credits -### Contributors - -This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. - -#### Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors) -* [Daniel Lohse](https://github.com/annismckenzie) -* [Attila Oláh](https://github.com/attilaolah) -* [Daniel Korner](https://github.com/Dadie) -* [Steven Wilkin](https://github.com/stevenwilkin) -* [Deiwin Sarjas](https://github.com/deiwin) -* [Noah Shibley](https://github.com/slugmobile) -* [Nathan Davies](https://github.com/nathj07) -* [Matt Sanford](https://github.com/mzsanford) -* [Simon ccl1115](https://github.com/ccl1115) - - - - -### Backers - -Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/govalidator#backer)] - - - - -### Sponsors - -Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/govalidator#sponsor)] - - - - - - - - - - - - - - - -## License -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fasaskevich%2Fgovalidator?ref=badge_large) diff --git a/vendor/github.com/asaskevich/govalidator/arrays.go b/vendor/github.com/asaskevich/govalidator/arrays.go deleted file mode 100644 index 3e1da7c..0000000 --- a/vendor/github.com/asaskevich/govalidator/arrays.go +++ /dev/null @@ -1,87 +0,0 @@ -package govalidator - -// Iterator is the function that accepts element of slice/array and its index -type Iterator func(interface{}, int) - -// ResultIterator is the function that accepts element of slice/array and its index and returns any result -type ResultIterator func(interface{}, int) interface{} - -// ConditionIterator is the function that accepts element of slice/array and its index and returns boolean -type ConditionIterator func(interface{}, int) bool - -// ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values -type ReduceIterator func(interface{}, interface{}) interface{} - -// Some validates that any item of array corresponds to ConditionIterator. Returns boolean. -func Some(array []interface{}, iterator ConditionIterator) bool { - res := false - for index, data := range array { - res = res || iterator(data, index) - } - return res -} - -// Every validates that every item of array corresponds to ConditionIterator. Returns boolean. -func Every(array []interface{}, iterator ConditionIterator) bool { - res := true - for index, data := range array { - res = res && iterator(data, index) - } - return res -} - -// Reduce boils down a list of values into a single value by ReduceIterator -func Reduce(array []interface{}, iterator ReduceIterator, initialValue interface{}) interface{} { - for _, data := range array { - initialValue = iterator(initialValue, data) - } - return initialValue -} - -// Each iterates over the slice and apply Iterator to every item -func Each(array []interface{}, iterator Iterator) { - for index, data := range array { - iterator(data, index) - } -} - -// Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result. -func Map(array []interface{}, iterator ResultIterator) []interface{} { - var result = make([]interface{}, len(array)) - for index, data := range array { - result[index] = iterator(data, index) - } - return result -} - -// Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise. -func Find(array []interface{}, iterator ConditionIterator) interface{} { - for index, data := range array { - if iterator(data, index) { - return data - } - } - return nil -} - -// Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice. -func Filter(array []interface{}, iterator ConditionIterator) []interface{} { - var result = make([]interface{}, 0) - for index, data := range array { - if iterator(data, index) { - result = append(result, data) - } - } - return result -} - -// Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator. -func Count(array []interface{}, iterator ConditionIterator) int { - count := 0 - for index, data := range array { - if iterator(data, index) { - count = count + 1 - } - } - return count -} diff --git a/vendor/github.com/asaskevich/govalidator/converter.go b/vendor/github.com/asaskevich/govalidator/converter.go deleted file mode 100644 index d68e990..0000000 --- a/vendor/github.com/asaskevich/govalidator/converter.go +++ /dev/null @@ -1,81 +0,0 @@ -package govalidator - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" -) - -// ToString convert the input to a string. -func ToString(obj interface{}) string { - res := fmt.Sprintf("%v", obj) - return res -} - -// ToJSON convert the input to a valid JSON string -func ToJSON(obj interface{}) (string, error) { - res, err := json.Marshal(obj) - if err != nil { - res = []byte("") - } - return string(res), err -} - -// ToFloat convert the input string to a float, or 0.0 if the input is not a float. -func ToFloat(value interface{}) (res float64, err error) { - val := reflect.ValueOf(value) - - switch value.(type) { - case int, int8, int16, int32, int64: - res = float64(val.Int()) - case uint, uint8, uint16, uint32, uint64: - res = float64(val.Uint()) - case float32, float64: - res = val.Float() - case string: - res, err = strconv.ParseFloat(val.String(), 64) - if err != nil { - res = 0 - } - default: - err = fmt.Errorf("ToInt: unknown interface type %T", value) - res = 0 - } - - return -} - -// ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer. -func ToInt(value interface{}) (res int64, err error) { - val := reflect.ValueOf(value) - - switch value.(type) { - case int, int8, int16, int32, int64: - res = val.Int() - case uint, uint8, uint16, uint32, uint64: - res = int64(val.Uint()) - case float32, float64: - res = int64(val.Float()) - case string: - if IsInt(val.String()) { - res, err = strconv.ParseInt(val.String(), 0, 64) - if err != nil { - res = 0 - } - } else { - err = fmt.Errorf("ToInt: invalid numeric format %g", value) - res = 0 - } - default: - err = fmt.Errorf("ToInt: unknown interface type %T", value) - res = 0 - } - - return -} - -// ToBoolean convert the input string to a boolean. -func ToBoolean(str string) (bool, error) { - return strconv.ParseBool(str) -} diff --git a/vendor/github.com/asaskevich/govalidator/doc.go b/vendor/github.com/asaskevich/govalidator/doc.go deleted file mode 100644 index 55dce62..0000000 --- a/vendor/github.com/asaskevich/govalidator/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package govalidator - -// A package of validators and sanitizers for strings, structures and collections. diff --git a/vendor/github.com/asaskevich/govalidator/error.go b/vendor/github.com/asaskevich/govalidator/error.go deleted file mode 100644 index 1da2336..0000000 --- a/vendor/github.com/asaskevich/govalidator/error.go +++ /dev/null @@ -1,47 +0,0 @@ -package govalidator - -import ( - "sort" - "strings" -) - -// Errors is an array of multiple errors and conforms to the error interface. -type Errors []error - -// Errors returns itself. -func (es Errors) Errors() []error { - return es -} - -func (es Errors) Error() string { - var errs []string - for _, e := range es { - errs = append(errs, e.Error()) - } - sort.Strings(errs) - return strings.Join(errs, ";") -} - -// Error encapsulates a name, an error and whether there's a custom error message or not. -type Error struct { - Name string - Err error - CustomErrorMessageExists bool - - // Validator indicates the name of the validator that failed - Validator string - Path []string -} - -func (e Error) Error() string { - if e.CustomErrorMessageExists { - return e.Err.Error() - } - - errName := e.Name - if len(e.Path) > 0 { - errName = strings.Join(append(e.Path, e.Name), ".") - } - - return errName + ": " + e.Err.Error() -} diff --git a/vendor/github.com/asaskevich/govalidator/numerics.go b/vendor/github.com/asaskevich/govalidator/numerics.go deleted file mode 100644 index 5041d9e..0000000 --- a/vendor/github.com/asaskevich/govalidator/numerics.go +++ /dev/null @@ -1,100 +0,0 @@ -package govalidator - -import ( - "math" -) - -// Abs returns absolute value of number -func Abs(value float64) float64 { - return math.Abs(value) -} - -// Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise -func Sign(value float64) float64 { - if value > 0 { - return 1 - } else if value < 0 { - return -1 - } else { - return 0 - } -} - -// IsNegative returns true if value < 0 -func IsNegative(value float64) bool { - return value < 0 -} - -// IsPositive returns true if value > 0 -func IsPositive(value float64) bool { - return value > 0 -} - -// IsNonNegative returns true if value >= 0 -func IsNonNegative(value float64) bool { - return value >= 0 -} - -// IsNonPositive returns true if value <= 0 -func IsNonPositive(value float64) bool { - return value <= 0 -} - -// InRangeInt returns true if value lies between left and right border -func InRangeInt(value, left, right interface{}) bool { - value64, _ := ToInt(value) - left64, _ := ToInt(left) - right64, _ := ToInt(right) - if left64 > right64 { - left64, right64 = right64, left64 - } - return value64 >= left64 && value64 <= right64 -} - -// InRangeFloat32 returns true if value lies between left and right border -func InRangeFloat32(value, left, right float32) bool { - if left > right { - left, right = right, left - } - return value >= left && value <= right -} - -// InRangeFloat64 returns true if value lies between left and right border -func InRangeFloat64(value, left, right float64) bool { - if left > right { - left, right = right, left - } - return value >= left && value <= right -} - -// InRange returns true if value lies between left and right border, generic type to handle int, float32, float64 and string. -// All types must the same type. -// False if value doesn't lie in range or if it incompatible or not comparable -func InRange(value interface{}, left interface{}, right interface{}) bool { - switch value.(type) { - case int: - intValue, _ := ToInt(value) - intLeft, _ := ToInt(left) - intRight, _ := ToInt(right) - return InRangeInt(intValue, intLeft, intRight) - case float32, float64: - intValue, _ := ToFloat(value) - intLeft, _ := ToFloat(left) - intRight, _ := ToFloat(right) - return InRangeFloat64(intValue, intLeft, intRight) - case string: - return value.(string) >= left.(string) && value.(string) <= right.(string) - default: - return false - } -} - -// IsWhole returns true if value is whole number -func IsWhole(value float64) bool { - return math.Remainder(value, 1) == 0 -} - -// IsNatural returns true if value is natural number (positive and whole) -func IsNatural(value float64) bool { - return IsWhole(value) && IsPositive(value) -} diff --git a/vendor/github.com/asaskevich/govalidator/patterns.go b/vendor/github.com/asaskevich/govalidator/patterns.go deleted file mode 100644 index bafc376..0000000 --- a/vendor/github.com/asaskevich/govalidator/patterns.go +++ /dev/null @@ -1,113 +0,0 @@ -package govalidator - -import "regexp" - -// Basic regular expressions for validating strings -const ( - Email string = "^(((([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|\\.|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])([a-zA-Z]|\\d|-|_|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*([a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" - CreditCard string = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11}|6[27][0-9]{14})$" - ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$" - ISBN13 string = "^(?:[0-9]{13})$" - UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" - UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" - Alpha string = "^[a-zA-Z]+$" - Alphanumeric string = "^[a-zA-Z0-9]+$" - Numeric string = "^[0-9]+$" - Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$" - Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$" - Hexadecimal string = "^[0-9a-fA-F]+$" - Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" - RGBcolor string = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$" - ASCII string = "^[\x00-\x7F]+$" - Multibyte string = "[^\x00-\x7F]" - FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" - HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" - Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" - PrintableASCII string = "^[\x20-\x7E]+$" - DataURI string = "^data:.+\\/(.+);base64$" - MagnetURI string = "^magnet:\\?xt=urn:[a-zA-Z0-9]+:[a-zA-Z0-9]{32,40}&dn=.+&tr=.+$" - Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" - Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` - IP string = `(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))` - URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)` - URLUsername string = `(\S+(:\S*)?@)` - URLPath string = `((\/|\?|#)[^\s]*)` - URLPort string = `(:(\d{1,5}))` - URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3]|24\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-5]))` - URLSubdomain string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))` - URL = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$` - SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` - WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` - UnixPath string = `^(/[^/\x00]*)+/?$` - WinARPath string = `^(?:(?:[a-zA-Z]:|\\\\[a-z0-9_.$●-]+\\[a-z0-9_.$●-]+)\\|\\?[^\\/:*?"<>|\r\n]+\\?)(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` - UnixARPath string = `^((\.{0,2}/)?([^/\x00]*))+/?$` - Semver string = "^v?(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$" - tagName string = "valid" - hasLowerCase string = ".*[[:lower:]]" - hasUpperCase string = ".*[[:upper:]]" - hasWhitespace string = ".*[[:space:]]" - hasWhitespaceOnly string = "^[[:space:]]+$" - IMEI string = "^[0-9a-f]{14}$|^\\d{15}$|^\\d{18}$" - IMSI string = "^\\d{14,15}$" - E164 string = `^\+?[1-9]\d{1,14}$` -) - -// Used by IsFilePath func -const ( - // Unknown is unresolved OS type - Unknown = iota - // Win is Windows type - Win - // Unix is *nix OS types - Unix -) - -var ( - userRegexp = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$") - hostRegexp = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$") - userDotRegexp = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})") - rxEmail = regexp.MustCompile(Email) - rxCreditCard = regexp.MustCompile(CreditCard) - rxISBN10 = regexp.MustCompile(ISBN10) - rxISBN13 = regexp.MustCompile(ISBN13) - rxUUID3 = regexp.MustCompile(UUID3) - rxUUID4 = regexp.MustCompile(UUID4) - rxUUID5 = regexp.MustCompile(UUID5) - rxUUID = regexp.MustCompile(UUID) - rxAlpha = regexp.MustCompile(Alpha) - rxAlphanumeric = regexp.MustCompile(Alphanumeric) - rxNumeric = regexp.MustCompile(Numeric) - rxInt = regexp.MustCompile(Int) - rxFloat = regexp.MustCompile(Float) - rxHexadecimal = regexp.MustCompile(Hexadecimal) - rxHexcolor = regexp.MustCompile(Hexcolor) - rxRGBcolor = regexp.MustCompile(RGBcolor) - rxASCII = regexp.MustCompile(ASCII) - rxPrintableASCII = regexp.MustCompile(PrintableASCII) - rxMultibyte = regexp.MustCompile(Multibyte) - rxFullWidth = regexp.MustCompile(FullWidth) - rxHalfWidth = regexp.MustCompile(HalfWidth) - rxBase64 = regexp.MustCompile(Base64) - rxDataURI = regexp.MustCompile(DataURI) - rxMagnetURI = regexp.MustCompile(MagnetURI) - rxLatitude = regexp.MustCompile(Latitude) - rxLongitude = regexp.MustCompile(Longitude) - rxDNSName = regexp.MustCompile(DNSName) - rxURL = regexp.MustCompile(URL) - rxSSN = regexp.MustCompile(SSN) - rxWinPath = regexp.MustCompile(WinPath) - rxUnixPath = regexp.MustCompile(UnixPath) - rxARWinPath = regexp.MustCompile(WinARPath) - rxARUnixPath = regexp.MustCompile(UnixARPath) - rxSemver = regexp.MustCompile(Semver) - rxHasLowerCase = regexp.MustCompile(hasLowerCase) - rxHasUpperCase = regexp.MustCompile(hasUpperCase) - rxHasWhitespace = regexp.MustCompile(hasWhitespace) - rxHasWhitespaceOnly = regexp.MustCompile(hasWhitespaceOnly) - rxIMEI = regexp.MustCompile(IMEI) - rxIMSI = regexp.MustCompile(IMSI) - rxE164 = regexp.MustCompile(E164) -) diff --git a/vendor/github.com/asaskevich/govalidator/types.go b/vendor/github.com/asaskevich/govalidator/types.go deleted file mode 100644 index c573abb..0000000 --- a/vendor/github.com/asaskevich/govalidator/types.go +++ /dev/null @@ -1,656 +0,0 @@ -package govalidator - -import ( - "reflect" - "regexp" - "sort" - "sync" -) - -// Validator is a wrapper for a validator function that returns bool and accepts string. -type Validator func(str string) bool - -// CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. -// The second parameter should be the context (in the case of validating a struct: the whole object being validated). -type CustomTypeValidator func(i interface{}, o interface{}) bool - -// ParamValidator is a wrapper for validator functions that accept additional parameters. -type ParamValidator func(str string, params ...string) bool - -// InterfaceParamValidator is a wrapper for functions that accept variants parameters for an interface value -type InterfaceParamValidator func(in interface{}, params ...string) bool -type tagOptionsMap map[string]tagOption - -func (t tagOptionsMap) orderedKeys() []string { - var keys []string - for k := range t { - keys = append(keys, k) - } - - sort.Slice(keys, func(a, b int) bool { - return t[keys[a]].order < t[keys[b]].order - }) - - return keys -} - -type tagOption struct { - name string - customErrorMessage string - order int -} - -// UnsupportedTypeError is a wrapper for reflect.Type -type UnsupportedTypeError struct { - Type reflect.Type -} - -// stringValues is a slice of reflect.Value holding *reflect.StringValue. -// It implements the methods to sort by string. -type stringValues []reflect.Value - -// InterfaceParamTagMap is a map of functions accept variants parameters for an interface value -var InterfaceParamTagMap = map[string]InterfaceParamValidator{ - "type": IsType, -} - -// InterfaceParamTagRegexMap maps interface param tags to their respective regexes. -var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{ - "type": regexp.MustCompile(`^type\((.*)\)$`), -} - -// ParamTagMap is a map of functions accept variants parameters -var ParamTagMap = map[string]ParamValidator{ - "length": ByteLength, - "range": Range, - "runelength": RuneLength, - "stringlength": StringLength, - "matches": StringMatches, - "in": IsInRaw, - "rsapub": IsRsaPub, - "minstringlength": MinStringLength, - "maxstringlength": MaxStringLength, -} - -// ParamTagRegexMap maps param tags to their respective regexes. -var ParamTagRegexMap = map[string]*regexp.Regexp{ - "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), - "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), - "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), - "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), - "in": regexp.MustCompile(`^in\((.*)\)`), - "matches": regexp.MustCompile(`^matches\((.+)\)$`), - "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), - "minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"), - "maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"), -} - -type customTypeTagMap struct { - validators map[string]CustomTypeValidator - - sync.RWMutex -} - -func (tm *customTypeTagMap) Get(name string) (CustomTypeValidator, bool) { - tm.RLock() - defer tm.RUnlock() - v, ok := tm.validators[name] - return v, ok -} - -func (tm *customTypeTagMap) Set(name string, ctv CustomTypeValidator) { - tm.Lock() - defer tm.Unlock() - tm.validators[name] = ctv -} - -// CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. -// Use this to validate compound or custom types that need to be handled as a whole, e.g. -// `type UUID [16]byte` (this would be handled as an array of bytes). -var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)} - -// TagMap is a map of functions, that can be used as tags for ValidateStruct function. -var TagMap = map[string]Validator{ - "email": IsEmail, - "url": IsURL, - "dialstring": IsDialString, - "requrl": IsRequestURL, - "requri": IsRequestURI, - "alpha": IsAlpha, - "utfletter": IsUTFLetter, - "alphanum": IsAlphanumeric, - "utfletternum": IsUTFLetterNumeric, - "numeric": IsNumeric, - "utfnumeric": IsUTFNumeric, - "utfdigit": IsUTFDigit, - "hexadecimal": IsHexadecimal, - "hexcolor": IsHexcolor, - "rgbcolor": IsRGBcolor, - "lowercase": IsLowerCase, - "uppercase": IsUpperCase, - "int": IsInt, - "float": IsFloat, - "null": IsNull, - "notnull": IsNotNull, - "uuid": IsUUID, - "uuidv3": IsUUIDv3, - "uuidv4": IsUUIDv4, - "uuidv5": IsUUIDv5, - "creditcard": IsCreditCard, - "isbn10": IsISBN10, - "isbn13": IsISBN13, - "json": IsJSON, - "multibyte": IsMultibyte, - "ascii": IsASCII, - "printableascii": IsPrintableASCII, - "fullwidth": IsFullWidth, - "halfwidth": IsHalfWidth, - "variablewidth": IsVariableWidth, - "base64": IsBase64, - "datauri": IsDataURI, - "ip": IsIP, - "port": IsPort, - "ipv4": IsIPv4, - "ipv6": IsIPv6, - "dns": IsDNSName, - "host": IsHost, - "mac": IsMAC, - "latitude": IsLatitude, - "longitude": IsLongitude, - "ssn": IsSSN, - "semver": IsSemver, - "rfc3339": IsRFC3339, - "rfc3339WithoutZone": IsRFC3339WithoutZone, - "ISO3166Alpha2": IsISO3166Alpha2, - "ISO3166Alpha3": IsISO3166Alpha3, - "ISO4217": IsISO4217, - "IMEI": IsIMEI, - "ulid": IsULID, -} - -// ISO3166Entry stores country codes -type ISO3166Entry struct { - EnglishShortName string - FrenchShortName string - Alpha2Code string - Alpha3Code string - Numeric string -} - -//ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes" -var ISO3166List = []ISO3166Entry{ - {"Afghanistan", "Afghanistan (l')", "AF", "AFG", "004"}, - {"Albania", "Albanie (l')", "AL", "ALB", "008"}, - {"Antarctica", "Antarctique (l')", "AQ", "ATA", "010"}, - {"Algeria", "Algérie (l')", "DZ", "DZA", "012"}, - {"American Samoa", "Samoa américaines (les)", "AS", "ASM", "016"}, - {"Andorra", "Andorre (l')", "AD", "AND", "020"}, - {"Angola", "Angola (l')", "AO", "AGO", "024"}, - {"Antigua and Barbuda", "Antigua-et-Barbuda", "AG", "ATG", "028"}, - {"Azerbaijan", "Azerbaïdjan (l')", "AZ", "AZE", "031"}, - {"Argentina", "Argentine (l')", "AR", "ARG", "032"}, - {"Australia", "Australie (l')", "AU", "AUS", "036"}, - {"Austria", "Autriche (l')", "AT", "AUT", "040"}, - {"Bahamas (the)", "Bahamas (les)", "BS", "BHS", "044"}, - {"Bahrain", "Bahreïn", "BH", "BHR", "048"}, - {"Bangladesh", "Bangladesh (le)", "BD", "BGD", "050"}, - {"Armenia", "Arménie (l')", "AM", "ARM", "051"}, - {"Barbados", "Barbade (la)", "BB", "BRB", "052"}, - {"Belgium", "Belgique (la)", "BE", "BEL", "056"}, - {"Bermuda", "Bermudes (les)", "BM", "BMU", "060"}, - {"Bhutan", "Bhoutan (le)", "BT", "BTN", "064"}, - {"Bolivia (Plurinational State of)", "Bolivie (État plurinational de)", "BO", "BOL", "068"}, - {"Bosnia and Herzegovina", "Bosnie-Herzégovine (la)", "BA", "BIH", "070"}, - {"Botswana", "Botswana (le)", "BW", "BWA", "072"}, - {"Bouvet Island", "Bouvet (l'Île)", "BV", "BVT", "074"}, - {"Brazil", "Brésil (le)", "BR", "BRA", "076"}, - {"Belize", "Belize (le)", "BZ", "BLZ", "084"}, - {"British Indian Ocean Territory (the)", "Indien (le Territoire britannique de l'océan)", "IO", "IOT", "086"}, - {"Solomon Islands", "Salomon (Îles)", "SB", "SLB", "090"}, - {"Virgin Islands (British)", "Vierges britanniques (les Îles)", "VG", "VGB", "092"}, - {"Brunei Darussalam", "Brunéi Darussalam (le)", "BN", "BRN", "096"}, - {"Bulgaria", "Bulgarie (la)", "BG", "BGR", "100"}, - {"Myanmar", "Myanmar (le)", "MM", "MMR", "104"}, - {"Burundi", "Burundi (le)", "BI", "BDI", "108"}, - {"Belarus", "Bélarus (le)", "BY", "BLR", "112"}, - {"Cambodia", "Cambodge (le)", "KH", "KHM", "116"}, - {"Cameroon", "Cameroun (le)", "CM", "CMR", "120"}, - {"Canada", "Canada (le)", "CA", "CAN", "124"}, - {"Cabo Verde", "Cabo Verde", "CV", "CPV", "132"}, - {"Cayman Islands (the)", "Caïmans (les Îles)", "KY", "CYM", "136"}, - {"Central African Republic (the)", "République centrafricaine (la)", "CF", "CAF", "140"}, - {"Sri Lanka", "Sri Lanka", "LK", "LKA", "144"}, - {"Chad", "Tchad (le)", "TD", "TCD", "148"}, - {"Chile", "Chili (le)", "CL", "CHL", "152"}, - {"China", "Chine (la)", "CN", "CHN", "156"}, - {"Taiwan (Province of China)", "Taïwan (Province de Chine)", "TW", "TWN", "158"}, - {"Christmas Island", "Christmas (l'Île)", "CX", "CXR", "162"}, - {"Cocos (Keeling) Islands (the)", "Cocos (les Îles)/ Keeling (les Îles)", "CC", "CCK", "166"}, - {"Colombia", "Colombie (la)", "CO", "COL", "170"}, - {"Comoros (the)", "Comores (les)", "KM", "COM", "174"}, - {"Mayotte", "Mayotte", "YT", "MYT", "175"}, - {"Congo (the)", "Congo (le)", "CG", "COG", "178"}, - {"Congo (the Democratic Republic of the)", "Congo (la République démocratique du)", "CD", "COD", "180"}, - {"Cook Islands (the)", "Cook (les Îles)", "CK", "COK", "184"}, - {"Costa Rica", "Costa Rica (le)", "CR", "CRI", "188"}, - {"Croatia", "Croatie (la)", "HR", "HRV", "191"}, - {"Cuba", "Cuba", "CU", "CUB", "192"}, - {"Cyprus", "Chypre", "CY", "CYP", "196"}, - {"Czech Republic (the)", "tchèque (la République)", "CZ", "CZE", "203"}, - {"Benin", "Bénin (le)", "BJ", "BEN", "204"}, - {"Denmark", "Danemark (le)", "DK", "DNK", "208"}, - {"Dominica", "Dominique (la)", "DM", "DMA", "212"}, - {"Dominican Republic (the)", "dominicaine (la République)", "DO", "DOM", "214"}, - {"Ecuador", "Équateur (l')", "EC", "ECU", "218"}, - {"El Salvador", "El Salvador", "SV", "SLV", "222"}, - {"Equatorial Guinea", "Guinée équatoriale (la)", "GQ", "GNQ", "226"}, - {"Ethiopia", "Éthiopie (l')", "ET", "ETH", "231"}, - {"Eritrea", "Érythrée (l')", "ER", "ERI", "232"}, - {"Estonia", "Estonie (l')", "EE", "EST", "233"}, - {"Faroe Islands (the)", "Féroé (les Îles)", "FO", "FRO", "234"}, - {"Falkland Islands (the) [Malvinas]", "Falkland (les Îles)/Malouines (les Îles)", "FK", "FLK", "238"}, - {"South Georgia and the South Sandwich Islands", "Géorgie du Sud-et-les Îles Sandwich du Sud (la)", "GS", "SGS", "239"}, - {"Fiji", "Fidji (les)", "FJ", "FJI", "242"}, - {"Finland", "Finlande (la)", "FI", "FIN", "246"}, - {"Åland Islands", "Åland(les Îles)", "AX", "ALA", "248"}, - {"France", "France (la)", "FR", "FRA", "250"}, - {"French Guiana", "Guyane française (la )", "GF", "GUF", "254"}, - {"French Polynesia", "Polynésie française (la)", "PF", "PYF", "258"}, - {"French Southern Territories (the)", "Terres australes françaises (les)", "TF", "ATF", "260"}, - {"Djibouti", "Djibouti", "DJ", "DJI", "262"}, - {"Gabon", "Gabon (le)", "GA", "GAB", "266"}, - {"Georgia", "Géorgie (la)", "GE", "GEO", "268"}, - {"Gambia (the)", "Gambie (la)", "GM", "GMB", "270"}, - {"Palestine, State of", "Palestine, État de", "PS", "PSE", "275"}, - {"Germany", "Allemagne (l')", "DE", "DEU", "276"}, - {"Ghana", "Ghana (le)", "GH", "GHA", "288"}, - {"Gibraltar", "Gibraltar", "GI", "GIB", "292"}, - {"Kiribati", "Kiribati", "KI", "KIR", "296"}, - {"Greece", "Grèce (la)", "GR", "GRC", "300"}, - {"Greenland", "Groenland (le)", "GL", "GRL", "304"}, - {"Grenada", "Grenade (la)", "GD", "GRD", "308"}, - {"Guadeloupe", "Guadeloupe (la)", "GP", "GLP", "312"}, - {"Guam", "Guam", "GU", "GUM", "316"}, - {"Guatemala", "Guatemala (le)", "GT", "GTM", "320"}, - {"Guinea", "Guinée (la)", "GN", "GIN", "324"}, - {"Guyana", "Guyana (le)", "GY", "GUY", "328"}, - {"Haiti", "Haïti", "HT", "HTI", "332"}, - {"Heard Island and McDonald Islands", "Heard-et-Îles MacDonald (l'Île)", "HM", "HMD", "334"}, - {"Holy See (the)", "Saint-Siège (le)", "VA", "VAT", "336"}, - {"Honduras", "Honduras (le)", "HN", "HND", "340"}, - {"Hong Kong", "Hong Kong", "HK", "HKG", "344"}, - {"Hungary", "Hongrie (la)", "HU", "HUN", "348"}, - {"Iceland", "Islande (l')", "IS", "ISL", "352"}, - {"India", "Inde (l')", "IN", "IND", "356"}, - {"Indonesia", "Indonésie (l')", "ID", "IDN", "360"}, - {"Iran (Islamic Republic of)", "Iran (République Islamique d')", "IR", "IRN", "364"}, - {"Iraq", "Iraq (l')", "IQ", "IRQ", "368"}, - {"Ireland", "Irlande (l')", "IE", "IRL", "372"}, - {"Israel", "Israël", "IL", "ISR", "376"}, - {"Italy", "Italie (l')", "IT", "ITA", "380"}, - {"Côte d'Ivoire", "Côte d'Ivoire (la)", "CI", "CIV", "384"}, - {"Jamaica", "Jamaïque (la)", "JM", "JAM", "388"}, - {"Japan", "Japon (le)", "JP", "JPN", "392"}, - {"Kazakhstan", "Kazakhstan (le)", "KZ", "KAZ", "398"}, - {"Jordan", "Jordanie (la)", "JO", "JOR", "400"}, - {"Kenya", "Kenya (le)", "KE", "KEN", "404"}, - {"Korea (the Democratic People's Republic of)", "Corée (la République populaire démocratique de)", "KP", "PRK", "408"}, - {"Korea (the Republic of)", "Corée (la République de)", "KR", "KOR", "410"}, - {"Kuwait", "Koweït (le)", "KW", "KWT", "414"}, - {"Kyrgyzstan", "Kirghizistan (le)", "KG", "KGZ", "417"}, - {"Lao People's Democratic Republic (the)", "Lao, République démocratique populaire", "LA", "LAO", "418"}, - {"Lebanon", "Liban (le)", "LB", "LBN", "422"}, - {"Lesotho", "Lesotho (le)", "LS", "LSO", "426"}, - {"Latvia", "Lettonie (la)", "LV", "LVA", "428"}, - {"Liberia", "Libéria (le)", "LR", "LBR", "430"}, - {"Libya", "Libye (la)", "LY", "LBY", "434"}, - {"Liechtenstein", "Liechtenstein (le)", "LI", "LIE", "438"}, - {"Lithuania", "Lituanie (la)", "LT", "LTU", "440"}, - {"Luxembourg", "Luxembourg (le)", "LU", "LUX", "442"}, - {"Macao", "Macao", "MO", "MAC", "446"}, - {"Madagascar", "Madagascar", "MG", "MDG", "450"}, - {"Malawi", "Malawi (le)", "MW", "MWI", "454"}, - {"Malaysia", "Malaisie (la)", "MY", "MYS", "458"}, - {"Maldives", "Maldives (les)", "MV", "MDV", "462"}, - {"Mali", "Mali (le)", "ML", "MLI", "466"}, - {"Malta", "Malte", "MT", "MLT", "470"}, - {"Martinique", "Martinique (la)", "MQ", "MTQ", "474"}, - {"Mauritania", "Mauritanie (la)", "MR", "MRT", "478"}, - {"Mauritius", "Maurice", "MU", "MUS", "480"}, - {"Mexico", "Mexique (le)", "MX", "MEX", "484"}, - {"Monaco", "Monaco", "MC", "MCO", "492"}, - {"Mongolia", "Mongolie (la)", "MN", "MNG", "496"}, - {"Moldova (the Republic of)", "Moldova , République de", "MD", "MDA", "498"}, - {"Montenegro", "Monténégro (le)", "ME", "MNE", "499"}, - {"Montserrat", "Montserrat", "MS", "MSR", "500"}, - {"Morocco", "Maroc (le)", "MA", "MAR", "504"}, - {"Mozambique", "Mozambique (le)", "MZ", "MOZ", "508"}, - {"Oman", "Oman", "OM", "OMN", "512"}, - {"Namibia", "Namibie (la)", "NA", "NAM", "516"}, - {"Nauru", "Nauru", "NR", "NRU", "520"}, - {"Nepal", "Népal (le)", "NP", "NPL", "524"}, - {"Netherlands (the)", "Pays-Bas (les)", "NL", "NLD", "528"}, - {"Curaçao", "Curaçao", "CW", "CUW", "531"}, - {"Aruba", "Aruba", "AW", "ABW", "533"}, - {"Sint Maarten (Dutch part)", "Saint-Martin (partie néerlandaise)", "SX", "SXM", "534"}, - {"Bonaire, Sint Eustatius and Saba", "Bonaire, Saint-Eustache et Saba", "BQ", "BES", "535"}, - {"New Caledonia", "Nouvelle-Calédonie (la)", "NC", "NCL", "540"}, - {"Vanuatu", "Vanuatu (le)", "VU", "VUT", "548"}, - {"New Zealand", "Nouvelle-Zélande (la)", "NZ", "NZL", "554"}, - {"Nicaragua", "Nicaragua (le)", "NI", "NIC", "558"}, - {"Niger (the)", "Niger (le)", "NE", "NER", "562"}, - {"Nigeria", "Nigéria (le)", "NG", "NGA", "566"}, - {"Niue", "Niue", "NU", "NIU", "570"}, - {"Norfolk Island", "Norfolk (l'Île)", "NF", "NFK", "574"}, - {"Norway", "Norvège (la)", "NO", "NOR", "578"}, - {"Northern Mariana Islands (the)", "Mariannes du Nord (les Îles)", "MP", "MNP", "580"}, - {"United States Minor Outlying Islands (the)", "Îles mineures éloignées des États-Unis (les)", "UM", "UMI", "581"}, - {"Micronesia (Federated States of)", "Micronésie (États fédérés de)", "FM", "FSM", "583"}, - {"Marshall Islands (the)", "Marshall (Îles)", "MH", "MHL", "584"}, - {"Palau", "Palaos (les)", "PW", "PLW", "585"}, - {"Pakistan", "Pakistan (le)", "PK", "PAK", "586"}, - {"Panama", "Panama (le)", "PA", "PAN", "591"}, - {"Papua New Guinea", "Papouasie-Nouvelle-Guinée (la)", "PG", "PNG", "598"}, - {"Paraguay", "Paraguay (le)", "PY", "PRY", "600"}, - {"Peru", "Pérou (le)", "PE", "PER", "604"}, - {"Philippines (the)", "Philippines (les)", "PH", "PHL", "608"}, - {"Pitcairn", "Pitcairn", "PN", "PCN", "612"}, - {"Poland", "Pologne (la)", "PL", "POL", "616"}, - {"Portugal", "Portugal (le)", "PT", "PRT", "620"}, - {"Guinea-Bissau", "Guinée-Bissau (la)", "GW", "GNB", "624"}, - {"Timor-Leste", "Timor-Leste (le)", "TL", "TLS", "626"}, - {"Puerto Rico", "Porto Rico", "PR", "PRI", "630"}, - {"Qatar", "Qatar (le)", "QA", "QAT", "634"}, - {"Réunion", "Réunion (La)", "RE", "REU", "638"}, - {"Romania", "Roumanie (la)", "RO", "ROU", "642"}, - {"Russian Federation (the)", "Russie (la Fédération de)", "RU", "RUS", "643"}, - {"Rwanda", "Rwanda (le)", "RW", "RWA", "646"}, - {"Saint Barthélemy", "Saint-Barthélemy", "BL", "BLM", "652"}, - {"Saint Helena, Ascension and Tristan da Cunha", "Sainte-Hélène, Ascension et Tristan da Cunha", "SH", "SHN", "654"}, - {"Saint Kitts and Nevis", "Saint-Kitts-et-Nevis", "KN", "KNA", "659"}, - {"Anguilla", "Anguilla", "AI", "AIA", "660"}, - {"Saint Lucia", "Sainte-Lucie", "LC", "LCA", "662"}, - {"Saint Martin (French part)", "Saint-Martin (partie française)", "MF", "MAF", "663"}, - {"Saint Pierre and Miquelon", "Saint-Pierre-et-Miquelon", "PM", "SPM", "666"}, - {"Saint Vincent and the Grenadines", "Saint-Vincent-et-les Grenadines", "VC", "VCT", "670"}, - {"San Marino", "Saint-Marin", "SM", "SMR", "674"}, - {"Sao Tome and Principe", "Sao Tomé-et-Principe", "ST", "STP", "678"}, - {"Saudi Arabia", "Arabie saoudite (l')", "SA", "SAU", "682"}, - {"Senegal", "Sénégal (le)", "SN", "SEN", "686"}, - {"Serbia", "Serbie (la)", "RS", "SRB", "688"}, - {"Seychelles", "Seychelles (les)", "SC", "SYC", "690"}, - {"Sierra Leone", "Sierra Leone (la)", "SL", "SLE", "694"}, - {"Singapore", "Singapour", "SG", "SGP", "702"}, - {"Slovakia", "Slovaquie (la)", "SK", "SVK", "703"}, - {"Viet Nam", "Viet Nam (le)", "VN", "VNM", "704"}, - {"Slovenia", "Slovénie (la)", "SI", "SVN", "705"}, - {"Somalia", "Somalie (la)", "SO", "SOM", "706"}, - {"South Africa", "Afrique du Sud (l')", "ZA", "ZAF", "710"}, - {"Zimbabwe", "Zimbabwe (le)", "ZW", "ZWE", "716"}, - {"Spain", "Espagne (l')", "ES", "ESP", "724"}, - {"South Sudan", "Soudan du Sud (le)", "SS", "SSD", "728"}, - {"Sudan (the)", "Soudan (le)", "SD", "SDN", "729"}, - {"Western Sahara*", "Sahara occidental (le)*", "EH", "ESH", "732"}, - {"Suriname", "Suriname (le)", "SR", "SUR", "740"}, - {"Svalbard and Jan Mayen", "Svalbard et l'Île Jan Mayen (le)", "SJ", "SJM", "744"}, - {"Swaziland", "Swaziland (le)", "SZ", "SWZ", "748"}, - {"Sweden", "Suède (la)", "SE", "SWE", "752"}, - {"Switzerland", "Suisse (la)", "CH", "CHE", "756"}, - {"Syrian Arab Republic", "République arabe syrienne (la)", "SY", "SYR", "760"}, - {"Tajikistan", "Tadjikistan (le)", "TJ", "TJK", "762"}, - {"Thailand", "Thaïlande (la)", "TH", "THA", "764"}, - {"Togo", "Togo (le)", "TG", "TGO", "768"}, - {"Tokelau", "Tokelau (les)", "TK", "TKL", "772"}, - {"Tonga", "Tonga (les)", "TO", "TON", "776"}, - {"Trinidad and Tobago", "Trinité-et-Tobago (la)", "TT", "TTO", "780"}, - {"United Arab Emirates (the)", "Émirats arabes unis (les)", "AE", "ARE", "784"}, - {"Tunisia", "Tunisie (la)", "TN", "TUN", "788"}, - {"Turkey", "Turquie (la)", "TR", "TUR", "792"}, - {"Turkmenistan", "Turkménistan (le)", "TM", "TKM", "795"}, - {"Turks and Caicos Islands (the)", "Turks-et-Caïcos (les Îles)", "TC", "TCA", "796"}, - {"Tuvalu", "Tuvalu (les)", "TV", "TUV", "798"}, - {"Uganda", "Ouganda (l')", "UG", "UGA", "800"}, - {"Ukraine", "Ukraine (l')", "UA", "UKR", "804"}, - {"Macedonia (the former Yugoslav Republic of)", "Macédoine (l'ex‑République yougoslave de)", "MK", "MKD", "807"}, - {"Egypt", "Égypte (l')", "EG", "EGY", "818"}, - {"United Kingdom of Great Britain and Northern Ireland (the)", "Royaume-Uni de Grande-Bretagne et d'Irlande du Nord (le)", "GB", "GBR", "826"}, - {"Guernsey", "Guernesey", "GG", "GGY", "831"}, - {"Jersey", "Jersey", "JE", "JEY", "832"}, - {"Isle of Man", "Île de Man", "IM", "IMN", "833"}, - {"Tanzania, United Republic of", "Tanzanie, République-Unie de", "TZ", "TZA", "834"}, - {"United States of America (the)", "États-Unis d'Amérique (les)", "US", "USA", "840"}, - {"Virgin Islands (U.S.)", "Vierges des États-Unis (les Îles)", "VI", "VIR", "850"}, - {"Burkina Faso", "Burkina Faso (le)", "BF", "BFA", "854"}, - {"Uruguay", "Uruguay (l')", "UY", "URY", "858"}, - {"Uzbekistan", "Ouzbékistan (l')", "UZ", "UZB", "860"}, - {"Venezuela (Bolivarian Republic of)", "Venezuela (République bolivarienne du)", "VE", "VEN", "862"}, - {"Wallis and Futuna", "Wallis-et-Futuna", "WF", "WLF", "876"}, - {"Samoa", "Samoa (le)", "WS", "WSM", "882"}, - {"Yemen", "Yémen (le)", "YE", "YEM", "887"}, - {"Zambia", "Zambie (la)", "ZM", "ZMB", "894"}, -} - -// ISO4217List is the list of ISO currency codes -var ISO4217List = []string{ - "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", - "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", - "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", - "DJF", "DKK", "DOP", "DZD", - "EGP", "ERN", "ETB", "EUR", - "FJD", "FKP", - "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", - "HKD", "HNL", "HRK", "HTG", "HUF", - "IDR", "ILS", "INR", "IQD", "IRR", "ISK", - "JMD", "JOD", "JPY", - "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", - "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", - "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", - "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", - "OMR", - "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", - "QAR", - "RON", "RSD", "RUB", "RWF", - "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "STN", "SVC", "SYP", "SZL", - "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", - "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", "UZS", - "VEF", "VES", "VND", "VUV", - "WST", - "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX", - "YER", - "ZAR", "ZMW", "ZWL", -} - -// ISO693Entry stores ISO language codes -type ISO693Entry struct { - Alpha3bCode string - Alpha2Code string - English string -} - -//ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json -var ISO693List = []ISO693Entry{ - {Alpha3bCode: "aar", Alpha2Code: "aa", English: "Afar"}, - {Alpha3bCode: "abk", Alpha2Code: "ab", English: "Abkhazian"}, - {Alpha3bCode: "afr", Alpha2Code: "af", English: "Afrikaans"}, - {Alpha3bCode: "aka", Alpha2Code: "ak", English: "Akan"}, - {Alpha3bCode: "alb", Alpha2Code: "sq", English: "Albanian"}, - {Alpha3bCode: "amh", Alpha2Code: "am", English: "Amharic"}, - {Alpha3bCode: "ara", Alpha2Code: "ar", English: "Arabic"}, - {Alpha3bCode: "arg", Alpha2Code: "an", English: "Aragonese"}, - {Alpha3bCode: "arm", Alpha2Code: "hy", English: "Armenian"}, - {Alpha3bCode: "asm", Alpha2Code: "as", English: "Assamese"}, - {Alpha3bCode: "ava", Alpha2Code: "av", English: "Avaric"}, - {Alpha3bCode: "ave", Alpha2Code: "ae", English: "Avestan"}, - {Alpha3bCode: "aym", Alpha2Code: "ay", English: "Aymara"}, - {Alpha3bCode: "aze", Alpha2Code: "az", English: "Azerbaijani"}, - {Alpha3bCode: "bak", Alpha2Code: "ba", English: "Bashkir"}, - {Alpha3bCode: "bam", Alpha2Code: "bm", English: "Bambara"}, - {Alpha3bCode: "baq", Alpha2Code: "eu", English: "Basque"}, - {Alpha3bCode: "bel", Alpha2Code: "be", English: "Belarusian"}, - {Alpha3bCode: "ben", Alpha2Code: "bn", English: "Bengali"}, - {Alpha3bCode: "bih", Alpha2Code: "bh", English: "Bihari languages"}, - {Alpha3bCode: "bis", Alpha2Code: "bi", English: "Bislama"}, - {Alpha3bCode: "bos", Alpha2Code: "bs", English: "Bosnian"}, - {Alpha3bCode: "bre", Alpha2Code: "br", English: "Breton"}, - {Alpha3bCode: "bul", Alpha2Code: "bg", English: "Bulgarian"}, - {Alpha3bCode: "bur", Alpha2Code: "my", English: "Burmese"}, - {Alpha3bCode: "cat", Alpha2Code: "ca", English: "Catalan; Valencian"}, - {Alpha3bCode: "cha", Alpha2Code: "ch", English: "Chamorro"}, - {Alpha3bCode: "che", Alpha2Code: "ce", English: "Chechen"}, - {Alpha3bCode: "chi", Alpha2Code: "zh", English: "Chinese"}, - {Alpha3bCode: "chu", Alpha2Code: "cu", English: "Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic"}, - {Alpha3bCode: "chv", Alpha2Code: "cv", English: "Chuvash"}, - {Alpha3bCode: "cor", Alpha2Code: "kw", English: "Cornish"}, - {Alpha3bCode: "cos", Alpha2Code: "co", English: "Corsican"}, - {Alpha3bCode: "cre", Alpha2Code: "cr", English: "Cree"}, - {Alpha3bCode: "cze", Alpha2Code: "cs", English: "Czech"}, - {Alpha3bCode: "dan", Alpha2Code: "da", English: "Danish"}, - {Alpha3bCode: "div", Alpha2Code: "dv", English: "Divehi; Dhivehi; Maldivian"}, - {Alpha3bCode: "dut", Alpha2Code: "nl", English: "Dutch; Flemish"}, - {Alpha3bCode: "dzo", Alpha2Code: "dz", English: "Dzongkha"}, - {Alpha3bCode: "eng", Alpha2Code: "en", English: "English"}, - {Alpha3bCode: "epo", Alpha2Code: "eo", English: "Esperanto"}, - {Alpha3bCode: "est", Alpha2Code: "et", English: "Estonian"}, - {Alpha3bCode: "ewe", Alpha2Code: "ee", English: "Ewe"}, - {Alpha3bCode: "fao", Alpha2Code: "fo", English: "Faroese"}, - {Alpha3bCode: "fij", Alpha2Code: "fj", English: "Fijian"}, - {Alpha3bCode: "fin", Alpha2Code: "fi", English: "Finnish"}, - {Alpha3bCode: "fre", Alpha2Code: "fr", English: "French"}, - {Alpha3bCode: "fry", Alpha2Code: "fy", English: "Western Frisian"}, - {Alpha3bCode: "ful", Alpha2Code: "ff", English: "Fulah"}, - {Alpha3bCode: "geo", Alpha2Code: "ka", English: "Georgian"}, - {Alpha3bCode: "ger", Alpha2Code: "de", English: "German"}, - {Alpha3bCode: "gla", Alpha2Code: "gd", English: "Gaelic; Scottish Gaelic"}, - {Alpha3bCode: "gle", Alpha2Code: "ga", English: "Irish"}, - {Alpha3bCode: "glg", Alpha2Code: "gl", English: "Galician"}, - {Alpha3bCode: "glv", Alpha2Code: "gv", English: "Manx"}, - {Alpha3bCode: "gre", Alpha2Code: "el", English: "Greek, Modern (1453-)"}, - {Alpha3bCode: "grn", Alpha2Code: "gn", English: "Guarani"}, - {Alpha3bCode: "guj", Alpha2Code: "gu", English: "Gujarati"}, - {Alpha3bCode: "hat", Alpha2Code: "ht", English: "Haitian; Haitian Creole"}, - {Alpha3bCode: "hau", Alpha2Code: "ha", English: "Hausa"}, - {Alpha3bCode: "heb", Alpha2Code: "he", English: "Hebrew"}, - {Alpha3bCode: "her", Alpha2Code: "hz", English: "Herero"}, - {Alpha3bCode: "hin", Alpha2Code: "hi", English: "Hindi"}, - {Alpha3bCode: "hmo", Alpha2Code: "ho", English: "Hiri Motu"}, - {Alpha3bCode: "hrv", Alpha2Code: "hr", English: "Croatian"}, - {Alpha3bCode: "hun", Alpha2Code: "hu", English: "Hungarian"}, - {Alpha3bCode: "ibo", Alpha2Code: "ig", English: "Igbo"}, - {Alpha3bCode: "ice", Alpha2Code: "is", English: "Icelandic"}, - {Alpha3bCode: "ido", Alpha2Code: "io", English: "Ido"}, - {Alpha3bCode: "iii", Alpha2Code: "ii", English: "Sichuan Yi; Nuosu"}, - {Alpha3bCode: "iku", Alpha2Code: "iu", English: "Inuktitut"}, - {Alpha3bCode: "ile", Alpha2Code: "ie", English: "Interlingue; Occidental"}, - {Alpha3bCode: "ina", Alpha2Code: "ia", English: "Interlingua (International Auxiliary Language Association)"}, - {Alpha3bCode: "ind", Alpha2Code: "id", English: "Indonesian"}, - {Alpha3bCode: "ipk", Alpha2Code: "ik", English: "Inupiaq"}, - {Alpha3bCode: "ita", Alpha2Code: "it", English: "Italian"}, - {Alpha3bCode: "jav", Alpha2Code: "jv", English: "Javanese"}, - {Alpha3bCode: "jpn", Alpha2Code: "ja", English: "Japanese"}, - {Alpha3bCode: "kal", Alpha2Code: "kl", English: "Kalaallisut; Greenlandic"}, - {Alpha3bCode: "kan", Alpha2Code: "kn", English: "Kannada"}, - {Alpha3bCode: "kas", Alpha2Code: "ks", English: "Kashmiri"}, - {Alpha3bCode: "kau", Alpha2Code: "kr", English: "Kanuri"}, - {Alpha3bCode: "kaz", Alpha2Code: "kk", English: "Kazakh"}, - {Alpha3bCode: "khm", Alpha2Code: "km", English: "Central Khmer"}, - {Alpha3bCode: "kik", Alpha2Code: "ki", English: "Kikuyu; Gikuyu"}, - {Alpha3bCode: "kin", Alpha2Code: "rw", English: "Kinyarwanda"}, - {Alpha3bCode: "kir", Alpha2Code: "ky", English: "Kirghiz; Kyrgyz"}, - {Alpha3bCode: "kom", Alpha2Code: "kv", English: "Komi"}, - {Alpha3bCode: "kon", Alpha2Code: "kg", English: "Kongo"}, - {Alpha3bCode: "kor", Alpha2Code: "ko", English: "Korean"}, - {Alpha3bCode: "kua", Alpha2Code: "kj", English: "Kuanyama; Kwanyama"}, - {Alpha3bCode: "kur", Alpha2Code: "ku", English: "Kurdish"}, - {Alpha3bCode: "lao", Alpha2Code: "lo", English: "Lao"}, - {Alpha3bCode: "lat", Alpha2Code: "la", English: "Latin"}, - {Alpha3bCode: "lav", Alpha2Code: "lv", English: "Latvian"}, - {Alpha3bCode: "lim", Alpha2Code: "li", English: "Limburgan; Limburger; Limburgish"}, - {Alpha3bCode: "lin", Alpha2Code: "ln", English: "Lingala"}, - {Alpha3bCode: "lit", Alpha2Code: "lt", English: "Lithuanian"}, - {Alpha3bCode: "ltz", Alpha2Code: "lb", English: "Luxembourgish; Letzeburgesch"}, - {Alpha3bCode: "lub", Alpha2Code: "lu", English: "Luba-Katanga"}, - {Alpha3bCode: "lug", Alpha2Code: "lg", English: "Ganda"}, - {Alpha3bCode: "mac", Alpha2Code: "mk", English: "Macedonian"}, - {Alpha3bCode: "mah", Alpha2Code: "mh", English: "Marshallese"}, - {Alpha3bCode: "mal", Alpha2Code: "ml", English: "Malayalam"}, - {Alpha3bCode: "mao", Alpha2Code: "mi", English: "Maori"}, - {Alpha3bCode: "mar", Alpha2Code: "mr", English: "Marathi"}, - {Alpha3bCode: "may", Alpha2Code: "ms", English: "Malay"}, - {Alpha3bCode: "mlg", Alpha2Code: "mg", English: "Malagasy"}, - {Alpha3bCode: "mlt", Alpha2Code: "mt", English: "Maltese"}, - {Alpha3bCode: "mon", Alpha2Code: "mn", English: "Mongolian"}, - {Alpha3bCode: "nau", Alpha2Code: "na", English: "Nauru"}, - {Alpha3bCode: "nav", Alpha2Code: "nv", English: "Navajo; Navaho"}, - {Alpha3bCode: "nbl", Alpha2Code: "nr", English: "Ndebele, South; South Ndebele"}, - {Alpha3bCode: "nde", Alpha2Code: "nd", English: "Ndebele, North; North Ndebele"}, - {Alpha3bCode: "ndo", Alpha2Code: "ng", English: "Ndonga"}, - {Alpha3bCode: "nep", Alpha2Code: "ne", English: "Nepali"}, - {Alpha3bCode: "nno", Alpha2Code: "nn", English: "Norwegian Nynorsk; Nynorsk, Norwegian"}, - {Alpha3bCode: "nob", Alpha2Code: "nb", English: "Bokmål, Norwegian; Norwegian Bokmål"}, - {Alpha3bCode: "nor", Alpha2Code: "no", English: "Norwegian"}, - {Alpha3bCode: "nya", Alpha2Code: "ny", English: "Chichewa; Chewa; Nyanja"}, - {Alpha3bCode: "oci", Alpha2Code: "oc", English: "Occitan (post 1500); Provençal"}, - {Alpha3bCode: "oji", Alpha2Code: "oj", English: "Ojibwa"}, - {Alpha3bCode: "ori", Alpha2Code: "or", English: "Oriya"}, - {Alpha3bCode: "orm", Alpha2Code: "om", English: "Oromo"}, - {Alpha3bCode: "oss", Alpha2Code: "os", English: "Ossetian; Ossetic"}, - {Alpha3bCode: "pan", Alpha2Code: "pa", English: "Panjabi; Punjabi"}, - {Alpha3bCode: "per", Alpha2Code: "fa", English: "Persian"}, - {Alpha3bCode: "pli", Alpha2Code: "pi", English: "Pali"}, - {Alpha3bCode: "pol", Alpha2Code: "pl", English: "Polish"}, - {Alpha3bCode: "por", Alpha2Code: "pt", English: "Portuguese"}, - {Alpha3bCode: "pus", Alpha2Code: "ps", English: "Pushto; Pashto"}, - {Alpha3bCode: "que", Alpha2Code: "qu", English: "Quechua"}, - {Alpha3bCode: "roh", Alpha2Code: "rm", English: "Romansh"}, - {Alpha3bCode: "rum", Alpha2Code: "ro", English: "Romanian; Moldavian; Moldovan"}, - {Alpha3bCode: "run", Alpha2Code: "rn", English: "Rundi"}, - {Alpha3bCode: "rus", Alpha2Code: "ru", English: "Russian"}, - {Alpha3bCode: "sag", Alpha2Code: "sg", English: "Sango"}, - {Alpha3bCode: "san", Alpha2Code: "sa", English: "Sanskrit"}, - {Alpha3bCode: "sin", Alpha2Code: "si", English: "Sinhala; Sinhalese"}, - {Alpha3bCode: "slo", Alpha2Code: "sk", English: "Slovak"}, - {Alpha3bCode: "slv", Alpha2Code: "sl", English: "Slovenian"}, - {Alpha3bCode: "sme", Alpha2Code: "se", English: "Northern Sami"}, - {Alpha3bCode: "smo", Alpha2Code: "sm", English: "Samoan"}, - {Alpha3bCode: "sna", Alpha2Code: "sn", English: "Shona"}, - {Alpha3bCode: "snd", Alpha2Code: "sd", English: "Sindhi"}, - {Alpha3bCode: "som", Alpha2Code: "so", English: "Somali"}, - {Alpha3bCode: "sot", Alpha2Code: "st", English: "Sotho, Southern"}, - {Alpha3bCode: "spa", Alpha2Code: "es", English: "Spanish; Castilian"}, - {Alpha3bCode: "srd", Alpha2Code: "sc", English: "Sardinian"}, - {Alpha3bCode: "srp", Alpha2Code: "sr", English: "Serbian"}, - {Alpha3bCode: "ssw", Alpha2Code: "ss", English: "Swati"}, - {Alpha3bCode: "sun", Alpha2Code: "su", English: "Sundanese"}, - {Alpha3bCode: "swa", Alpha2Code: "sw", English: "Swahili"}, - {Alpha3bCode: "swe", Alpha2Code: "sv", English: "Swedish"}, - {Alpha3bCode: "tah", Alpha2Code: "ty", English: "Tahitian"}, - {Alpha3bCode: "tam", Alpha2Code: "ta", English: "Tamil"}, - {Alpha3bCode: "tat", Alpha2Code: "tt", English: "Tatar"}, - {Alpha3bCode: "tel", Alpha2Code: "te", English: "Telugu"}, - {Alpha3bCode: "tgk", Alpha2Code: "tg", English: "Tajik"}, - {Alpha3bCode: "tgl", Alpha2Code: "tl", English: "Tagalog"}, - {Alpha3bCode: "tha", Alpha2Code: "th", English: "Thai"}, - {Alpha3bCode: "tib", Alpha2Code: "bo", English: "Tibetan"}, - {Alpha3bCode: "tir", Alpha2Code: "ti", English: "Tigrinya"}, - {Alpha3bCode: "ton", Alpha2Code: "to", English: "Tonga (Tonga Islands)"}, - {Alpha3bCode: "tsn", Alpha2Code: "tn", English: "Tswana"}, - {Alpha3bCode: "tso", Alpha2Code: "ts", English: "Tsonga"}, - {Alpha3bCode: "tuk", Alpha2Code: "tk", English: "Turkmen"}, - {Alpha3bCode: "tur", Alpha2Code: "tr", English: "Turkish"}, - {Alpha3bCode: "twi", Alpha2Code: "tw", English: "Twi"}, - {Alpha3bCode: "uig", Alpha2Code: "ug", English: "Uighur; Uyghur"}, - {Alpha3bCode: "ukr", Alpha2Code: "uk", English: "Ukrainian"}, - {Alpha3bCode: "urd", Alpha2Code: "ur", English: "Urdu"}, - {Alpha3bCode: "uzb", Alpha2Code: "uz", English: "Uzbek"}, - {Alpha3bCode: "ven", Alpha2Code: "ve", English: "Venda"}, - {Alpha3bCode: "vie", Alpha2Code: "vi", English: "Vietnamese"}, - {Alpha3bCode: "vol", Alpha2Code: "vo", English: "Volapük"}, - {Alpha3bCode: "wel", Alpha2Code: "cy", English: "Welsh"}, - {Alpha3bCode: "wln", Alpha2Code: "wa", English: "Walloon"}, - {Alpha3bCode: "wol", Alpha2Code: "wo", English: "Wolof"}, - {Alpha3bCode: "xho", Alpha2Code: "xh", English: "Xhosa"}, - {Alpha3bCode: "yid", Alpha2Code: "yi", English: "Yiddish"}, - {Alpha3bCode: "yor", Alpha2Code: "yo", English: "Yoruba"}, - {Alpha3bCode: "zha", Alpha2Code: "za", English: "Zhuang; Chuang"}, - {Alpha3bCode: "zul", Alpha2Code: "zu", English: "Zulu"}, -} diff --git a/vendor/github.com/asaskevich/govalidator/utils.go b/vendor/github.com/asaskevich/govalidator/utils.go deleted file mode 100644 index f4c30f8..0000000 --- a/vendor/github.com/asaskevich/govalidator/utils.go +++ /dev/null @@ -1,270 +0,0 @@ -package govalidator - -import ( - "errors" - "fmt" - "html" - "math" - "path" - "regexp" - "strings" - "unicode" - "unicode/utf8" -) - -// Contains checks if the string contains the substring. -func Contains(str, substring string) bool { - return strings.Contains(str, substring) -} - -// Matches checks if string matches the pattern (pattern is regular expression) -// In case of error return false -func Matches(str, pattern string) bool { - match, _ := regexp.MatchString(pattern, str) - return match -} - -// LeftTrim trims characters from the left side of the input. -// If second argument is empty, it will remove leading spaces. -func LeftTrim(str, chars string) string { - if chars == "" { - return strings.TrimLeftFunc(str, unicode.IsSpace) - } - r, _ := regexp.Compile("^[" + chars + "]+") - return r.ReplaceAllString(str, "") -} - -// RightTrim trims characters from the right side of the input. -// If second argument is empty, it will remove trailing spaces. -func RightTrim(str, chars string) string { - if chars == "" { - return strings.TrimRightFunc(str, unicode.IsSpace) - } - r, _ := regexp.Compile("[" + chars + "]+$") - return r.ReplaceAllString(str, "") -} - -// Trim trims characters from both sides of the input. -// If second argument is empty, it will remove spaces. -func Trim(str, chars string) string { - return LeftTrim(RightTrim(str, chars), chars) -} - -// WhiteList removes characters that do not appear in the whitelist. -func WhiteList(str, chars string) string { - pattern := "[^" + chars + "]+" - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, "") -} - -// BlackList removes characters that appear in the blacklist. -func BlackList(str, chars string) string { - pattern := "[" + chars + "]+" - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, "") -} - -// StripLow removes characters with a numerical value < 32 and 127, mostly control characters. -// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD). -func StripLow(str string, keepNewLines bool) string { - chars := "" - if keepNewLines { - chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F" - } else { - chars = "\x00-\x1F\x7F" - } - return BlackList(str, chars) -} - -// ReplacePattern replaces regular expression pattern in string -func ReplacePattern(str, pattern, replace string) string { - r, _ := regexp.Compile(pattern) - return r.ReplaceAllString(str, replace) -} - -// Escape replaces <, >, & and " with HTML entities. -var Escape = html.EscapeString - -func addSegment(inrune, segment []rune) []rune { - if len(segment) == 0 { - return inrune - } - if len(inrune) != 0 { - inrune = append(inrune, '_') - } - inrune = append(inrune, segment...) - return inrune -} - -// UnderscoreToCamelCase converts from underscore separated form to camel case form. -// Ex.: my_func => MyFunc -func UnderscoreToCamelCase(s string) string { - return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1) -} - -// CamelCaseToUnderscore converts from camel case form to underscore separated form. -// Ex.: MyFunc => my_func -func CamelCaseToUnderscore(str string) string { - var output []rune - var segment []rune - for _, r := range str { - - // not treat number as separate segment - if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) { - output = addSegment(output, segment) - segment = nil - } - segment = append(segment, unicode.ToLower(r)) - } - output = addSegment(output, segment) - return string(output) -} - -// Reverse returns reversed string -func Reverse(s string) string { - r := []rune(s) - for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r) -} - -// GetLines splits string by "\n" and return array of lines -func GetLines(s string) []string { - return strings.Split(s, "\n") -} - -// GetLine returns specified line of multiline string -func GetLine(s string, index int) (string, error) { - lines := GetLines(s) - if index < 0 || index >= len(lines) { - return "", errors.New("line index out of bounds") - } - return lines[index], nil -} - -// RemoveTags removes all tags from HTML string -func RemoveTags(s string) string { - return ReplacePattern(s, "<[^>]*>", "") -} - -// SafeFileName returns safe string that can be used in file names -func SafeFileName(str string) string { - name := strings.ToLower(str) - name = path.Clean(path.Base(name)) - name = strings.Trim(name, " ") - separators, err := regexp.Compile(`[ &_=+:]`) - if err == nil { - name = separators.ReplaceAllString(name, "-") - } - legal, err := regexp.Compile(`[^[:alnum:]-.]`) - if err == nil { - name = legal.ReplaceAllString(name, "") - } - for strings.Contains(name, "--") { - name = strings.Replace(name, "--", "-", -1) - } - return name -} - -// NormalizeEmail canonicalize an email address. -// The local part of the email address is lowercased for all domains; the hostname is always lowercased and -// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). -// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and -// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are -// normalized to @gmail.com. -func NormalizeEmail(str string) (string, error) { - if !IsEmail(str) { - return "", fmt.Errorf("%s is not an email", str) - } - parts := strings.Split(str, "@") - parts[0] = strings.ToLower(parts[0]) - parts[1] = strings.ToLower(parts[1]) - if parts[1] == "gmail.com" || parts[1] == "googlemail.com" { - parts[1] = "gmail.com" - parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0] - } - return strings.Join(parts, "@"), nil -} - -// Truncate a string to the closest length without breaking words. -func Truncate(str string, length int, ending string) string { - var aftstr, befstr string - if len(str) > length { - words := strings.Fields(str) - before, present := 0, 0 - for i := range words { - befstr = aftstr - before = present - aftstr = aftstr + words[i] + " " - present = len(aftstr) - if present > length && i != 0 { - if (length - before) < (present - length) { - return Trim(befstr, " /\\.,\"'#!?&@+-") + ending - } - return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending - } - } - } - - return str -} - -// PadLeft pads left side of a string if size of string is less then indicated pad length -func PadLeft(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, true, false) -} - -// PadRight pads right side of a string if size of string is less then indicated pad length -func PadRight(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, false, true) -} - -// PadBoth pads both sides of a string if size of string is less then indicated pad length -func PadBoth(str string, padStr string, padLen int) string { - return buildPadStr(str, padStr, padLen, true, true) -} - -// PadString either left, right or both sides. -// Note that padding string can be unicode and more then one character -func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string { - - // When padded length is less then the current string size - if padLen < utf8.RuneCountInString(str) { - return str - } - - padLen -= utf8.RuneCountInString(str) - - targetLen := padLen - - targetLenLeft := targetLen - targetLenRight := targetLen - if padLeft && padRight { - targetLenLeft = padLen / 2 - targetLenRight = padLen - targetLenLeft - } - - strToRepeatLen := utf8.RuneCountInString(padStr) - - repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen))) - repeatedString := strings.Repeat(padStr, repeatTimes) - - leftSide := "" - if padLeft { - leftSide = repeatedString[0:targetLenLeft] - } - - rightSide := "" - if padRight { - rightSide = repeatedString[0:targetLenRight] - } - - return leftSide + str + rightSide -} - -// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object -func TruncatingErrorf(str string, args ...interface{}) error { - n := strings.Count(str, "%s") - return fmt.Errorf(str, args[:n]...) -} diff --git a/vendor/github.com/asaskevich/govalidator/validator.go b/vendor/github.com/asaskevich/govalidator/validator.go deleted file mode 100644 index 46ecfc8..0000000 --- a/vendor/github.com/asaskevich/govalidator/validator.go +++ /dev/null @@ -1,1769 +0,0 @@ -// Package govalidator is package of validators and sanitizers for strings, structs and collections. -package govalidator - -import ( - "bytes" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "fmt" - "io/ioutil" - "net" - "net/url" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" -) - -var ( - fieldsRequiredByDefault bool - nilPtrAllowedByRequired = false - notNumberRegexp = regexp.MustCompile("[^0-9]+") - whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) - paramsRegexp = regexp.MustCompile(`\(.*\)$`) -) - -const maxURLRuneCount = 2083 -const minURLRuneCount = 3 -const rfc3339WithoutZone = "2006-01-02T15:04:05" - -// SetFieldsRequiredByDefault causes validation to fail when struct fields -// do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). -// This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): -// type exampleStruct struct { -// Name string `` -// Email string `valid:"email"` -// This, however, will only fail when Email is empty or an invalid email address: -// type exampleStruct2 struct { -// Name string `valid:"-"` -// Email string `valid:"email"` -// Lastly, this will only fail when Email is an invalid email address but not when it's empty: -// type exampleStruct2 struct { -// Name string `valid:"-"` -// Email string `valid:"email,optional"` -func SetFieldsRequiredByDefault(value bool) { - fieldsRequiredByDefault = value -} - -// SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. -// The validation will still reject ptr fields in their zero value state. Example with this enabled: -// type exampleStruct struct { -// Name *string `valid:"required"` -// With `Name` set to "", this will be considered invalid input and will cause a validation error. -// With `Name` set to nil, this will be considered valid by validation. -// By default this is disabled. -func SetNilPtrAllowedByRequired(value bool) { - nilPtrAllowedByRequired = value -} - -// IsEmail checks if the string is an email. -func IsEmail(str string) bool { - // TODO uppercase letters are not supported - return rxEmail.MatchString(str) -} - -// IsExistingEmail checks if the string is an email of existing domain -func IsExistingEmail(email string) bool { - - if len(email) < 6 || len(email) > 254 { - return false - } - at := strings.LastIndex(email, "@") - if at <= 0 || at > len(email)-3 { - return false - } - user := email[:at] - host := email[at+1:] - if len(user) > 64 { - return false - } - switch host { - case "localhost", "example.com": - return true - } - if userDotRegexp.MatchString(user) || !userRegexp.MatchString(user) || !hostRegexp.MatchString(host) { - return false - } - if _, err := net.LookupMX(host); err != nil { - if _, err := net.LookupIP(host); err != nil { - return false - } - } - - return true -} - -// IsURL checks if the string is an URL. -func IsURL(str string) bool { - if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") { - return false - } - strTemp := str - if strings.Contains(str, ":") && !strings.Contains(str, "://") { - // support no indicated urlscheme but with colon for port number - // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString - strTemp = "http://" + str - } - u, err := url.Parse(strTemp) - if err != nil { - return false - } - if strings.HasPrefix(u.Host, ".") { - return false - } - if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { - return false - } - return rxURL.MatchString(str) -} - -// IsRequestURL checks if the string rawurl, assuming -// it was received in an HTTP request, is a valid -// URL confirm to RFC 3986 -func IsRequestURL(rawurl string) bool { - url, err := url.ParseRequestURI(rawurl) - if err != nil { - return false //Couldn't even parse the rawurl - } - if len(url.Scheme) == 0 { - return false //No Scheme found - } - return true -} - -// IsRequestURI checks if the string rawurl, assuming -// it was received in an HTTP request, is an -// absolute URI or an absolute path. -func IsRequestURI(rawurl string) bool { - _, err := url.ParseRequestURI(rawurl) - return err == nil -} - -// IsAlpha checks if the string contains only letters (a-zA-Z). Empty string is valid. -func IsAlpha(str string) bool { - if IsNull(str) { - return true - } - return rxAlpha.MatchString(str) -} - -//IsUTFLetter checks if the string contains only unicode letter characters. -//Similar to IsAlpha but for all languages. Empty string is valid. -func IsUTFLetter(str string) bool { - if IsNull(str) { - return true - } - - for _, c := range str { - if !unicode.IsLetter(c) { - return false - } - } - return true - -} - -// IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid. -func IsAlphanumeric(str string) bool { - if IsNull(str) { - return true - } - return rxAlphanumeric.MatchString(str) -} - -// IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid. -func IsUTFLetterNumeric(str string) bool { - if IsNull(str) { - return true - } - for _, c := range str { - if !unicode.IsLetter(c) && !unicode.IsNumber(c) { //letters && numbers are ok - return false - } - } - return true - -} - -// IsNumeric checks if the string contains only numbers. Empty string is valid. -func IsNumeric(str string) bool { - if IsNull(str) { - return true - } - return rxNumeric.MatchString(str) -} - -// IsUTFNumeric checks if the string contains only unicode numbers of any kind. -// Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. -func IsUTFNumeric(str string) bool { - if IsNull(str) { - return true - } - if strings.IndexAny(str, "+-") > 0 { - return false - } - if len(str) > 1 { - str = strings.TrimPrefix(str, "-") - str = strings.TrimPrefix(str, "+") - } - for _, c := range str { - if !unicode.IsNumber(c) { //numbers && minus sign are ok - return false - } - } - return true - -} - -// IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid. -func IsUTFDigit(str string) bool { - if IsNull(str) { - return true - } - if strings.IndexAny(str, "+-") > 0 { - return false - } - if len(str) > 1 { - str = strings.TrimPrefix(str, "-") - str = strings.TrimPrefix(str, "+") - } - for _, c := range str { - if !unicode.IsDigit(c) { //digits && minus sign are ok - return false - } - } - return true - -} - -// IsHexadecimal checks if the string is a hexadecimal number. -func IsHexadecimal(str string) bool { - return rxHexadecimal.MatchString(str) -} - -// IsHexcolor checks if the string is a hexadecimal color. -func IsHexcolor(str string) bool { - return rxHexcolor.MatchString(str) -} - -// IsRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB). -func IsRGBcolor(str string) bool { - return rxRGBcolor.MatchString(str) -} - -// IsLowerCase checks if the string is lowercase. Empty string is valid. -func IsLowerCase(str string) bool { - if IsNull(str) { - return true - } - return str == strings.ToLower(str) -} - -// IsUpperCase checks if the string is uppercase. Empty string is valid. -func IsUpperCase(str string) bool { - if IsNull(str) { - return true - } - return str == strings.ToUpper(str) -} - -// HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid. -func HasLowerCase(str string) bool { - if IsNull(str) { - return true - } - return rxHasLowerCase.MatchString(str) -} - -// HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid. -func HasUpperCase(str string) bool { - if IsNull(str) { - return true - } - return rxHasUpperCase.MatchString(str) -} - -// IsInt checks if the string is an integer. Empty string is valid. -func IsInt(str string) bool { - if IsNull(str) { - return true - } - return rxInt.MatchString(str) -} - -// IsFloat checks if the string is a float. -func IsFloat(str string) bool { - return str != "" && rxFloat.MatchString(str) -} - -// IsDivisibleBy checks if the string is a number that's divisible by another. -// If second argument is not valid integer or zero, it's return false. -// Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). -func IsDivisibleBy(str, num string) bool { - f, _ := ToFloat(str) - p := int64(f) - q, _ := ToInt(num) - if q == 0 { - return false - } - return (p == 0) || (p%q == 0) -} - -// IsNull checks if the string is null. -func IsNull(str string) bool { - return len(str) == 0 -} - -// IsNotNull checks if the string is not null. -func IsNotNull(str string) bool { - return !IsNull(str) -} - -// HasWhitespaceOnly checks the string only contains whitespace -func HasWhitespaceOnly(str string) bool { - return len(str) > 0 && rxHasWhitespaceOnly.MatchString(str) -} - -// HasWhitespace checks if the string contains any whitespace -func HasWhitespace(str string) bool { - return len(str) > 0 && rxHasWhitespace.MatchString(str) -} - -// IsByteLength checks if the string's length (in bytes) falls in a range. -func IsByteLength(str string, min, max int) bool { - return len(str) >= min && len(str) <= max -} - -// IsUUIDv3 checks if the string is a UUID version 3. -func IsUUIDv3(str string) bool { - return rxUUID3.MatchString(str) -} - -// IsUUIDv4 checks if the string is a UUID version 4. -func IsUUIDv4(str string) bool { - return rxUUID4.MatchString(str) -} - -// IsUUIDv5 checks if the string is a UUID version 5. -func IsUUIDv5(str string) bool { - return rxUUID5.MatchString(str) -} - -// IsUUID checks if the string is a UUID (version 3, 4 or 5). -func IsUUID(str string) bool { - return rxUUID.MatchString(str) -} - -// Byte to index table for O(1) lookups when unmarshaling. -// We use 0xFF as sentinel value for invalid indexes. -var ulidDec = [...]byte{ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, - 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, - 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, - 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, - 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, - 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, - 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, - 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, -} - -// EncodedSize is the length of a text encoded ULID. -const ulidEncodedSize = 26 - -// IsULID checks if the string is a ULID. -// -// Implementation got from: -// https://github.com/oklog/ulid (Apache-2.0 License) -// -func IsULID(str string) bool { - // Check if a base32 encoded ULID is the right length. - if len(str) != ulidEncodedSize { - return false - } - - // Check if all the characters in a base32 encoded ULID are part of the - // expected base32 character set. - if ulidDec[str[0]] == 0xFF || - ulidDec[str[1]] == 0xFF || - ulidDec[str[2]] == 0xFF || - ulidDec[str[3]] == 0xFF || - ulidDec[str[4]] == 0xFF || - ulidDec[str[5]] == 0xFF || - ulidDec[str[6]] == 0xFF || - ulidDec[str[7]] == 0xFF || - ulidDec[str[8]] == 0xFF || - ulidDec[str[9]] == 0xFF || - ulidDec[str[10]] == 0xFF || - ulidDec[str[11]] == 0xFF || - ulidDec[str[12]] == 0xFF || - ulidDec[str[13]] == 0xFF || - ulidDec[str[14]] == 0xFF || - ulidDec[str[15]] == 0xFF || - ulidDec[str[16]] == 0xFF || - ulidDec[str[17]] == 0xFF || - ulidDec[str[18]] == 0xFF || - ulidDec[str[19]] == 0xFF || - ulidDec[str[20]] == 0xFF || - ulidDec[str[21]] == 0xFF || - ulidDec[str[22]] == 0xFF || - ulidDec[str[23]] == 0xFF || - ulidDec[str[24]] == 0xFF || - ulidDec[str[25]] == 0xFF { - return false - } - - // Check if the first character in a base32 encoded ULID will overflow. This - // happens because the base32 representation encodes 130 bits, while the - // ULID is only 128 bits. - // - // See https://github.com/oklog/ulid/issues/9 for details. - if str[0] > '7' { - return false - } - return true -} - -// IsCreditCard checks if the string is a credit card. -func IsCreditCard(str string) bool { - sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") - if !rxCreditCard.MatchString(sanitized) { - return false - } - var sum int64 - var digit string - var tmpNum int64 - var shouldDouble bool - for i := len(sanitized) - 1; i >= 0; i-- { - digit = sanitized[i:(i + 1)] - tmpNum, _ = ToInt(digit) - if shouldDouble { - tmpNum *= 2 - if tmpNum >= 10 { - sum += (tmpNum % 10) + 1 - } else { - sum += tmpNum - } - } else { - sum += tmpNum - } - shouldDouble = !shouldDouble - } - - return sum%10 == 0 -} - -// IsISBN10 checks if the string is an ISBN version 10. -func IsISBN10(str string) bool { - return IsISBN(str, 10) -} - -// IsISBN13 checks if the string is an ISBN version 13. -func IsISBN13(str string) bool { - return IsISBN(str, 13) -} - -// IsISBN checks if the string is an ISBN (version 10 or 13). -// If version value is not equal to 10 or 13, it will be checks both variants. -func IsISBN(str string, version int) bool { - sanitized := whiteSpacesAndMinus.ReplaceAllString(str, "") - var checksum int32 - var i int32 - if version == 10 { - if !rxISBN10.MatchString(sanitized) { - return false - } - for i = 0; i < 9; i++ { - checksum += (i + 1) * int32(sanitized[i]-'0') - } - if sanitized[9] == 'X' { - checksum += 10 * 10 - } else { - checksum += 10 * int32(sanitized[9]-'0') - } - if checksum%11 == 0 { - return true - } - return false - } else if version == 13 { - if !rxISBN13.MatchString(sanitized) { - return false - } - factor := []int32{1, 3} - for i = 0; i < 12; i++ { - checksum += factor[i%2] * int32(sanitized[i]-'0') - } - return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 - } - return IsISBN(str, 10) || IsISBN(str, 13) -} - -// IsJSON checks if the string is valid JSON (note: uses json.Unmarshal). -func IsJSON(str string) bool { - var js json.RawMessage - return json.Unmarshal([]byte(str), &js) == nil -} - -// IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid. -func IsMultibyte(str string) bool { - if IsNull(str) { - return true - } - return rxMultibyte.MatchString(str) -} - -// IsASCII checks if the string contains ASCII chars only. Empty string is valid. -func IsASCII(str string) bool { - if IsNull(str) { - return true - } - return rxASCII.MatchString(str) -} - -// IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid. -func IsPrintableASCII(str string) bool { - if IsNull(str) { - return true - } - return rxPrintableASCII.MatchString(str) -} - -// IsFullWidth checks if the string contains any full-width chars. Empty string is valid. -func IsFullWidth(str string) bool { - if IsNull(str) { - return true - } - return rxFullWidth.MatchString(str) -} - -// IsHalfWidth checks if the string contains any half-width chars. Empty string is valid. -func IsHalfWidth(str string) bool { - if IsNull(str) { - return true - } - return rxHalfWidth.MatchString(str) -} - -// IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid. -func IsVariableWidth(str string) bool { - if IsNull(str) { - return true - } - return rxHalfWidth.MatchString(str) && rxFullWidth.MatchString(str) -} - -// IsBase64 checks if a string is base64 encoded. -func IsBase64(str string) bool { - return rxBase64.MatchString(str) -} - -// IsFilePath checks is a string is Win or Unix file path and returns it's type. -func IsFilePath(str string) (bool, int) { - if rxWinPath.MatchString(str) { - //check windows path limit see: - // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath - if len(str[3:]) > 32767 { - return false, Win - } - return true, Win - } else if rxUnixPath.MatchString(str) { - return true, Unix - } - return false, Unknown -} - -//IsWinFilePath checks both relative & absolute paths in Windows -func IsWinFilePath(str string) bool { - if rxARWinPath.MatchString(str) { - //check windows path limit see: - // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath - if len(str[3:]) > 32767 { - return false - } - return true - } - return false -} - -//IsUnixFilePath checks both relative & absolute paths in Unix -func IsUnixFilePath(str string) bool { - if rxARUnixPath.MatchString(str) { - return true - } - return false -} - -// IsDataURI checks if a string is base64 encoded data URI such as an image -func IsDataURI(str string) bool { - dataURI := strings.Split(str, ",") - if !rxDataURI.MatchString(dataURI[0]) { - return false - } - return IsBase64(dataURI[1]) -} - -// IsMagnetURI checks if a string is valid magnet URI -func IsMagnetURI(str string) bool { - return rxMagnetURI.MatchString(str) -} - -// IsISO3166Alpha2 checks if a string is valid two-letter country code -func IsISO3166Alpha2(str string) bool { - for _, entry := range ISO3166List { - if str == entry.Alpha2Code { - return true - } - } - return false -} - -// IsISO3166Alpha3 checks if a string is valid three-letter country code -func IsISO3166Alpha3(str string) bool { - for _, entry := range ISO3166List { - if str == entry.Alpha3Code { - return true - } - } - return false -} - -// IsISO693Alpha2 checks if a string is valid two-letter language code -func IsISO693Alpha2(str string) bool { - for _, entry := range ISO693List { - if str == entry.Alpha2Code { - return true - } - } - return false -} - -// IsISO693Alpha3b checks if a string is valid three-letter language code -func IsISO693Alpha3b(str string) bool { - for _, entry := range ISO693List { - if str == entry.Alpha3bCode { - return true - } - } - return false -} - -// IsDNSName will validate the given string as a DNS name -func IsDNSName(str string) bool { - if str == "" || len(strings.Replace(str, ".", "", -1)) > 255 { - // constraints already violated - return false - } - return !IsIP(str) && rxDNSName.MatchString(str) -} - -// IsHash checks if a string is a hash of type algorithm. -// Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] -func IsHash(str string, algorithm string) bool { - var len string - algo := strings.ToLower(algorithm) - - if algo == "crc32" || algo == "crc32b" { - len = "8" - } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" { - len = "32" - } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" { - len = "40" - } else if algo == "tiger192" { - len = "48" - } else if algo == "sha3-224" { - len = "56" - } else if algo == "sha256" || algo == "sha3-256" { - len = "64" - } else if algo == "sha384" || algo == "sha3-384" { - len = "96" - } else if algo == "sha512" || algo == "sha3-512" { - len = "128" - } else { - return false - } - - return Matches(str, "^[a-f0-9]{"+len+"}$") -} - -// IsSHA3224 checks is a string is a SHA3-224 hash. Alias for `IsHash(str, "sha3-224")` -func IsSHA3224(str string) bool { - return IsHash(str, "sha3-224") -} - -// IsSHA3256 checks is a string is a SHA3-256 hash. Alias for `IsHash(str, "sha3-256")` -func IsSHA3256(str string) bool { - return IsHash(str, "sha3-256") -} - -// IsSHA3384 checks is a string is a SHA3-384 hash. Alias for `IsHash(str, "sha3-384")` -func IsSHA3384(str string) bool { - return IsHash(str, "sha3-384") -} - -// IsSHA3512 checks is a string is a SHA3-512 hash. Alias for `IsHash(str, "sha3-512")` -func IsSHA3512(str string) bool { - return IsHash(str, "sha3-512") -} - -// IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")` -func IsSHA512(str string) bool { - return IsHash(str, "sha512") -} - -// IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")` -func IsSHA384(str string) bool { - return IsHash(str, "sha384") -} - -// IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")` -func IsSHA256(str string) bool { - return IsHash(str, "sha256") -} - -// IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")` -func IsTiger192(str string) bool { - return IsHash(str, "tiger192") -} - -// IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")` -func IsTiger160(str string) bool { - return IsHash(str, "tiger160") -} - -// IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")` -func IsRipeMD160(str string) bool { - return IsHash(str, "ripemd160") -} - -// IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")` -func IsSHA1(str string) bool { - return IsHash(str, "sha1") -} - -// IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")` -func IsTiger128(str string) bool { - return IsHash(str, "tiger128") -} - -// IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")` -func IsRipeMD128(str string) bool { - return IsHash(str, "ripemd128") -} - -// IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")` -func IsCRC32(str string) bool { - return IsHash(str, "crc32") -} - -// IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")` -func IsCRC32b(str string) bool { - return IsHash(str, "crc32b") -} - -// IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")` -func IsMD5(str string) bool { - return IsHash(str, "md5") -} - -// IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")` -func IsMD4(str string) bool { - return IsHash(str, "md4") -} - -// IsDialString validates the given string for usage with the various Dial() functions -func IsDialString(str string) bool { - if h, p, err := net.SplitHostPort(str); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) { - return true - } - - return false -} - -// IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP` -func IsIP(str string) bool { - return net.ParseIP(str) != nil -} - -// IsPort checks if a string represents a valid port -func IsPort(str string) bool { - if i, err := strconv.Atoi(str); err == nil && i > 0 && i < 65536 { - return true - } - return false -} - -// IsIPv4 checks if the string is an IP version 4. -func IsIPv4(str string) bool { - ip := net.ParseIP(str) - return ip != nil && strings.Contains(str, ".") -} - -// IsIPv6 checks if the string is an IP version 6. -func IsIPv6(str string) bool { - ip := net.ParseIP(str) - return ip != nil && strings.Contains(str, ":") -} - -// IsCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6) -func IsCIDR(str string) bool { - _, _, err := net.ParseCIDR(str) - return err == nil -} - -// IsMAC checks if a string is valid MAC address. -// Possible MAC formats: -// 01:23:45:67:89:ab -// 01:23:45:67:89:ab:cd:ef -// 01-23-45-67-89-ab -// 01-23-45-67-89-ab-cd-ef -// 0123.4567.89ab -// 0123.4567.89ab.cdef -func IsMAC(str string) bool { - _, err := net.ParseMAC(str) - return err == nil -} - -// IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name -func IsHost(str string) bool { - return IsIP(str) || IsDNSName(str) -} - -// IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. -func IsMongoID(str string) bool { - return rxHexadecimal.MatchString(str) && (len(str) == 24) -} - -// IsLatitude checks if a string is valid latitude. -func IsLatitude(str string) bool { - return rxLatitude.MatchString(str) -} - -// IsLongitude checks if a string is valid longitude. -func IsLongitude(str string) bool { - return rxLongitude.MatchString(str) -} - -// IsIMEI checks if a string is valid IMEI -func IsIMEI(str string) bool { - return rxIMEI.MatchString(str) -} - -// IsIMSI checks if a string is valid IMSI -func IsIMSI(str string) bool { - if !rxIMSI.MatchString(str) { - return false - } - - mcc, err := strconv.ParseInt(str[0:3], 10, 32) - if err != nil { - return false - } - - switch mcc { - case 202, 204, 206, 208, 212, 213, 214, 216, 218, 219: - case 220, 221, 222, 226, 228, 230, 231, 232, 234, 235: - case 238, 240, 242, 244, 246, 247, 248, 250, 255, 257: - case 259, 260, 262, 266, 268, 270, 272, 274, 276, 278: - case 280, 282, 283, 284, 286, 288, 289, 290, 292, 293: - case 294, 295, 297, 302, 308, 310, 311, 312, 313, 314: - case 315, 316, 330, 332, 334, 338, 340, 342, 344, 346: - case 348, 350, 352, 354, 356, 358, 360, 362, 363, 364: - case 365, 366, 368, 370, 372, 374, 376, 400, 401, 402: - case 404, 405, 406, 410, 412, 413, 414, 415, 416, 417: - case 418, 419, 420, 421, 422, 424, 425, 426, 427, 428: - case 429, 430, 431, 432, 434, 436, 437, 438, 440, 441: - case 450, 452, 454, 455, 456, 457, 460, 461, 466, 467: - case 470, 472, 502, 505, 510, 514, 515, 520, 525, 528: - case 530, 536, 537, 539, 540, 541, 542, 543, 544, 545: - case 546, 547, 548, 549, 550, 551, 552, 553, 554, 555: - case 602, 603, 604, 605, 606, 607, 608, 609, 610, 611: - case 612, 613, 614, 615, 616, 617, 618, 619, 620, 621: - case 622, 623, 624, 625, 626, 627, 628, 629, 630, 631: - case 632, 633, 634, 635, 636, 637, 638, 639, 640, 641: - case 642, 643, 645, 646, 647, 648, 649, 650, 651, 652: - case 653, 654, 655, 657, 658, 659, 702, 704, 706, 708: - case 710, 712, 714, 716, 722, 724, 730, 732, 734, 736: - case 738, 740, 742, 744, 746, 748, 750, 995: - return true - default: - return false - } - return true -} - -// IsRsaPublicKey checks if a string is valid public key with provided length -func IsRsaPublicKey(str string, keylen int) bool { - bb := bytes.NewBufferString(str) - pemBytes, err := ioutil.ReadAll(bb) - if err != nil { - return false - } - block, _ := pem.Decode(pemBytes) - if block != nil && block.Type != "PUBLIC KEY" { - return false - } - var der []byte - - if block != nil { - der = block.Bytes - } else { - der, err = base64.StdEncoding.DecodeString(str) - if err != nil { - return false - } - } - - key, err := x509.ParsePKIXPublicKey(der) - if err != nil { - return false - } - pubkey, ok := key.(*rsa.PublicKey) - if !ok { - return false - } - bitlen := len(pubkey.N.Bytes()) * 8 - return bitlen == int(keylen) -} - -// IsRegex checks if a give string is a valid regex with RE2 syntax or not -func IsRegex(str string) bool { - if _, err := regexp.Compile(str); err == nil { - return true - } - return false -} - -func toJSONName(tag string) string { - if tag == "" { - return "" - } - - // JSON name always comes first. If there's no options then split[0] is - // JSON name, if JSON name is not set, then split[0] is an empty string. - split := strings.SplitN(tag, ",", 2) - - name := split[0] - - // However it is possible that the field is skipped when - // (de-)serializing from/to JSON, in which case assume that there is no - // tag name to use - if name == "-" { - return "" - } - return name -} - -func prependPathToErrors(err error, path string) error { - switch err2 := err.(type) { - case Error: - err2.Path = append([]string{path}, err2.Path...) - return err2 - case Errors: - errors := err2.Errors() - for i, err3 := range errors { - errors[i] = prependPathToErrors(err3, path) - } - return err2 - } - return err -} - -// ValidateArray performs validation according to condition iterator that validates every element of the array -func ValidateArray(array []interface{}, iterator ConditionIterator) bool { - return Every(array, iterator) -} - -// ValidateMap use validation map for fields. -// result will be equal to `false` if there are any errors. -// s is the map containing the data to be validated. -// m is the validation map in the form: -// map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}} -func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error) { - if s == nil { - return true, nil - } - result := true - var err error - var errs Errors - var index int - val := reflect.ValueOf(s) - for key, value := range s { - presentResult := true - validator, ok := m[key] - if !ok { - presentResult = false - var err error - err = fmt.Errorf("all map keys has to be present in the validation map; got %s", key) - err = prependPathToErrors(err, key) - errs = append(errs, err) - } - valueField := reflect.ValueOf(value) - mapResult := true - typeResult := true - structResult := true - resultField := true - switch subValidator := validator.(type) { - case map[string]interface{}: - var err error - if v, ok := value.(map[string]interface{}); !ok { - mapResult = false - err = fmt.Errorf("map validator has to be for the map type only; got %s", valueField.Type().String()) - err = prependPathToErrors(err, key) - errs = append(errs, err) - } else { - mapResult, err = ValidateMap(v, subValidator) - if err != nil { - mapResult = false - err = prependPathToErrors(err, key) - errs = append(errs, err) - } - } - case string: - if (valueField.Kind() == reflect.Struct || - (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && - subValidator != "-" { - var err error - structResult, err = ValidateStruct(valueField.Interface()) - if err != nil { - err = prependPathToErrors(err, key) - errs = append(errs, err) - } - } - resultField, err = typeCheck(valueField, reflect.StructField{ - Name: key, - PkgPath: "", - Type: val.Type(), - Tag: reflect.StructTag(fmt.Sprintf("%s:%q", tagName, subValidator)), - Offset: 0, - Index: []int{index}, - Anonymous: false, - }, val, nil) - if err != nil { - errs = append(errs, err) - } - case nil: - // already handlerd when checked before - default: - typeResult = false - err = fmt.Errorf("map validator has to be either map[string]interface{} or string; got %s", valueField.Type().String()) - err = prependPathToErrors(err, key) - errs = append(errs, err) - } - result = result && presentResult && typeResult && resultField && structResult && mapResult - index++ - } - // checks required keys - requiredResult := true - for key, value := range m { - if schema, ok := value.(string); ok { - tags := parseTagIntoMap(schema) - if required, ok := tags["required"]; ok { - if _, ok := s[key]; !ok { - requiredResult = false - if required.customErrorMessage != "" { - err = Error{key, fmt.Errorf(required.customErrorMessage), true, "required", []string{}} - } else { - err = Error{key, fmt.Errorf("required field missing"), false, "required", []string{}} - } - errs = append(errs, err) - } - } - } - } - - if len(errs) > 0 { - err = errs - } - return result && requiredResult, err -} - -// ValidateStruct use tags for fields. -// result will be equal to `false` if there are any errors. -// todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail) -func ValidateStruct(s interface{}) (bool, error) { - if s == nil { - return true, nil - } - result := true - var err error - val := reflect.ValueOf(s) - if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { - val = val.Elem() - } - // we only accept structs - if val.Kind() != reflect.Struct { - return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) - } - var errs Errors - for i := 0; i < val.NumField(); i++ { - valueField := val.Field(i) - typeField := val.Type().Field(i) - if typeField.PkgPath != "" { - continue // Private field - } - structResult := true - if valueField.Kind() == reflect.Interface { - valueField = valueField.Elem() - } - if (valueField.Kind() == reflect.Struct || - (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && - typeField.Tag.Get(tagName) != "-" { - var err error - structResult, err = ValidateStruct(valueField.Interface()) - if err != nil { - err = prependPathToErrors(err, typeField.Name) - errs = append(errs, err) - } - } - resultField, err2 := typeCheck(valueField, typeField, val, nil) - if err2 != nil { - - // Replace structure name with JSON name if there is a tag on the variable - jsonTag := toJSONName(typeField.Tag.Get("json")) - if jsonTag != "" { - switch jsonError := err2.(type) { - case Error: - jsonError.Name = jsonTag - err2 = jsonError - case Errors: - for i2, err3 := range jsonError { - switch customErr := err3.(type) { - case Error: - customErr.Name = jsonTag - jsonError[i2] = customErr - } - } - - err2 = jsonError - } - } - - errs = append(errs, err2) - } - result = result && resultField && structResult - } - if len(errs) > 0 { - err = errs - } - return result, err -} - -// ValidateStructAsync performs async validation of the struct and returns results through the channels -func ValidateStructAsync(s interface{}) (<-chan bool, <-chan error) { - res := make(chan bool) - errors := make(chan error) - - go func() { - defer close(res) - defer close(errors) - - isValid, isFailed := ValidateStruct(s) - - res <- isValid - errors <- isFailed - }() - - return res, errors -} - -// ValidateMapAsync performs async validation of the map and returns results through the channels -func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error) { - res := make(chan bool) - errors := make(chan error) - - go func() { - defer close(res) - defer close(errors) - - isValid, isFailed := ValidateMap(s, m) - - res <- isValid - errors <- isFailed - }() - - return res, errors -} - -// parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} -func parseTagIntoMap(tag string) tagOptionsMap { - optionsMap := make(tagOptionsMap) - options := strings.Split(tag, ",") - - for i, option := range options { - option = strings.TrimSpace(option) - - validationOptions := strings.Split(option, "~") - if !isValidTag(validationOptions[0]) { - continue - } - if len(validationOptions) == 2 { - optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i} - } else { - optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i} - } - } - return optionsMap -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -// IsSSN will validate the given string as a U.S. Social Security Number -func IsSSN(str string) bool { - if str == "" || len(str) != 11 { - return false - } - return rxSSN.MatchString(str) -} - -// IsSemver checks if string is valid semantic version -func IsSemver(str string) bool { - return rxSemver.MatchString(str) -} - -// IsType checks if interface is of some type -func IsType(v interface{}, params ...string) bool { - if len(params) == 1 { - typ := params[0] - return strings.Replace(reflect.TypeOf(v).String(), " ", "", -1) == strings.Replace(typ, " ", "", -1) - } - return false -} - -// IsTime checks if string is valid according to given format -func IsTime(str string, format string) bool { - _, err := time.Parse(format, str) - return err == nil -} - -// IsUnixTime checks if string is valid unix timestamp value -func IsUnixTime(str string) bool { - if _, err := strconv.Atoi(str); err == nil { - return true - } - return false -} - -// IsRFC3339 checks if string is valid timestamp value according to RFC3339 -func IsRFC3339(str string) bool { - return IsTime(str, time.RFC3339) -} - -// IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone. -func IsRFC3339WithoutZone(str string) bool { - return IsTime(str, rfc3339WithoutZone) -} - -// IsISO4217 checks if string is valid ISO currency code -func IsISO4217(str string) bool { - for _, currency := range ISO4217List { - if str == currency { - return true - } - } - - return false -} - -// ByteLength checks string's length -func ByteLength(str string, params ...string) bool { - if len(params) == 2 { - min, _ := ToInt(params[0]) - max, _ := ToInt(params[1]) - return len(str) >= int(min) && len(str) <= int(max) - } - - return false -} - -// RuneLength checks string's length -// Alias for StringLength -func RuneLength(str string, params ...string) bool { - return StringLength(str, params...) -} - -// IsRsaPub checks whether string is valid RSA key -// Alias for IsRsaPublicKey -func IsRsaPub(str string, params ...string) bool { - if len(params) == 1 { - len, _ := ToInt(params[0]) - return IsRsaPublicKey(str, int(len)) - } - - return false -} - -// StringMatches checks if a string matches a given pattern. -func StringMatches(s string, params ...string) bool { - if len(params) == 1 { - pattern := params[0] - return Matches(s, pattern) - } - return false -} - -// StringLength checks string's length (including multi byte strings) -func StringLength(str string, params ...string) bool { - - if len(params) == 2 { - strLength := utf8.RuneCountInString(str) - min, _ := ToInt(params[0]) - max, _ := ToInt(params[1]) - return strLength >= int(min) && strLength <= int(max) - } - - return false -} - -// MinStringLength checks string's minimum length (including multi byte strings) -func MinStringLength(str string, params ...string) bool { - - if len(params) == 1 { - strLength := utf8.RuneCountInString(str) - min, _ := ToInt(params[0]) - return strLength >= int(min) - } - - return false -} - -// MaxStringLength checks string's maximum length (including multi byte strings) -func MaxStringLength(str string, params ...string) bool { - - if len(params) == 1 { - strLength := utf8.RuneCountInString(str) - max, _ := ToInt(params[0]) - return strLength <= int(max) - } - - return false -} - -// Range checks string's length -func Range(str string, params ...string) bool { - if len(params) == 2 { - value, _ := ToFloat(str) - min, _ := ToFloat(params[0]) - max, _ := ToFloat(params[1]) - return InRange(value, min, max) - } - - return false -} - -// IsInRaw checks if string is in list of allowed values -func IsInRaw(str string, params ...string) bool { - if len(params) == 1 { - rawParams := params[0] - - parsedParams := strings.Split(rawParams, "|") - - return IsIn(str, parsedParams...) - } - - return false -} - -// IsIn checks if string str is a member of the set of strings params -func IsIn(str string, params ...string) bool { - for _, param := range params { - if str == param { - return true - } - } - - return false -} - -func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) { - if nilPtrAllowedByRequired { - k := v.Kind() - if (k == reflect.Ptr || k == reflect.Interface) && v.IsNil() { - return true, nil - } - } - - if requiredOption, isRequired := options["required"]; isRequired { - if len(requiredOption.customErrorMessage) > 0 { - return false, Error{t.Name, fmt.Errorf(requiredOption.customErrorMessage), true, "required", []string{}} - } - return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required", []string{}} - } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional { - return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required", []string{}} - } - // not required and empty is valid - return true, nil -} - -func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) { - if !v.IsValid() { - return false, nil - } - - tag := t.Tag.Get(tagName) - - // checks if the field should be ignored - switch tag { - case "": - if v.Kind() != reflect.Slice && v.Kind() != reflect.Map { - if !fieldsRequiredByDefault { - return true, nil - } - return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required", []string{}} - } - case "-": - return true, nil - } - - isRootType := false - if options == nil { - isRootType = true - options = parseTagIntoMap(tag) - } - - if isEmptyValue(v) { - // an empty value is not validated, checks only required - isValid, resultErr = checkRequired(v, t, options) - for key := range options { - delete(options, key) - } - return isValid, resultErr - } - - var customTypeErrors Errors - optionsOrder := options.orderedKeys() - for _, validatorName := range optionsOrder { - validatorStruct := options[validatorName] - if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok { - delete(options, validatorName) - - if result := validatefunc(v.Interface(), o.Interface()); !result { - if len(validatorStruct.customErrorMessage) > 0 { - customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: TruncatingErrorf(validatorStruct.customErrorMessage, fmt.Sprint(v), validatorName), CustomErrorMessageExists: true, Validator: stripParams(validatorName)}) - continue - } - customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)}) - } - } - } - - if len(customTypeErrors.Errors()) > 0 { - return false, customTypeErrors - } - - if isRootType { - // Ensure that we've checked the value by all specified validators before report that the value is valid - defer func() { - delete(options, "optional") - delete(options, "required") - - if isValid && resultErr == nil && len(options) != 0 { - optionsOrder := options.orderedKeys() - for _, validator := range optionsOrder { - isValid = false - resultErr = Error{t.Name, fmt.Errorf( - "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator), []string{}} - return - } - } - }() - } - - for _, validatorSpec := range optionsOrder { - validatorStruct := options[validatorSpec] - var negate bool - validator := validatorSpec - customMsgExists := len(validatorStruct.customErrorMessage) > 0 - - // checks whether the tag looks like '!something' or 'something' - if validator[0] == '!' { - validator = validator[1:] - negate = true - } - - // checks for interface param validators - for key, value := range InterfaceParamTagRegexMap { - ps := value.FindStringSubmatch(validator) - if len(ps) == 0 { - continue - } - - validatefunc, ok := InterfaceParamTagMap[key] - if !ok { - continue - } - - delete(options, validatorSpec) - - field := fmt.Sprint(v) - if result := validatefunc(v.Interface(), ps[1:]...); (!result && !negate) || (result && negate) { - if customMsgExists { - return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - } - } - - switch v.Kind() { - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, - reflect.Float32, reflect.Float64, - reflect.String: - // for each tag option checks the map of validator functions - for _, validatorSpec := range optionsOrder { - validatorStruct := options[validatorSpec] - var negate bool - validator := validatorSpec - customMsgExists := len(validatorStruct.customErrorMessage) > 0 - - // checks whether the tag looks like '!something' or 'something' - if validator[0] == '!' { - validator = validator[1:] - negate = true - } - - // checks for param validators - for key, value := range ParamTagRegexMap { - ps := value.FindStringSubmatch(validator) - if len(ps) == 0 { - continue - } - - validatefunc, ok := ParamTagMap[key] - if !ok { - continue - } - - delete(options, validatorSpec) - - switch v.Kind() { - case reflect.String, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - - field := fmt.Sprint(v) // make value into string, then validate with regex - if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) { - if customMsgExists { - return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - default: - // type not yet supported, fail - return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec), []string{}} - } - } - - if validatefunc, ok := TagMap[validator]; ok { - delete(options, validatorSpec) - - switch v.Kind() { - case reflect.String, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - field := fmt.Sprint(v) // make value into string, then validate with regex - if result := validatefunc(field); !result && !negate || result && negate { - if customMsgExists { - return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - if negate { - return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} - } - default: - //Not Yet Supported Types (Fail here!) - err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v) - return false, Error{t.Name, err, false, stripParams(validatorSpec), []string{}} - } - } - } - return true, nil - case reflect.Map: - if v.Type().Key().Kind() != reflect.String { - return false, &UnsupportedTypeError{v.Type()} - } - var sv stringValues - sv = v.MapKeys() - sort.Sort(sv) - result := true - for i, k := range sv { - var resultItem bool - var err error - if v.MapIndex(k).Kind() != reflect.Struct { - resultItem, err = typeCheck(v.MapIndex(k), t, o, options) - if err != nil { - return false, err - } - } else { - resultItem, err = ValidateStruct(v.MapIndex(k).Interface()) - if err != nil { - err = prependPathToErrors(err, t.Name+"."+sv[i].Interface().(string)) - return false, err - } - } - result = result && resultItem - } - return result, nil - case reflect.Slice, reflect.Array: - result := true - for i := 0; i < v.Len(); i++ { - var resultItem bool - var err error - if v.Index(i).Kind() != reflect.Struct { - resultItem, err = typeCheck(v.Index(i), t, o, options) - if err != nil { - return false, err - } - } else { - resultItem, err = ValidateStruct(v.Index(i).Interface()) - if err != nil { - err = prependPathToErrors(err, t.Name+"."+strconv.Itoa(i)) - return false, err - } - } - result = result && resultItem - } - return result, nil - case reflect.Interface: - // If the value is an interface then encode its element - if v.IsNil() { - return true, nil - } - return ValidateStruct(v.Interface()) - case reflect.Ptr: - // If the value is a pointer then checks its element - if v.IsNil() { - return true, nil - } - return typeCheck(v.Elem(), t, o, options) - case reflect.Struct: - return true, nil - default: - return false, &UnsupportedTypeError{v.Type()} - } -} - -func stripParams(validatorString string) string { - return paramsRegexp.ReplaceAllString(validatorString, "") -} - -// isEmptyValue checks whether value empty or not -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.String, reflect.Array: - return v.Len() == 0 - case reflect.Map, reflect.Slice: - return v.Len() == 0 || v.IsNil() - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) -} - -// ErrorByField returns error for specified field of the struct -// validated by ValidateStruct or empty string if there are no errors -// or this field doesn't exists or doesn't have any errors. -func ErrorByField(e error, field string) string { - if e == nil { - return "" - } - return ErrorsByField(e)[field] -} - -// ErrorsByField returns map of errors of the struct validated -// by ValidateStruct or empty map if there are no errors. -func ErrorsByField(e error) map[string]string { - m := make(map[string]string) - if e == nil { - return m - } - // prototype for ValidateStruct - - switch e := e.(type) { - case Error: - m[e.Name] = e.Err.Error() - case Errors: - for _, item := range e.Errors() { - n := ErrorsByField(item) - for k, v := range n { - m[k] = v - } - } - } - - return m -} - -// Error returns string equivalent for reflect.Type -func (e *UnsupportedTypeError) Error() string { - return "validator: unsupported type: " + e.Type.String() -} - -func (sv stringValues) Len() int { return len(sv) } -func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } -func (sv stringValues) get(i int) string { return sv[i].String() } - -func IsE164(str string) bool { - return rxE164.MatchString(str) -} diff --git a/vendor/github.com/asaskevich/govalidator/wercker.yml b/vendor/github.com/asaskevich/govalidator/wercker.yml deleted file mode 100644 index bc5f7b0..0000000 --- a/vendor/github.com/asaskevich/govalidator/wercker.yml +++ /dev/null @@ -1,15 +0,0 @@ -box: golang -build: - steps: - - setup-go-workspace - - - script: - name: go get - code: | - go version - go get -t ./... - - - script: - name: go test - code: | - go test -race -v ./... diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE deleted file mode 100644 index bc52e96..0000000 --- a/vendor/github.com/davecgh/go-spew/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2012-2016 Dave Collins - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go deleted file mode 100644 index 7929947..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// Go versions prior to 1.4 are disabled because they use a different layout -// for interfaces which make the implementation of unsafeReflectValue more complex. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -package spew - -import ( - "reflect" - "unsafe" -) - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = false - - // ptrSize is the size of a pointer on the current arch. - ptrSize = unsafe.Sizeof((*byte)(nil)) -) - -type flag uintptr - -var ( - // flagRO indicates whether the value field of a reflect.Value - // is read-only. - flagRO flag - - // flagAddr indicates whether the address of the reflect.Value's - // value may be taken. - flagAddr flag -) - -// flagKindMask holds the bits that make up the kind -// part of the flags field. In all the supported versions, -// it is in the lower 5 bits. -const flagKindMask = flag(0x1f) - -// Different versions of Go have used different -// bit layouts for the flags type. This table -// records the known combinations. -var okFlags = []struct { - ro, addr flag -}{{ - // From Go 1.4 to 1.5 - ro: 1 << 5, - addr: 1 << 7, -}, { - // Up to Go tip. - ro: 1<<5 | 1<<6, - addr: 1 << 8, -}} - -var flagValOffset = func() uintptr { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - return field.Offset -}() - -// flagField returns a pointer to the flag field of a reflect.Value. -func flagField(v *reflect.Value) *flag { - return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) -} - -// unsafeReflectValue converts the passed reflect.Value into a one that bypasses -// the typical safety restrictions preventing access to unaddressable and -// unexported data. It works by digging the raw pointer to the underlying -// value out of the protected value and generating a new unprotected (unsafe) -// reflect.Value to it. -// -// This allows us to check for implementations of the Stringer and error -// interfaces to be used for pretty printing ordinarily unaddressable and -// inaccessible values such as unexported struct fields. -func unsafeReflectValue(v reflect.Value) reflect.Value { - if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { - return v - } - flagFieldPtr := flagField(&v) - *flagFieldPtr &^= flagRO - *flagFieldPtr |= flagAddr - return v -} - -// Sanity checks against future reflect package changes -// to the type or semantics of the Value.flag field. -func init() { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { - panic("reflect.Value flag field has changed kind") - } - type t0 int - var t struct { - A t0 - // t0 will have flagEmbedRO set. - t0 - // a will have flagStickyRO set - a t0 - } - vA := reflect.ValueOf(t).FieldByName("A") - va := reflect.ValueOf(t).FieldByName("a") - vt0 := reflect.ValueOf(t).FieldByName("t0") - - // Infer flagRO from the difference between the flags - // for the (otherwise identical) fields in t. - flagPublic := *flagField(&vA) - flagWithRO := *flagField(&va) | *flagField(&vt0) - flagRO = flagPublic ^ flagWithRO - - // Infer flagAddr from the difference between a value - // taken from a pointer and not. - vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") - flagNoPtr := *flagField(&vA) - flagPtr := *flagField(&vPtrA) - flagAddr = flagNoPtr ^ flagPtr - - // Check that the inferred flags tally with one of the known versions. - for _, f := range okFlags { - if flagRO == f.ro && flagAddr == f.addr { - return - } - } - panic("reflect.Value read-only flag has changed semantics") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go deleted file mode 100644 index 205c28d..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is running on Google App Engine, compiled by GopherJS, or -// "-tags safe" is added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build js appengine safe disableunsafe !go1.4 - -package spew - -import "reflect" - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = true -) - -// unsafeReflectValue typically converts the passed reflect.Value into a one -// that bypasses the typical safety restrictions preventing access to -// unaddressable and unexported data. However, doing this relies on access to -// the unsafe package. This is a stub version which simply returns the passed -// reflect.Value when the unsafe package is not available. -func unsafeReflectValue(v reflect.Value) reflect.Value { - return v -} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go deleted file mode 100644 index 1be8ce9..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "reflect" - "sort" - "strconv" -) - -// Some constants in the form of bytes to avoid string overhead. This mirrors -// the technique used in the fmt package. -var ( - panicBytes = []byte("(PANIC=") - plusBytes = []byte("+") - iBytes = []byte("i") - trueBytes = []byte("true") - falseBytes = []byte("false") - interfaceBytes = []byte("(interface {})") - commaNewlineBytes = []byte(",\n") - newlineBytes = []byte("\n") - openBraceBytes = []byte("{") - openBraceNewlineBytes = []byte("{\n") - closeBraceBytes = []byte("}") - asteriskBytes = []byte("*") - colonBytes = []byte(":") - colonSpaceBytes = []byte(": ") - openParenBytes = []byte("(") - closeParenBytes = []byte(")") - spaceBytes = []byte(" ") - pointerChainBytes = []byte("->") - nilAngleBytes = []byte("") - maxNewlineBytes = []byte("\n") - maxShortBytes = []byte("") - circularBytes = []byte("") - circularShortBytes = []byte("") - invalidAngleBytes = []byte("") - openBracketBytes = []byte("[") - closeBracketBytes = []byte("]") - percentBytes = []byte("%") - precisionBytes = []byte(".") - openAngleBytes = []byte("<") - closeAngleBytes = []byte(">") - openMapBytes = []byte("map[") - closeMapBytes = []byte("]") - lenEqualsBytes = []byte("len=") - capEqualsBytes = []byte("cap=") -) - -// hexDigits is used to map a decimal value to a hex digit. -var hexDigits = "0123456789abcdef" - -// catchPanic handles any panics that might occur during the handleMethods -// calls. -func catchPanic(w io.Writer, v reflect.Value) { - if err := recover(); err != nil { - w.Write(panicBytes) - fmt.Fprintf(w, "%v", err) - w.Write(closeParenBytes) - } -} - -// handleMethods attempts to call the Error and String methods on the underlying -// type the passed reflect.Value represents and outputes the result to Writer w. -// -// It handles panics in any called methods by catching and displaying the error -// as the formatted value. -func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { - // We need an interface to check if the type implements the error or - // Stringer interface. However, the reflect package won't give us an - // interface on certain things like unexported struct fields in order - // to enforce visibility rules. We use unsafe, when it's available, - // to bypass these restrictions since this package does not mutate the - // values. - if !v.CanInterface() { - if UnsafeDisabled { - return false - } - - v = unsafeReflectValue(v) - } - - // Choose whether or not to do error and Stringer interface lookups against - // the base type or a pointer to the base type depending on settings. - // Technically calling one of these methods with a pointer receiver can - // mutate the value, however, types which choose to satisify an error or - // Stringer interface with a pointer receiver should not be mutating their - // state inside these interface methods. - if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { - v = unsafeReflectValue(v) - } - if v.CanAddr() { - v = v.Addr() - } - - // Is it an error or Stringer? - switch iface := v.Interface().(type) { - case error: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.Error())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - - w.Write([]byte(iface.Error())) - return true - - case fmt.Stringer: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.String())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - w.Write([]byte(iface.String())) - return true - } - return false -} - -// printBool outputs a boolean value as true or false to Writer w. -func printBool(w io.Writer, val bool) { - if val { - w.Write(trueBytes) - } else { - w.Write(falseBytes) - } -} - -// printInt outputs a signed integer value to Writer w. -func printInt(w io.Writer, val int64, base int) { - w.Write([]byte(strconv.FormatInt(val, base))) -} - -// printUint outputs an unsigned integer value to Writer w. -func printUint(w io.Writer, val uint64, base int) { - w.Write([]byte(strconv.FormatUint(val, base))) -} - -// printFloat outputs a floating point value using the specified precision, -// which is expected to be 32 or 64bit, to Writer w. -func printFloat(w io.Writer, val float64, precision int) { - w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) -} - -// printComplex outputs a complex value using the specified float precision -// for the real and imaginary parts to Writer w. -func printComplex(w io.Writer, c complex128, floatPrecision int) { - r := real(c) - w.Write(openParenBytes) - w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) - i := imag(c) - if i >= 0 { - w.Write(plusBytes) - } - w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) - w.Write(iBytes) - w.Write(closeParenBytes) -} - -// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' -// prefix to Writer w. -func printHexPtr(w io.Writer, p uintptr) { - // Null pointer. - num := uint64(p) - if num == 0 { - w.Write(nilAngleBytes) - return - } - - // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix - buf := make([]byte, 18) - - // It's simpler to construct the hex string right to left. - base := uint64(16) - i := len(buf) - 1 - for num >= base { - buf[i] = hexDigits[num%base] - num /= base - i-- - } - buf[i] = hexDigits[num] - - // Add '0x' prefix. - i-- - buf[i] = 'x' - i-- - buf[i] = '0' - - // Strip unused leading bytes. - buf = buf[i:] - w.Write(buf) -} - -// valuesSorter implements sort.Interface to allow a slice of reflect.Value -// elements to be sorted. -type valuesSorter struct { - values []reflect.Value - strings []string // either nil or same len and values - cs *ConfigState -} - -// newValuesSorter initializes a valuesSorter instance, which holds a set of -// surrogate keys on which the data should be sorted. It uses flags in -// ConfigState to decide if and how to populate those surrogate keys. -func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { - vs := &valuesSorter{values: values, cs: cs} - if canSortSimply(vs.values[0].Kind()) { - return vs - } - if !cs.DisableMethods { - vs.strings = make([]string, len(values)) - for i := range vs.values { - b := bytes.Buffer{} - if !handleMethods(cs, &b, vs.values[i]) { - vs.strings = nil - break - } - vs.strings[i] = b.String() - } - } - if vs.strings == nil && cs.SpewKeys { - vs.strings = make([]string, len(values)) - for i := range vs.values { - vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) - } - } - return vs -} - -// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted -// directly, or whether it should be considered for sorting by surrogate keys -// (if the ConfigState allows it). -func canSortSimply(kind reflect.Kind) bool { - // This switch parallels valueSortLess, except for the default case. - switch kind { - case reflect.Bool: - return true - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return true - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return true - case reflect.Float32, reflect.Float64: - return true - case reflect.String: - return true - case reflect.Uintptr: - return true - case reflect.Array: - return true - } - return false -} - -// Len returns the number of values in the slice. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Len() int { - return len(s.values) -} - -// Swap swaps the values at the passed indices. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Swap(i, j int) { - s.values[i], s.values[j] = s.values[j], s.values[i] - if s.strings != nil { - s.strings[i], s.strings[j] = s.strings[j], s.strings[i] - } -} - -// valueSortLess returns whether the first value should sort before the second -// value. It is used by valueSorter.Less as part of the sort.Interface -// implementation. -func valueSortLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Bool: - return !a.Bool() && b.Bool() - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return a.Int() < b.Int() - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return a.Uint() < b.Uint() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.String: - return a.String() < b.String() - case reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Array: - // Compare the contents of both arrays. - l := a.Len() - for i := 0; i < l; i++ { - av := a.Index(i) - bv := b.Index(i) - if av.Interface() == bv.Interface() { - continue - } - return valueSortLess(av, bv) - } - } - return a.String() < b.String() -} - -// Less returns whether the value at index i should sort before the -// value at index j. It is part of the sort.Interface implementation. -func (s *valuesSorter) Less(i, j int) bool { - if s.strings == nil { - return valueSortLess(s.values[i], s.values[j]) - } - return s.strings[i] < s.strings[j] -} - -// sortValues is a sort function that handles both native types and any type that -// can be converted to error or Stringer. Other inputs are sorted according to -// their Value.String() value to ensure display stability. -func sortValues(values []reflect.Value, cs *ConfigState) { - if len(values) == 0 { - return - } - sort.Sort(newValuesSorter(values, cs)) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go deleted file mode 100644 index 2e3d22f..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/config.go +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// ConfigState houses the configuration options used by spew to format and -// display values. There is a global instance, Config, that is used to control -// all top-level Formatter and Dump functionality. Each ConfigState instance -// provides methods equivalent to the top-level functions. -// -// The zero value for ConfigState provides no indentation. You would typically -// want to set it to a space or a tab. -// -// Alternatively, you can use NewDefaultConfig to get a ConfigState instance -// with default settings. See the documentation of NewDefaultConfig for default -// values. -type ConfigState struct { - // Indent specifies the string to use for each indentation level. The - // global config instance that all top-level functions use set this to a - // single space by default. If you would like more indentation, you might - // set this to a tab with "\t" or perhaps two spaces with " ". - Indent string - - // MaxDepth controls the maximum number of levels to descend into nested - // data structures. The default, 0, means there is no limit. - // - // NOTE: Circular data structures are properly detected, so it is not - // necessary to set this value unless you specifically want to limit deeply - // nested data structures. - MaxDepth int - - // DisableMethods specifies whether or not error and Stringer interfaces are - // invoked for types that implement them. - DisableMethods bool - - // DisablePointerMethods specifies whether or not to check for and invoke - // error and Stringer interfaces on types which only accept a pointer - // receiver when the current type is not a pointer. - // - // NOTE: This might be an unsafe action since calling one of these methods - // with a pointer receiver could technically mutate the value, however, - // in practice, types which choose to satisify an error or Stringer - // interface with a pointer receiver should not be mutating their state - // inside these interface methods. As a result, this option relies on - // access to the unsafe package, so it will not have any effect when - // running in environments without access to the unsafe package such as - // Google App Engine or with the "safe" build tag specified. - DisablePointerMethods bool - - // DisablePointerAddresses specifies whether to disable the printing of - // pointer addresses. This is useful when diffing data structures in tests. - DisablePointerAddresses bool - - // DisableCapacities specifies whether to disable the printing of capacities - // for arrays, slices, maps and channels. This is useful when diffing - // data structures in tests. - DisableCapacities bool - - // ContinueOnMethod specifies whether or not recursion should continue once - // a custom error or Stringer interface is invoked. The default, false, - // means it will print the results of invoking the custom error or Stringer - // interface and return immediately instead of continuing to recurse into - // the internals of the data type. - // - // NOTE: This flag does not have any effect if method invocation is disabled - // via the DisableMethods or DisablePointerMethods options. - ContinueOnMethod bool - - // SortKeys specifies map keys should be sorted before being printed. Use - // this to have a more deterministic, diffable output. Note that only - // native types (bool, int, uint, floats, uintptr and string) and types - // that support the error or Stringer interfaces (if methods are - // enabled) are supported, with other types sorted according to the - // reflect.Value.String() output which guarantees display stability. - SortKeys bool - - // SpewKeys specifies that, as a last resort attempt, map keys should - // be spewed to strings and sorted by those strings. This is only - // considered if SortKeys is true. - SpewKeys bool -} - -// Config is the active configuration of the top-level functions. -// The configuration can be changed by modifying the contents of spew.Config. -var Config = ConfigState{Indent: " "} - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the formatted string as a value that satisfies error. See NewFormatter -// for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, c.convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, c.convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, c.convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a Formatter interface returned by c.NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, c.convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Print(a ...interface{}) (n int, err error) { - return fmt.Print(c.convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, c.convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Println(a ...interface{}) (n int, err error) { - return fmt.Println(c.convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprint(a ...interface{}) string { - return fmt.Sprint(c.convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, c.convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a Formatter interface returned by c.NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintln(a ...interface{}) string { - return fmt.Sprintln(c.convertArgs(a)...) -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -c.Printf, c.Println, or c.Printf. -*/ -func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(c, v) -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { - fdump(c, w, a...) -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by modifying the public members -of c. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func (c *ConfigState) Dump(a ...interface{}) { - fdump(c, os.Stdout, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func (c *ConfigState) Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(c, &buf, a...) - return buf.String() -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a spew Formatter interface using -// the ConfigState associated with s. -func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = newFormatter(c, arg) - } - return formatters -} - -// NewDefaultConfig returns a ConfigState with the following default settings. -// -// Indent: " " -// MaxDepth: 0 -// DisableMethods: false -// DisablePointerMethods: false -// ContinueOnMethod: false -// SortKeys: false -func NewDefaultConfig() *ConfigState { - return &ConfigState{Indent: " "} -} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go deleted file mode 100644 index aacaac6..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/doc.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Package spew implements a deep pretty printer for Go data structures to aid in -debugging. - -A quick overview of the additional features spew provides over the built-in -printing facilities for Go data types are as follows: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output (only when using - Dump style) - -There are two different approaches spew allows for dumping Go data structures: - - * Dump style which prints with newlines, customizable indentation, - and additional debug information such as types and all pointer addresses - used to indirect to the final value - * A custom Formatter interface that integrates cleanly with the standard fmt - package and replaces %v, %+v, %#v, and %#+v to provide inline printing - similar to the default %v while providing the additional functionality - outlined above and passing unsupported format verbs such as %x and %q - along to fmt - -Quick Start - -This section demonstrates how to quickly get started with spew. See the -sections below for further details on formatting and configuration options. - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - spew.Dump(myVar1, myVar2, ...) - spew.Fdump(someWriter, myVar1, myVar2, ...) - str := spew.Sdump(myVar1, myVar2, ...) - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with -%v (most compact), %+v (adds pointer addresses), %#v (adds types), or -%#+v (adds types and pointer addresses): - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -Configuration Options - -Configuration of spew is handled by fields in the ConfigState type. For -convenience, all of the top-level functions use a global state available -via the spew.Config global. - -It is also possible to create a ConfigState instance that provides methods -equivalent to the top-level functions. This allows concurrent configuration -options. See the ConfigState documentation for more details. - -The following configuration options are available: - * Indent - String to use for each indentation level for Dump functions. - It is a single space by default. A popular alternative is "\t". - - * MaxDepth - Maximum number of levels to descend into nested data structures. - There is no limit by default. - - * DisableMethods - Disables invocation of error and Stringer interface methods. - Method invocation is enabled by default. - - * DisablePointerMethods - Disables invocation of error and Stringer interface methods on types - which only accept pointer receivers from non-pointer variables. - Pointer method invocation is enabled by default. - - * DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - - * DisableCapacities - DisableCapacities specifies whether to disable the printing of - capacities for arrays, slices, maps and channels. This is useful when - diffing data structures in tests. - - * ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - - * SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are - supported with other types sorted according to the - reflect.Value.String() output which guarantees display - stability. Natural map order is used by default. - - * SpewKeys - Specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only - considered if SortKeys is true. - -Dump Usage - -Simply call spew.Dump with a list of variables you want to dump: - - spew.Dump(myVar1, myVar2, ...) - -You may also call spew.Fdump if you would prefer to output to an arbitrary -io.Writer. For example, to dump to standard error: - - spew.Fdump(os.Stderr, myVar1, myVar2, ...) - -A third option is to call spew.Sdump to get the formatted output as a string: - - str := spew.Sdump(myVar1, myVar2, ...) - -Sample Dump Output - -See the Dump example for details on the setup of the types and variables being -shown here. - - (main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - ExportedField: (map[interface {}]interface {}) (len=1) { - (string) (len=3) "one": (bool) true - } - } - -Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C -command as shown. - ([]uint8) (len=32 cap=32) { - 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - 00000020 31 32 |12| - } - -Custom Formatter - -Spew provides a custom formatter that implements the fmt.Formatter interface -so that it integrates cleanly with standard fmt package printing functions. The -formatter is useful for inline printing of smaller data types similar to the -standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Custom Formatter Usage - -The simplest way to make use of the spew custom formatter is to call one of the -convenience functions such as spew.Printf, spew.Println, or spew.Printf. The -functions have syntax you are most likely already familiar with: - - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Println(myVar, myVar2) - spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -See the Index for the full list convenience functions. - -Sample Formatter Output - -Double pointer to a uint8: - %v: <**>5 - %+v: <**>(0xf8400420d0->0xf8400420c8)5 - %#v: (**uint8)5 - %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 - -Pointer to circular struct with a uint8 field and a pointer to itself: - %v: <*>{1 <*>} - %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} - %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} - %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} - -See the Printf example for details on the setup of variables being shown -here. - -Errors - -Since it is possible for custom Stringer/error interfaces to panic, spew -detects them and handles them internally by printing the panic information -inline with the output. Since spew is intended to provide deep pretty printing -capabilities on structures, it intentionally does not return any errors. -*/ -package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go deleted file mode 100644 index f78d89f..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "encoding/hex" - "fmt" - "io" - "os" - "reflect" - "regexp" - "strconv" - "strings" -) - -var ( - // uint8Type is a reflect.Type representing a uint8. It is used to - // convert cgo types to uint8 slices for hexdumping. - uint8Type = reflect.TypeOf(uint8(0)) - - // cCharRE is a regular expression that matches a cgo char. - // It is used to detect character arrays to hexdump them. - cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) - - // cUnsignedCharRE is a regular expression that matches a cgo unsigned - // char. It is used to detect unsigned character arrays to hexdump - // them. - cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) - - // cUint8tCharRE is a regular expression that matches a cgo uint8_t. - // It is used to detect uint8_t arrays to hexdump them. - cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) -) - -// dumpState contains information about the state of a dump operation. -type dumpState struct { - w io.Writer - depth int - pointers map[uintptr]int - ignoreNextType bool - ignoreNextIndent bool - cs *ConfigState -} - -// indent performs indentation according to the depth level and cs.Indent -// option. -func (d *dumpState) indent() { - if d.ignoreNextIndent { - d.ignoreNextIndent = false - return - } - d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) -} - -// unpackValue returns values inside of non-nil interfaces when possible. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface && !v.IsNil() { - v = v.Elem() - } - return v -} - -// dumpPtr handles formatting of pointers by indirecting them as necessary. -func (d *dumpState) dumpPtr(v reflect.Value) { - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range d.pointers { - if depth >= d.depth { - delete(d.pointers, k) - } - } - - // Keep list of all dereferenced pointers to show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by dereferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := d.pointers[addr]; ok && pd < d.depth { - cycleFound = true - indirects-- - break - } - d.pointers[addr] = d.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type information. - d.w.Write(openParenBytes) - d.w.Write(bytes.Repeat(asteriskBytes, indirects)) - d.w.Write([]byte(ve.Type().String())) - d.w.Write(closeParenBytes) - - // Display pointer information. - if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { - d.w.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - d.w.Write(pointerChainBytes) - } - printHexPtr(d.w, addr) - } - d.w.Write(closeParenBytes) - } - - // Display dereferenced value. - d.w.Write(openParenBytes) - switch { - case nilFound: - d.w.Write(nilAngleBytes) - - case cycleFound: - d.w.Write(circularBytes) - - default: - d.ignoreNextType = true - d.dump(ve) - } - d.w.Write(closeParenBytes) -} - -// dumpSlice handles formatting of arrays and slices. Byte (uint8 under -// reflection) arrays and slices are dumped in hexdump -C fashion. -func (d *dumpState) dumpSlice(v reflect.Value) { - // Determine whether this type should be hex dumped or not. Also, - // for types which should be hexdumped, try to use the underlying data - // first, then fall back to trying to convert them to a uint8 slice. - var buf []uint8 - doConvert := false - doHexDump := false - numEntries := v.Len() - if numEntries > 0 { - vt := v.Index(0).Type() - vts := vt.String() - switch { - // C types that need to be converted. - case cCharRE.MatchString(vts): - fallthrough - case cUnsignedCharRE.MatchString(vts): - fallthrough - case cUint8tCharRE.MatchString(vts): - doConvert = true - - // Try to use existing uint8 slices and fall back to converting - // and copying if that fails. - case vt.Kind() == reflect.Uint8: - // We need an addressable interface to convert the type - // to a byte slice. However, the reflect package won't - // give us an interface on certain things like - // unexported struct fields in order to enforce - // visibility rules. We use unsafe, when available, to - // bypass these restrictions since this package does not - // mutate the values. - vs := v - if !vs.CanInterface() || !vs.CanAddr() { - vs = unsafeReflectValue(vs) - } - if !UnsafeDisabled { - vs = vs.Slice(0, numEntries) - - // Use the existing uint8 slice if it can be - // type asserted. - iface := vs.Interface() - if slice, ok := iface.([]uint8); ok { - buf = slice - doHexDump = true - break - } - } - - // The underlying data needs to be converted if it can't - // be type asserted to a uint8 slice. - doConvert = true - } - - // Copy and convert the underlying type if needed. - if doConvert && vt.ConvertibleTo(uint8Type) { - // Convert and copy each element into a uint8 byte - // slice. - buf = make([]uint8, numEntries) - for i := 0; i < numEntries; i++ { - vv := v.Index(i) - buf[i] = uint8(vv.Convert(uint8Type).Uint()) - } - doHexDump = true - } - } - - // Hexdump the entire slice as needed. - if doHexDump { - indent := strings.Repeat(d.cs.Indent, d.depth) - str := indent + hex.Dump(buf) - str = strings.Replace(str, "\n", "\n"+indent, -1) - str = strings.TrimRight(str, d.cs.Indent) - d.w.Write([]byte(str)) - return - } - - // Recursively call dump for each item. - for i := 0; i < numEntries; i++ { - d.dump(d.unpackValue(v.Index(i))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } -} - -// dump is the main workhorse for dumping a value. It uses the passed reflect -// value to figure out what kind of object we are dealing with and formats it -// appropriately. It is a recursive function, however circular data structures -// are detected and handled properly. -func (d *dumpState) dump(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - d.w.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - d.indent() - d.dumpPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !d.ignoreNextType { - d.indent() - d.w.Write(openParenBytes) - d.w.Write([]byte(v.Type().String())) - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - d.ignoreNextType = false - - // Display length and capacity if the built-in len and cap functions - // work with the value's kind and the len/cap itself is non-zero. - valueLen, valueCap := 0, 0 - switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - valueLen, valueCap = v.Len(), v.Cap() - case reflect.Map, reflect.String: - valueLen = v.Len() - } - if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { - d.w.Write(openParenBytes) - if valueLen != 0 { - d.w.Write(lenEqualsBytes) - printInt(d.w, int64(valueLen), 10) - } - if !d.cs.DisableCapacities && valueCap != 0 { - if valueLen != 0 { - d.w.Write(spaceBytes) - } - d.w.Write(capEqualsBytes) - printInt(d.w, int64(valueCap), 10) - } - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - - // Call Stringer/error interfaces if they exist and the handle methods flag - // is enabled - if !d.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(d.cs, d.w, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(d.w, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(d.w, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(d.w, v.Uint(), 10) - - case reflect.Float32: - printFloat(d.w, v.Float(), 32) - - case reflect.Float64: - printFloat(d.w, v.Float(), 64) - - case reflect.Complex64: - printComplex(d.w, v.Complex(), 32) - - case reflect.Complex128: - printComplex(d.w, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - d.dumpSlice(v) - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.String: - d.w.Write([]byte(strconv.Quote(v.String()))) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - d.w.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - numEntries := v.Len() - keys := v.MapKeys() - if d.cs.SortKeys { - sortValues(keys, d.cs) - } - for i, key := range keys { - d.dump(d.unpackValue(key)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.MapIndex(key))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Struct: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - vt := v.Type() - numFields := v.NumField() - for i := 0; i < numFields; i++ { - d.indent() - vtf := vt.Field(i) - d.w.Write([]byte(vtf.Name)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.Field(i))) - if i < (numFields - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(d.w, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(d.w, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it in case any new - // types are added. - default: - if v.CanInterface() { - fmt.Fprintf(d.w, "%v", v.Interface()) - } else { - fmt.Fprintf(d.w, "%v", v.String()) - } - } -} - -// fdump is a helper function to consolidate the logic from the various public -// methods which take varying writers and config states. -func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { - for _, arg := range a { - if arg == nil { - w.Write(interfaceBytes) - w.Write(spaceBytes) - w.Write(nilAngleBytes) - w.Write(newlineBytes) - continue - } - - d := dumpState{w: w, cs: cs} - d.pointers = make(map[uintptr]int) - d.dump(reflect.ValueOf(arg)) - d.w.Write(newlineBytes) - } -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func Fdump(w io.Writer, a ...interface{}) { - fdump(&Config, w, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(&Config, &buf, a...) - return buf.String() -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by an exported package global, -spew.Config. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func Dump(a ...interface{}) { - fdump(&Config, os.Stdout, a...) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go deleted file mode 100644 index b04edb7..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "reflect" - "strconv" - "strings" -) - -// supportedFlags is a list of all the character flags supported by fmt package. -const supportedFlags = "0-+# " - -// formatState implements the fmt.Formatter interface and contains information -// about the state of a formatting operation. The NewFormatter function can -// be used to get a new Formatter which can be used directly as arguments -// in standard fmt package printing calls. -type formatState struct { - value interface{} - fs fmt.State - depth int - pointers map[uintptr]int - ignoreNextType bool - cs *ConfigState -} - -// buildDefaultFormat recreates the original format string without precision -// and width information to pass in to fmt.Sprintf in the case of an -// unrecognized type. Unless new types are added to the language, this -// function won't ever be called. -func (f *formatState) buildDefaultFormat() (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - buf.WriteRune('v') - - format = buf.String() - return format -} - -// constructOrigFormat recreates the original format string including precision -// and width information to pass along to the standard fmt package. This allows -// automatic deferral of all format strings this package doesn't support. -func (f *formatState) constructOrigFormat(verb rune) (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - if width, ok := f.fs.Width(); ok { - buf.WriteString(strconv.Itoa(width)) - } - - if precision, ok := f.fs.Precision(); ok { - buf.Write(precisionBytes) - buf.WriteString(strconv.Itoa(precision)) - } - - buf.WriteRune(verb) - - format = buf.String() - return format -} - -// unpackValue returns values inside of non-nil interfaces when possible and -// ensures that types for values which have been unpacked from an interface -// are displayed when the show types flag is also set. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (f *formatState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface { - f.ignoreNextType = false - if !v.IsNil() { - v = v.Elem() - } - } - return v -} - -// formatPtr handles formatting of pointers by indirecting them as necessary. -func (f *formatState) formatPtr(v reflect.Value) { - // Display nil if top level pointer is nil. - showTypes := f.fs.Flag('#') - if v.IsNil() && (!showTypes || f.ignoreNextType) { - f.fs.Write(nilAngleBytes) - return - } - - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range f.pointers { - if depth >= f.depth { - delete(f.pointers, k) - } - } - - // Keep list of all dereferenced pointers to possibly show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by derferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := f.pointers[addr]; ok && pd < f.depth { - cycleFound = true - indirects-- - break - } - f.pointers[addr] = f.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type or indirection level depending on flags. - if showTypes && !f.ignoreNextType { - f.fs.Write(openParenBytes) - f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) - f.fs.Write([]byte(ve.Type().String())) - f.fs.Write(closeParenBytes) - } else { - if nilFound || cycleFound { - indirects += strings.Count(ve.Type().String(), "*") - } - f.fs.Write(openAngleBytes) - f.fs.Write([]byte(strings.Repeat("*", indirects))) - f.fs.Write(closeAngleBytes) - } - - // Display pointer information depending on flags. - if f.fs.Flag('+') && (len(pointerChain) > 0) { - f.fs.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - f.fs.Write(pointerChainBytes) - } - printHexPtr(f.fs, addr) - } - f.fs.Write(closeParenBytes) - } - - // Display dereferenced value. - switch { - case nilFound: - f.fs.Write(nilAngleBytes) - - case cycleFound: - f.fs.Write(circularShortBytes) - - default: - f.ignoreNextType = true - f.format(ve) - } -} - -// format is the main workhorse for providing the Formatter interface. It -// uses the passed reflect value to figure out what kind of object we are -// dealing with and formats it appropriately. It is a recursive function, -// however circular data structures are detected and handled properly. -func (f *formatState) format(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - f.fs.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - f.formatPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !f.ignoreNextType && f.fs.Flag('#') { - f.fs.Write(openParenBytes) - f.fs.Write([]byte(v.Type().String())) - f.fs.Write(closeParenBytes) - } - f.ignoreNextType = false - - // Call Stringer/error interfaces if they exist and the handle methods - // flag is enabled. - if !f.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(f.cs, f.fs, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(f.fs, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(f.fs, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(f.fs, v.Uint(), 10) - - case reflect.Float32: - printFloat(f.fs, v.Float(), 32) - - case reflect.Float64: - printFloat(f.fs, v.Float(), 64) - - case reflect.Complex64: - printComplex(f.fs, v.Complex(), 32) - - case reflect.Complex128: - printComplex(f.fs, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - f.fs.Write(openBracketBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - numEntries := v.Len() - for i := 0; i < numEntries; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(v.Index(i))) - } - } - f.depth-- - f.fs.Write(closeBracketBytes) - - case reflect.String: - f.fs.Write([]byte(v.String())) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - f.fs.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - - f.fs.Write(openMapBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - keys := v.MapKeys() - if f.cs.SortKeys { - sortValues(keys, f.cs) - } - for i, key := range keys { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(key)) - f.fs.Write(colonBytes) - f.ignoreNextType = true - f.format(f.unpackValue(v.MapIndex(key))) - } - } - f.depth-- - f.fs.Write(closeMapBytes) - - case reflect.Struct: - numFields := v.NumField() - f.fs.Write(openBraceBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - vt := v.Type() - for i := 0; i < numFields; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - vtf := vt.Field(i) - if f.fs.Flag('+') || f.fs.Flag('#') { - f.fs.Write([]byte(vtf.Name)) - f.fs.Write(colonBytes) - } - f.format(f.unpackValue(v.Field(i))) - } - } - f.depth-- - f.fs.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(f.fs, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(f.fs, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it if any get added. - default: - format := f.buildDefaultFormat() - if v.CanInterface() { - fmt.Fprintf(f.fs, format, v.Interface()) - } else { - fmt.Fprintf(f.fs, format, v.String()) - } - } -} - -// Format satisfies the fmt.Formatter interface. See NewFormatter for usage -// details. -func (f *formatState) Format(fs fmt.State, verb rune) { - f.fs = fs - - // Use standard formatting for verbs that are not v. - if verb != 'v' { - format := f.constructOrigFormat(verb) - fmt.Fprintf(fs, format, f.value) - return - } - - if f.value == nil { - if fs.Flag('#') { - fs.Write(interfaceBytes) - } - fs.Write(nilAngleBytes) - return - } - - f.format(reflect.ValueOf(f.value)) -} - -// newFormatter is a helper function to consolidate the logic from the various -// public methods which take varying config states. -func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { - fs := &formatState{value: v, cs: cs} - fs.pointers = make(map[uintptr]int) - return fs -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -Printf, Println, or Fprintf. -*/ -func NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(&Config, v) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go deleted file mode 100644 index 32c0e33..0000000 --- a/vendor/github.com/davecgh/go-spew/spew/spew.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "fmt" - "io" -) - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the formatted string as a value that satisfies error. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a default Formatter interface returned by NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) -func Print(a ...interface{}) (n int, err error) { - return fmt.Print(convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) -func Println(a ...interface{}) (n int, err error) { - return fmt.Println(convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprint(a ...interface{}) string { - return fmt.Sprint(convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintln(a ...interface{}) string { - return fmt.Sprintln(convertArgs(a)...) -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a default spew Formatter interface. -func convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = NewFormatter(arg) - } - return formatters -} diff --git a/vendor/github.com/go-playground/locales/.gitignore b/vendor/github.com/go-playground/locales/.gitignore deleted file mode 100644 index daf913b..0000000 --- a/vendor/github.com/go-playground/locales/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# 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 - -*.exe -*.test -*.prof diff --git a/vendor/github.com/go-playground/locales/.travis.yml b/vendor/github.com/go-playground/locales/.travis.yml deleted file mode 100644 index d50237a..0000000 --- a/vendor/github.com/go-playground/locales/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: go -go: - - 1.13.1 - - tip -matrix: - allow_failures: - - go: tip - -notifications: - email: - recipients: dean.karn@gmail.com - on_success: change - on_failure: always - -before_install: - - go install github.com/mattn/goveralls - -# Only clone the most recent commit. -git: - depth: 1 - -script: - - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... - -after_success: | - goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/vendor/github.com/go-playground/locales/LICENSE b/vendor/github.com/go-playground/locales/LICENSE deleted file mode 100644 index 75854ac..0000000 --- a/vendor/github.com/go-playground/locales/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Go Playground - -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. \ No newline at end of file diff --git a/vendor/github.com/go-playground/locales/README.md b/vendor/github.com/go-playground/locales/README.md deleted file mode 100644 index 5b0694f..0000000 --- a/vendor/github.com/go-playground/locales/README.md +++ /dev/null @@ -1,172 +0,0 @@ -## locales -![Project status](https://img.shields.io/badge/version-0.14.0-green.svg) -[![Build Status](https://travis-ci.org/go-playground/locales.svg?branch=master)](https://travis-ci.org/go-playground/locales) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/locales)](https://goreportcard.com/report/github.com/go-playground/locales) -[![GoDoc](https://godoc.org/github.com/go-playground/locales?status.svg)](https://godoc.org/github.com/go-playground/locales) -![License](https://img.shields.io/dub/l/vibe-d.svg) -[![Gitter](https://badges.gitter.im/go-playground/locales.svg)](https://gitter.im/go-playground/locales?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -Locales is a set of locales generated from the [Unicode CLDR Project](http://cldr.unicode.org/) which can be used independently or within -an i18n package; these were built for use with, but not exclusive to, [Universal Translator](https://github.com/go-playground/universal-translator). - -Features --------- -- [x] Rules generated from the latest [CLDR](http://cldr.unicode.org/index/downloads) data, v36.0.1 -- [x] Contains Cardinal, Ordinal and Range Plural Rules -- [x] Contains Month, Weekday and Timezone translations built in -- [x] Contains Date & Time formatting functions -- [x] Contains Number, Currency, Accounting and Percent formatting functions -- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) - -Full Tests --------------------- -I could sure use your help adding tests for every locale, it is a huge undertaking and I just don't have the free time to do it all at the moment; -any help would be **greatly appreciated!!!!** please see [issue](https://github.com/go-playground/locales/issues/1) for details. - -Installation ------------ - -Use go get - -```shell -go get github.com/go-playground/locales -``` - -NOTES --------- -You'll notice most return types are []byte, this is because most of the time the results will be concatenated with a larger body -of text and can avoid some allocations if already appending to a byte array, otherwise just cast as string. - -Usage -------- -```go -package main - -import ( - "fmt" - "time" - - "github.com/go-playground/locales/currency" - "github.com/go-playground/locales/en_CA" -) - -func main() { - - loc, _ := time.LoadLocation("America/Toronto") - datetime := time.Date(2016, 02, 03, 9, 0, 1, 0, loc) - - l := en_CA.New() - - // Dates - fmt.Println(l.FmtDateFull(datetime)) - fmt.Println(l.FmtDateLong(datetime)) - fmt.Println(l.FmtDateMedium(datetime)) - fmt.Println(l.FmtDateShort(datetime)) - - // Times - fmt.Println(l.FmtTimeFull(datetime)) - fmt.Println(l.FmtTimeLong(datetime)) - fmt.Println(l.FmtTimeMedium(datetime)) - fmt.Println(l.FmtTimeShort(datetime)) - - // Months Wide - fmt.Println(l.MonthWide(time.January)) - fmt.Println(l.MonthWide(time.February)) - fmt.Println(l.MonthWide(time.March)) - // ... - - // Months Abbreviated - fmt.Println(l.MonthAbbreviated(time.January)) - fmt.Println(l.MonthAbbreviated(time.February)) - fmt.Println(l.MonthAbbreviated(time.March)) - // ... - - // Months Narrow - fmt.Println(l.MonthNarrow(time.January)) - fmt.Println(l.MonthNarrow(time.February)) - fmt.Println(l.MonthNarrow(time.March)) - // ... - - // Weekdays Wide - fmt.Println(l.WeekdayWide(time.Sunday)) - fmt.Println(l.WeekdayWide(time.Monday)) - fmt.Println(l.WeekdayWide(time.Tuesday)) - // ... - - // Weekdays Abbreviated - fmt.Println(l.WeekdayAbbreviated(time.Sunday)) - fmt.Println(l.WeekdayAbbreviated(time.Monday)) - fmt.Println(l.WeekdayAbbreviated(time.Tuesday)) - // ... - - // Weekdays Short - fmt.Println(l.WeekdayShort(time.Sunday)) - fmt.Println(l.WeekdayShort(time.Monday)) - fmt.Println(l.WeekdayShort(time.Tuesday)) - // ... - - // Weekdays Narrow - fmt.Println(l.WeekdayNarrow(time.Sunday)) - fmt.Println(l.WeekdayNarrow(time.Monday)) - fmt.Println(l.WeekdayNarrow(time.Tuesday)) - // ... - - var f64 float64 - - f64 = -10356.4523 - - // Number - fmt.Println(l.FmtNumber(f64, 2)) - - // Currency - fmt.Println(l.FmtCurrency(f64, 2, currency.CAD)) - fmt.Println(l.FmtCurrency(f64, 2, currency.USD)) - - // Accounting - fmt.Println(l.FmtAccounting(f64, 2, currency.CAD)) - fmt.Println(l.FmtAccounting(f64, 2, currency.USD)) - - f64 = 78.12 - - // Percent - fmt.Println(l.FmtPercent(f64, 0)) - - // Plural Rules for locale, so you know what rules you must cover - fmt.Println(l.PluralsCardinal()) - fmt.Println(l.PluralsOrdinal()) - - // Cardinal Plural Rules - fmt.Println(l.CardinalPluralRule(1, 0)) - fmt.Println(l.CardinalPluralRule(1.0, 0)) - fmt.Println(l.CardinalPluralRule(1.0, 1)) - fmt.Println(l.CardinalPluralRule(3, 0)) - - // Ordinal Plural Rules - fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st - fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd - fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd - fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th - - // Range Plural Rules - fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 - fmt.Println(l.RangePluralRule(1, 0, 2, 0)) // 1-2 - fmt.Println(l.RangePluralRule(5, 0, 8, 0)) // 5-8 -} -``` - -NOTES: -------- -These rules were generated from the [Unicode CLDR Project](http://cldr.unicode.org/), if you encounter any issues -I strongly encourage contributing to the CLDR project to get the locale information corrected and the next time -these locales are regenerated the fix will come with. - -I do however realize that time constraints are often important and so there are two options: - -1. Create your own locale, copy, paste and modify, and ensure it complies with the `Translator` interface. -2. Add an exception in the locale generation code directly and once regenerated, fix will be in place. - -Please to not make fixes inside the locale files, they WILL get overwritten when the locales are regenerated. - -License ------- -Distributed under MIT License, please see license file in code for more details. diff --git a/vendor/github.com/go-playground/locales/currency/currency.go b/vendor/github.com/go-playground/locales/currency/currency.go deleted file mode 100644 index b5a95fb..0000000 --- a/vendor/github.com/go-playground/locales/currency/currency.go +++ /dev/null @@ -1,311 +0,0 @@ -package currency - -// Type is the currency type associated with the locales currency enum -type Type int - -// locale currencies -const ( - ADP Type = iota - AED - AFA - AFN - ALK - ALL - AMD - ANG - AOA - AOK - AON - AOR - ARA - ARL - ARM - ARP - ARS - ATS - AUD - AWG - AZM - AZN - BAD - BAM - BAN - BBD - BDT - BEC - BEF - BEL - BGL - BGM - BGN - BGO - BHD - BIF - BMD - BND - BOB - BOL - BOP - BOV - BRB - BRC - BRE - BRL - BRN - BRR - BRZ - BSD - BTN - BUK - BWP - BYB - BYN - BYR - BZD - CAD - CDF - CHE - CHF - CHW - CLE - CLF - CLP - CNH - CNX - CNY - COP - COU - CRC - CSD - CSK - CUC - CUP - CVE - CYP - CZK - DDM - DEM - DJF - DKK - DOP - DZD - ECS - ECV - EEK - EGP - ERN - ESA - ESB - ESP - ETB - EUR - FIM - FJD - FKP - FRF - GBP - GEK - GEL - GHC - GHS - GIP - GMD - GNF - GNS - GQE - GRD - GTQ - GWE - GWP - GYD - HKD - HNL - HRD - HRK - HTG - HUF - IDR - IEP - ILP - ILR - ILS - INR - IQD - IRR - ISJ - ISK - ITL - JMD - JOD - JPY - KES - KGS - KHR - KMF - KPW - KRH - KRO - KRW - KWD - KYD - KZT - LAK - LBP - LKR - LRD - LSL - LTL - LTT - LUC - LUF - LUL - LVL - LVR - LYD - MAD - MAF - MCF - MDC - MDL - MGA - MGF - MKD - MKN - MLF - MMK - MNT - MOP - MRO - MRU - MTL - MTP - MUR - MVP - MVR - MWK - MXN - MXP - MXV - MYR - MZE - MZM - MZN - NAD - NGN - NIC - NIO - NLG - NOK - NPR - NZD - OMR - PAB - PEI - PEN - PES - PGK - PHP - PKR - PLN - PLZ - PTE - PYG - QAR - RHD - ROL - RON - RSD - RUB - RUR - RWF - SAR - SBD - SCR - SDD - SDG - SDP - SEK - SGD - SHP - SIT - SKK - SLL - SOS - SRD - SRG - SSP - STD - STN - SUR - SVC - SYP - SZL - THB - TJR - TJS - TMM - TMT - TND - TOP - TPE - TRL - TRY - TTD - TWD - TZS - UAH - UAK - UGS - UGX - USD - USN - USS - UYI - UYP - UYU - UYW - UZS - VEB - VEF - VES - VND - VNN - VUV - WST - XAF - XAG - XAU - XBA - XBB - XBC - XBD - XCD - XDR - XEU - XFO - XFU - XOF - XPD - XPF - XPT - XRE - XSU - XTS - XUA - XXX - YDD - YER - YUD - YUM - YUN - YUR - ZAL - ZAR - ZMK - ZMW - ZRN - ZRZ - ZWD - ZWL - ZWR -) diff --git a/vendor/github.com/go-playground/locales/logo.png b/vendor/github.com/go-playground/locales/logo.png deleted file mode 100644 index 3038276..0000000 Binary files a/vendor/github.com/go-playground/locales/logo.png and /dev/null differ diff --git a/vendor/github.com/go-playground/locales/rules.go b/vendor/github.com/go-playground/locales/rules.go deleted file mode 100644 index 9202900..0000000 --- a/vendor/github.com/go-playground/locales/rules.go +++ /dev/null @@ -1,293 +0,0 @@ -package locales - -import ( - "strconv" - "time" - - "github.com/go-playground/locales/currency" -) - -// // ErrBadNumberValue is returned when the number passed for -// // plural rule determination cannot be parsed -// type ErrBadNumberValue struct { -// NumberValue string -// InnerError error -// } - -// // Error returns ErrBadNumberValue error string -// func (e *ErrBadNumberValue) Error() string { -// return fmt.Sprintf("Invalid Number Value '%s' %s", e.NumberValue, e.InnerError) -// } - -// var _ error = new(ErrBadNumberValue) - -// PluralRule denotes the type of plural rules -type PluralRule int - -// PluralRule's -const ( - PluralRuleUnknown PluralRule = iota - PluralRuleZero // zero - PluralRuleOne // one - singular - PluralRuleTwo // two - dual - PluralRuleFew // few - paucal - PluralRuleMany // many - also used for fractions if they have a separate class - PluralRuleOther // other - required—general plural form—also used if the language only has a single form -) - -const ( - pluralsString = "UnknownZeroOneTwoFewManyOther" -) - -// Translator encapsulates an instance of a locale -// NOTE: some values are returned as a []byte just in case the caller -// wishes to add more and can help avoid allocations; otherwise just cast as string -type Translator interface { - - // The following Functions are for overriding, debugging or developing - // with a Translator Locale - - // Locale returns the string value of the translator - Locale() string - - // returns an array of cardinal plural rules associated - // with this translator - PluralsCardinal() []PluralRule - - // returns an array of ordinal plural rules associated - // with this translator - PluralsOrdinal() []PluralRule - - // returns an array of range plural rules associated - // with this translator - PluralsRange() []PluralRule - - // returns the cardinal PluralRule given 'num' and digits/precision of 'v' for locale - CardinalPluralRule(num float64, v uint64) PluralRule - - // returns the ordinal PluralRule given 'num' and digits/precision of 'v' for locale - OrdinalPluralRule(num float64, v uint64) PluralRule - - // returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for locale - RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) PluralRule - - // returns the locales abbreviated month given the 'month' provided - MonthAbbreviated(month time.Month) string - - // returns the locales abbreviated months - MonthsAbbreviated() []string - - // returns the locales narrow month given the 'month' provided - MonthNarrow(month time.Month) string - - // returns the locales narrow months - MonthsNarrow() []string - - // returns the locales wide month given the 'month' provided - MonthWide(month time.Month) string - - // returns the locales wide months - MonthsWide() []string - - // returns the locales abbreviated weekday given the 'weekday' provided - WeekdayAbbreviated(weekday time.Weekday) string - - // returns the locales abbreviated weekdays - WeekdaysAbbreviated() []string - - // returns the locales narrow weekday given the 'weekday' provided - WeekdayNarrow(weekday time.Weekday) string - - // WeekdaysNarrowreturns the locales narrow weekdays - WeekdaysNarrow() []string - - // returns the locales short weekday given the 'weekday' provided - WeekdayShort(weekday time.Weekday) string - - // returns the locales short weekdays - WeekdaysShort() []string - - // returns the locales wide weekday given the 'weekday' provided - WeekdayWide(weekday time.Weekday) string - - // returns the locales wide weekdays - WeekdaysWide() []string - - // The following Functions are common Formatting functionsfor the Translator's Locale - - // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' - FmtNumber(num float64, v uint64) string - - // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' - // NOTE: 'num' passed into FmtPercent is assumed to be in percent already - FmtPercent(num float64, v uint64) string - - // returns the currency representation of 'num' with digits/precision of 'v' for locale - FmtCurrency(num float64, v uint64, currency currency.Type) string - - // returns the currency representation of 'num' with digits/precision of 'v' for locale - // in accounting notation. - FmtAccounting(num float64, v uint64, currency currency.Type) string - - // returns the short date representation of 't' for locale - FmtDateShort(t time.Time) string - - // returns the medium date representation of 't' for locale - FmtDateMedium(t time.Time) string - - // returns the long date representation of 't' for locale - FmtDateLong(t time.Time) string - - // returns the full date representation of 't' for locale - FmtDateFull(t time.Time) string - - // returns the short time representation of 't' for locale - FmtTimeShort(t time.Time) string - - // returns the medium time representation of 't' for locale - FmtTimeMedium(t time.Time) string - - // returns the long time representation of 't' for locale - FmtTimeLong(t time.Time) string - - // returns the full time representation of 't' for locale - FmtTimeFull(t time.Time) string -} - -// String returns the string value of PluralRule -func (p PluralRule) String() string { - - switch p { - case PluralRuleZero: - return pluralsString[7:11] - case PluralRuleOne: - return pluralsString[11:14] - case PluralRuleTwo: - return pluralsString[14:17] - case PluralRuleFew: - return pluralsString[17:20] - case PluralRuleMany: - return pluralsString[20:24] - case PluralRuleOther: - return pluralsString[24:] - default: - return pluralsString[:7] - } -} - -// -// Precision Notes: -// -// must specify a precision >= 0, and here is why https://play.golang.org/p/LyL90U0Vyh -// -// v := float64(3.141) -// i := float64(int64(v)) -// -// fmt.Println(v - i) -// -// or -// -// s := strconv.FormatFloat(v-i, 'f', -1, 64) -// fmt.Println(s) -// -// these will not print what you'd expect: 0.14100000000000001 -// and so this library requires a precision to be specified, or -// inaccurate plural rules could be applied. -// -// -// -// n - absolute value of the source number (integer and decimals). -// i - integer digits of n. -// v - number of visible fraction digits in n, with trailing zeros. -// w - number of visible fraction digits in n, without trailing zeros. -// f - visible fractional digits in n, with trailing zeros. -// t - visible fractional digits in n, without trailing zeros. -// -// -// Func(num float64, v uint64) // v = digits/precision and prevents -1 as a special case as this can lead to very unexpected behaviour, see precision note's above. -// -// n := math.Abs(num) -// i := int64(n) -// v := v -// -// -// w := strconv.FormatFloat(num-float64(i), 'f', int(v), 64) // then parse backwards on string until no more zero's.... -// f := strconv.FormatFloat(n, 'f', int(v), 64) // then turn everything after decimal into an int64 -// t := strconv.FormatFloat(n, 'f', int(v), 64) // then parse backwards on string until no more zero's.... -// -// -// -// General Inclusion Rules -// - v will always be available inherently -// - all require n -// - w requires i -// - -// W returns the number of visible fraction digits in N, without trailing zeros. -func W(n float64, v uint64) (w int64) { - - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - - // with either be '0' or '0.xxxx', so if 1 then w will be zero - // otherwise need to parse - if len(s) != 1 { - - s = s[2:] - end := len(s) + 1 - - for i := end; i >= 0; i-- { - if s[i] != '0' { - end = i + 1 - break - } - } - - w = int64(len(s[:end])) - } - - return -} - -// F returns the visible fractional digits in N, with trailing zeros. -func F(n float64, v uint64) (f int64) { - - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - - // with either be '0' or '0.xxxx', so if 1 then f will be zero - // otherwise need to parse - if len(s) != 1 { - - // ignoring error, because it can't fail as we generated - // the string internally from a real number - f, _ = strconv.ParseInt(s[2:], 10, 64) - } - - return -} - -// T returns the visible fractional digits in N, without trailing zeros. -func T(n float64, v uint64) (t int64) { - - s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) - - // with either be '0' or '0.xxxx', so if 1 then t will be zero - // otherwise need to parse - if len(s) != 1 { - - s = s[2:] - end := len(s) + 1 - - for i := end; i >= 0; i-- { - if s[i] != '0' { - end = i + 1 - break - } - } - - // ignoring error, because it can't fail as we generated - // the string internally from a real number - t, _ = strconv.ParseInt(s[:end], 10, 64) - } - - return -} diff --git a/vendor/github.com/go-playground/universal-translator/.gitignore b/vendor/github.com/go-playground/universal-translator/.gitignore deleted file mode 100644 index bc4e07f..0000000 --- a/vendor/github.com/go-playground/universal-translator/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# 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 - -*.exe -*.test -*.prof -*.coverprofile \ No newline at end of file diff --git a/vendor/github.com/go-playground/universal-translator/.travis.yml b/vendor/github.com/go-playground/universal-translator/.travis.yml deleted file mode 100644 index 39b8b92..0000000 --- a/vendor/github.com/go-playground/universal-translator/.travis.yml +++ /dev/null @@ -1,27 +0,0 @@ -language: go -go: - - 1.13.4 - - tip -matrix: - allow_failures: - - go: tip - -notifications: - email: - recipients: dean.karn@gmail.com - on_success: change - on_failure: always - -before_install: - - go install github.com/mattn/goveralls - -# Only clone the most recent commit. -git: - depth: 1 - -script: - - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... - -after_success: | - [ $TRAVIS_GO_VERSION = 1.13.4 ] && - goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/vendor/github.com/go-playground/universal-translator/LICENSE b/vendor/github.com/go-playground/universal-translator/LICENSE deleted file mode 100644 index 8d8aba1..0000000 --- a/vendor/github.com/go-playground/universal-translator/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Go Playground - -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/go-playground/universal-translator/Makefile b/vendor/github.com/go-playground/universal-translator/Makefile deleted file mode 100644 index ec3455b..0000000 --- a/vendor/github.com/go-playground/universal-translator/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -GOCMD=GO111MODULE=on go - -linters-install: - @golangci-lint --version >/dev/null 2>&1 || { \ - echo "installing linting tools..."; \ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.41.1; \ - } - -lint: linters-install - golangci-lint run - -test: - $(GOCMD) test -cover -race ./... - -bench: - $(GOCMD) test -bench=. -benchmem ./... - -.PHONY: test lint linters-install \ No newline at end of file diff --git a/vendor/github.com/go-playground/universal-translator/README.md b/vendor/github.com/go-playground/universal-translator/README.md deleted file mode 100644 index 46dec6d..0000000 --- a/vendor/github.com/go-playground/universal-translator/README.md +++ /dev/null @@ -1,89 +0,0 @@ -## universal-translator -![Project status](https://img.shields.io/badge/version-0.18.0-green.svg) -[![Build Status](https://travis-ci.org/go-playground/universal-translator.svg?branch=master)](https://travis-ci.org/go-playground/universal-translator) -[![Coverage Status](https://coveralls.io/repos/github/go-playground/universal-translator/badge.svg)](https://coveralls.io/github/go-playground/universal-translator) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/universal-translator)](https://goreportcard.com/report/github.com/go-playground/universal-translator) -[![GoDoc](https://godoc.org/github.com/go-playground/universal-translator?status.svg)](https://godoc.org/github.com/go-playground/universal-translator) -![License](https://img.shields.io/dub/l/vibe-d.svg) -[![Gitter](https://badges.gitter.im/go-playground/universal-translator.svg)](https://gitter.im/go-playground/universal-translator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -Universal Translator is an i18n Translator for Go/Golang using CLDR data + pluralization rules - -Why another i18n library? --------------------------- -Because none of the plural rules seem to be correct out there, including the previous implementation of this package, -so I took it upon myself to create [locales](https://github.com/go-playground/locales) for everyone to use; this package -is a thin wrapper around [locales](https://github.com/go-playground/locales) in order to store and translate text for -use in your applications. - -Features --------- -- [x] Rules generated from the [CLDR](http://cldr.unicode.org/index/downloads) data, v36.0.1 -- [x] Contains Cardinal, Ordinal and Range Plural Rules -- [x] Contains Month, Weekday and Timezone translations built in -- [x] Contains Date & Time formatting functions -- [x] Contains Number, Currency, Accounting and Percent formatting functions -- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) -- [x] Support loading translations from files -- [x] Exporting translations to file(s), mainly for getting them professionally translated -- [ ] Code Generation for translation files -> Go code.. i.e. after it has been professionally translated -- [ ] Tests for all languages, I need help with this, please see [here](https://github.com/go-playground/locales/issues/1) - -Installation ------------ - -Use go get - -```shell -go get github.com/go-playground/universal-translator -``` - -Usage & Documentation -------- - -Please see https://godoc.org/github.com/go-playground/universal-translator for usage docs - -##### Examples: - -- [Basic](https://github.com/go-playground/universal-translator/tree/master/_examples/basic) -- [Full - no files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-no-files) -- [Full - with files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-with-files) - -File formatting --------------- -All types, Plain substitution, Cardinal, Ordinal and Range translations can all be contained within the same file(s); -they are only separated for easy viewing. - -##### Examples: - -- [Formats](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) - -##### Basic Makeup -NOTE: not all fields are needed for all translation types, see [examples](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) -```json -{ - "locale": "en", - "key": "days-left", - "trans": "You have {0} day left.", - "type": "Cardinal", - "rule": "One", - "override": false -} -``` -|Field|Description| -|---|---| -|locale|The locale for which the translation is for.| -|key|The translation key that will be used to store and lookup each translation; normally it is a string or integer.| -|trans|The actual translation text.| -|type|The type of translation Cardinal, Ordinal, Range or "" for a plain substitution(not required to be defined if plain used)| -|rule|The plural rule for which the translation is for eg. One, Two, Few, Many or Other.(not required to be defined if plain used)| -|override|If you wish to override an existing translation that has already been registered, set this to 'true'. 99% of the time there is no need to define it.| - -Help With Tests ---------------- -To anyone interesting in helping or contributing, I sure could use some help creating tests for each language. -Please see issue [here](https://github.com/go-playground/locales/issues/1) for details. - -License ------- -Distributed under MIT License, please see license file in code for more details. diff --git a/vendor/github.com/go-playground/universal-translator/errors.go b/vendor/github.com/go-playground/universal-translator/errors.go deleted file mode 100644 index 38b163b..0000000 --- a/vendor/github.com/go-playground/universal-translator/errors.go +++ /dev/null @@ -1,148 +0,0 @@ -package ut - -import ( - "errors" - "fmt" - - "github.com/go-playground/locales" -) - -var ( - // ErrUnknowTranslation indicates the translation could not be found - ErrUnknowTranslation = errors.New("Unknown Translation") -) - -var _ error = new(ErrConflictingTranslation) -var _ error = new(ErrRangeTranslation) -var _ error = new(ErrOrdinalTranslation) -var _ error = new(ErrCardinalTranslation) -var _ error = new(ErrMissingPluralTranslation) -var _ error = new(ErrExistingTranslator) - -// ErrExistingTranslator is the error representing a conflicting translator -type ErrExistingTranslator struct { - locale string -} - -// Error returns ErrExistingTranslator's internal error text -func (e *ErrExistingTranslator) Error() string { - return fmt.Sprintf("error: conflicting translator for locale '%s'", e.locale) -} - -// ErrConflictingTranslation is the error representing a conflicting translation -type ErrConflictingTranslation struct { - locale string - key interface{} - rule locales.PluralRule - text string -} - -// Error returns ErrConflictingTranslation's internal error text -func (e *ErrConflictingTranslation) Error() string { - - if _, ok := e.key.(string); !ok { - return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) - } - - return fmt.Sprintf("error: conflicting key '%s' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) -} - -// ErrRangeTranslation is the error representing a range translation error -type ErrRangeTranslation struct { - text string -} - -// Error returns ErrRangeTranslation's internal error text -func (e *ErrRangeTranslation) Error() string { - return e.text -} - -// ErrOrdinalTranslation is the error representing an ordinal translation error -type ErrOrdinalTranslation struct { - text string -} - -// Error returns ErrOrdinalTranslation's internal error text -func (e *ErrOrdinalTranslation) Error() string { - return e.text -} - -// ErrCardinalTranslation is the error representing a cardinal translation error -type ErrCardinalTranslation struct { - text string -} - -// Error returns ErrCardinalTranslation's internal error text -func (e *ErrCardinalTranslation) Error() string { - return e.text -} - -// ErrMissingPluralTranslation is the error signifying a missing translation given -// the locales plural rules. -type ErrMissingPluralTranslation struct { - locale string - key interface{} - rule locales.PluralRule - translationType string -} - -// Error returns ErrMissingPluralTranslation's internal error text -func (e *ErrMissingPluralTranslation) Error() string { - - if _, ok := e.key.(string); !ok { - return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) - } - - return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s' and locale '%s'", e.translationType, e.rule, e.key, e.locale) -} - -// ErrMissingBracket is the error representing a missing bracket in a translation -// eg. This is a {0 <-- missing ending '}' -type ErrMissingBracket struct { - locale string - key interface{} - text string -} - -// Error returns ErrMissingBracket error message -func (e *ErrMissingBracket) Error() string { - return fmt.Sprintf("error: missing bracket '{}', in translation. locale: '%s' key: '%v' text: '%s'", e.locale, e.key, e.text) -} - -// ErrBadParamSyntax is the error representing a bad parameter definition in a translation -// eg. This is a {must-be-int} -type ErrBadParamSyntax struct { - locale string - param string - key interface{} - text string -} - -// Error returns ErrBadParamSyntax error message -func (e *ErrBadParamSyntax) Error() string { - return fmt.Sprintf("error: bad parameter syntax, missing parameter '%s' in translation. locale: '%s' key: '%v' text: '%s'", e.param, e.locale, e.key, e.text) -} - -// import/export errors - -// ErrMissingLocale is the error representing an expected locale that could -// not be found aka locale not registered with the UniversalTranslator Instance -type ErrMissingLocale struct { - locale string -} - -// Error returns ErrMissingLocale's internal error text -func (e *ErrMissingLocale) Error() string { - return fmt.Sprintf("error: locale '%s' not registered.", e.locale) -} - -// ErrBadPluralDefinition is the error representing an incorrect plural definition -// usually found within translations defined within files during the import process. -type ErrBadPluralDefinition struct { - tl translation -} - -// Error returns ErrBadPluralDefinition's internal error text -func (e *ErrBadPluralDefinition) Error() string { - return fmt.Sprintf("error: bad plural definition '%#v'", e.tl) -} diff --git a/vendor/github.com/go-playground/universal-translator/import_export.go b/vendor/github.com/go-playground/universal-translator/import_export.go deleted file mode 100644 index 1216f19..0000000 --- a/vendor/github.com/go-playground/universal-translator/import_export.go +++ /dev/null @@ -1,276 +0,0 @@ -package ut - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "io" - - "github.com/go-playground/locales" -) - -type translation struct { - Locale string `json:"locale"` - Key interface{} `json:"key"` // either string or integer - Translation string `json:"trans"` - PluralType string `json:"type,omitempty"` - PluralRule string `json:"rule,omitempty"` - OverrideExisting bool `json:"override,omitempty"` -} - -const ( - cardinalType = "Cardinal" - ordinalType = "Ordinal" - rangeType = "Range" -) - -// ImportExportFormat is the format of the file import or export -type ImportExportFormat uint8 - -// supported Export Formats -const ( - FormatJSON ImportExportFormat = iota -) - -// Export writes the translations out to a file on disk. -// -// NOTE: this currently only works with string or int translations keys. -func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) error { - - _, err := os.Stat(dirname) - fmt.Println(dirname, err, os.IsNotExist(err)) - if err != nil { - - if !os.IsNotExist(err) { - return err - } - - if err = os.MkdirAll(dirname, 0744); err != nil { - return err - } - } - - // build up translations - var trans []translation - var b []byte - var ext string - - for _, locale := range t.translators { - - for k, v := range locale.(*translator).translations { - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k, - Translation: v.text, - }) - } - - for k, pluralTrans := range locale.(*translator).cardinalTanslations { - - for i, plural := range pluralTrans { - - // leave enough for all plural rules - // but not all are set for all languages. - if plural == nil { - continue - } - - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k.(string), - Translation: plural.text, - PluralType: cardinalType, - PluralRule: locales.PluralRule(i).String(), - }) - } - } - - for k, pluralTrans := range locale.(*translator).ordinalTanslations { - - for i, plural := range pluralTrans { - - // leave enough for all plural rules - // but not all are set for all languages. - if plural == nil { - continue - } - - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k.(string), - Translation: plural.text, - PluralType: ordinalType, - PluralRule: locales.PluralRule(i).String(), - }) - } - } - - for k, pluralTrans := range locale.(*translator).rangeTanslations { - - for i, plural := range pluralTrans { - - // leave enough for all plural rules - // but not all are set for all languages. - if plural == nil { - continue - } - - trans = append(trans, translation{ - Locale: locale.Locale(), - Key: k.(string), - Translation: plural.text, - PluralType: rangeType, - PluralRule: locales.PluralRule(i).String(), - }) - } - } - - switch format { - case FormatJSON: - b, err = json.MarshalIndent(trans, "", " ") - ext = ".json" - } - - if err != nil { - return err - } - - err = ioutil.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0644) - if err != nil { - return err - } - - trans = trans[0:0] - } - - return nil -} - -// Import reads the translations out of a file or directory on disk. -// -// NOTE: this currently only works with string or int translations keys. -func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilename string) error { - - fi, err := os.Stat(dirnameOrFilename) - if err != nil { - return err - } - - processFn := func(filename string) error { - - f, err := os.Open(filename) - if err != nil { - return err - } - defer f.Close() - - return t.ImportByReader(format, f) - } - - if !fi.IsDir() { - return processFn(dirnameOrFilename) - } - - // recursively go through directory - walker := func(path string, info os.FileInfo, err error) error { - - if info.IsDir() { - return nil - } - - switch format { - case FormatJSON: - // skip non JSON files - if filepath.Ext(info.Name()) != ".json" { - return nil - } - } - - return processFn(path) - } - - return filepath.Walk(dirnameOrFilename, walker) -} - -// ImportByReader imports the the translations found within the contents read from the supplied reader. -// -// NOTE: generally used when assets have been embedded into the binary and are already in memory. -func (t *UniversalTranslator) ImportByReader(format ImportExportFormat, reader io.Reader) error { - - b, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - - var trans []translation - - switch format { - case FormatJSON: - err = json.Unmarshal(b, &trans) - } - - if err != nil { - return err - } - - for _, tl := range trans { - - locale, found := t.FindTranslator(tl.Locale) - if !found { - return &ErrMissingLocale{locale: tl.Locale} - } - - pr := stringToPR(tl.PluralRule) - - if pr == locales.PluralRuleUnknown { - - err = locale.Add(tl.Key, tl.Translation, tl.OverrideExisting) - if err != nil { - return err - } - - continue - } - - switch tl.PluralType { - case cardinalType: - err = locale.AddCardinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) - case ordinalType: - err = locale.AddOrdinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) - case rangeType: - err = locale.AddRange(tl.Key, tl.Translation, pr, tl.OverrideExisting) - default: - return &ErrBadPluralDefinition{tl: tl} - } - - if err != nil { - return err - } - } - - return nil -} - -func stringToPR(s string) locales.PluralRule { - - switch s { - case "Zero": - return locales.PluralRuleZero - case "One": - return locales.PluralRuleOne - case "Two": - return locales.PluralRuleTwo - case "Few": - return locales.PluralRuleFew - case "Many": - return locales.PluralRuleMany - case "Other": - return locales.PluralRuleOther - default: - return locales.PluralRuleUnknown - } - -} diff --git a/vendor/github.com/go-playground/universal-translator/logo.png b/vendor/github.com/go-playground/universal-translator/logo.png deleted file mode 100644 index a37aa8c..0000000 Binary files a/vendor/github.com/go-playground/universal-translator/logo.png and /dev/null differ diff --git a/vendor/github.com/go-playground/universal-translator/translator.go b/vendor/github.com/go-playground/universal-translator/translator.go deleted file mode 100644 index 24b18db..0000000 --- a/vendor/github.com/go-playground/universal-translator/translator.go +++ /dev/null @@ -1,420 +0,0 @@ -package ut - -import ( - "fmt" - "strconv" - "strings" - - "github.com/go-playground/locales" -) - -const ( - paramZero = "{0}" - paramOne = "{1}" - unknownTranslation = "" -) - -// Translator is universal translators -// translator instance which is a thin wrapper -// around locales.Translator instance providing -// some extra functionality -type Translator interface { - locales.Translator - - // adds a normal translation for a particular language/locale - // {#} is the only replacement type accepted and are ad infinitum - // eg. one: '{0} day left' other: '{0} days left' - Add(key interface{}, text string, override bool) error - - // adds a cardinal plural translation for a particular language/locale - // {0} is the only replacement type accepted and only one variable is accepted as - // multiple cannot be used for a plural rule determination, unless it is a range; - // see AddRange below. - // eg. in locale 'en' one: '{0} day left' other: '{0} days left' - AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error - - // adds an ordinal plural translation for a particular language/locale - // {0} is the only replacement type accepted and only one variable is accepted as - // multiple cannot be used for a plural rule determination, unless it is a range; - // see AddRange below. - // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - // - 1st, 2nd, 3rd... - AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error - - // adds a range plural translation for a particular language/locale - // {0} and {1} are the only replacement types accepted and only these are accepted. - // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' - AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error - - // creates the translation for the locale given the 'key' and params passed in - T(key interface{}, params ...string) (string, error) - - // creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments - // and param passed in - C(key interface{}, num float64, digits uint64, param string) (string, error) - - // creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments - // and param passed in - O(key interface{}, num float64, digits uint64, param string) (string, error) - - // creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and - // 'digit2' arguments and 'param1' and 'param2' passed in - R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) - - // VerifyTranslations checks to ensures that no plural rules have been - // missed within the translations. - VerifyTranslations() error -} - -var _ Translator = new(translator) -var _ locales.Translator = new(translator) - -type translator struct { - locales.Translator - translations map[interface{}]*transText - cardinalTanslations map[interface{}][]*transText // array index is mapped to locales.PluralRule index + the locales.PluralRuleUnknown - ordinalTanslations map[interface{}][]*transText - rangeTanslations map[interface{}][]*transText -} - -type transText struct { - text string - indexes []int -} - -func newTranslator(trans locales.Translator) Translator { - return &translator{ - Translator: trans, - translations: make(map[interface{}]*transText), // translation text broken up by byte index - cardinalTanslations: make(map[interface{}][]*transText), - ordinalTanslations: make(map[interface{}][]*transText), - rangeTanslations: make(map[interface{}][]*transText), - } -} - -// Add adds a normal translation for a particular language/locale -// {#} is the only replacement type accepted and are ad infinitum -// eg. one: '{0} day left' other: '{0} days left' -func (t *translator) Add(key interface{}, text string, override bool) error { - - if _, ok := t.translations[key]; ok && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text} - } - - lb := strings.Count(text, "{") - rb := strings.Count(text, "}") - - if lb != rb { - return &ErrMissingBracket{locale: t.Locale(), key: key, text: text} - } - - trans := &transText{ - text: text, - } - - var idx int - - for i := 0; i < lb; i++ { - s := "{" + strconv.Itoa(i) + "}" - idx = strings.Index(text, s) - if idx == -1 { - return &ErrBadParamSyntax{locale: t.Locale(), param: s, key: key, text: text} - } - - trans.indexes = append(trans.indexes, idx) - trans.indexes = append(trans.indexes, idx+len(s)) - } - - t.translations[key] = trans - - return nil -} - -// AddCardinal adds a cardinal plural translation for a particular language/locale -// {0} is the only replacement type accepted and only one variable is accepted as -// multiple cannot be used for a plural rule determination, unless it is a range; -// see AddRange below. -// eg. in locale 'en' one: '{0} day left' other: '{0} days left' -func (t *translator) AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error { - - var verified bool - - // verify plural rule exists for locale - for _, pr := range t.PluralsCardinal() { - if pr == rule { - verified = true - break - } - } - - if !verified { - return &ErrCardinalTranslation{text: fmt.Sprintf("error: cardinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} - } - - tarr, ok := t.cardinalTanslations[key] - if ok { - // verify not adding a conflicting record - if len(tarr) > 0 && tarr[rule] != nil && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} - } - - } else { - tarr = make([]*transText, 7) - t.cardinalTanslations[key] = tarr - } - - trans := &transText{ - text: text, - indexes: make([]int, 2), - } - - tarr[rule] = trans - - idx := strings.Index(text, paramZero) - if idx == -1 { - tarr[rule] = nil - return &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} - } - - trans.indexes[0] = idx - trans.indexes[1] = idx + len(paramZero) - - return nil -} - -// AddOrdinal adds an ordinal plural translation for a particular language/locale -// {0} is the only replacement type accepted and only one variable is accepted as -// multiple cannot be used for a plural rule determination, unless it is a range; -// see AddRange below. -// eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd... -func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error { - - var verified bool - - // verify plural rule exists for locale - for _, pr := range t.PluralsOrdinal() { - if pr == rule { - verified = true - break - } - } - - if !verified { - return &ErrOrdinalTranslation{text: fmt.Sprintf("error: ordinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} - } - - tarr, ok := t.ordinalTanslations[key] - if ok { - // verify not adding a conflicting record - if len(tarr) > 0 && tarr[rule] != nil && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} - } - - } else { - tarr = make([]*transText, 7) - t.ordinalTanslations[key] = tarr - } - - trans := &transText{ - text: text, - indexes: make([]int, 2), - } - - tarr[rule] = trans - - idx := strings.Index(text, paramZero) - if idx == -1 { - tarr[rule] = nil - return &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} - } - - trans.indexes[0] = idx - trans.indexes[1] = idx + len(paramZero) - - return nil -} - -// AddRange adds a range plural translation for a particular language/locale -// {0} and {1} are the only replacement types accepted and only these are accepted. -// eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' -func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error { - - var verified bool - - // verify plural rule exists for locale - for _, pr := range t.PluralsRange() { - if pr == rule { - verified = true - break - } - } - - if !verified { - return &ErrRangeTranslation{text: fmt.Sprintf("error: range plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} - } - - tarr, ok := t.rangeTanslations[key] - if ok { - // verify not adding a conflicting record - if len(tarr) > 0 && tarr[rule] != nil && !override { - return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} - } - - } else { - tarr = make([]*transText, 7) - t.rangeTanslations[key] = tarr - } - - trans := &transText{ - text: text, - indexes: make([]int, 4), - } - - tarr[rule] = trans - - idx := strings.Index(text, paramZero) - if idx == -1 { - tarr[rule] = nil - return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} - } - - trans.indexes[0] = idx - trans.indexes[1] = idx + len(paramZero) - - idx = strings.Index(text, paramOne) - if idx == -1 { - tarr[rule] = nil - return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%v' text: '%s'", paramOne, t.Locale(), key, text)} - } - - trans.indexes[2] = idx - trans.indexes[3] = idx + len(paramOne) - - return nil -} - -// T creates the translation for the locale given the 'key' and params passed in -func (t *translator) T(key interface{}, params ...string) (string, error) { - - trans, ok := t.translations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - b := make([]byte, 0, 64) - - var start, end, count int - - for i := 0; i < len(trans.indexes); i++ { - end = trans.indexes[i] - b = append(b, trans.text[start:end]...) - b = append(b, params[count]...) - i++ - start = trans.indexes[i] - count++ - } - - b = append(b, trans.text[start:]...) - - return string(b), nil -} - -// C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in -func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { - - tarr, ok := t.cardinalTanslations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - rule := t.CardinalPluralRule(num, digits) - - trans := tarr[rule] - - b := make([]byte, 0, 64) - b = append(b, trans.text[:trans.indexes[0]]...) - b = append(b, param...) - b = append(b, trans.text[trans.indexes[1]:]...) - - return string(b), nil -} - -// O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in -func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { - - tarr, ok := t.ordinalTanslations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - rule := t.OrdinalPluralRule(num, digits) - - trans := tarr[rule] - - b := make([]byte, 0, 64) - b = append(b, trans.text[:trans.indexes[0]]...) - b = append(b, param...) - b = append(b, trans.text[trans.indexes[1]:]...) - - return string(b), nil -} - -// R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments -// and 'param1' and 'param2' passed in -func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { - - tarr, ok := t.rangeTanslations[key] - if !ok { - return unknownTranslation, ErrUnknowTranslation - } - - rule := t.RangePluralRule(num1, digits1, num2, digits2) - - trans := tarr[rule] - - b := make([]byte, 0, 64) - b = append(b, trans.text[:trans.indexes[0]]...) - b = append(b, param1...) - b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...) - b = append(b, param2...) - b = append(b, trans.text[trans.indexes[3]:]...) - - return string(b), nil -} - -// VerifyTranslations checks to ensures that no plural rules have been -// missed within the translations. -func (t *translator) VerifyTranslations() error { - - for k, v := range t.cardinalTanslations { - - for _, rule := range t.PluralsCardinal() { - - if v[rule] == nil { - return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} - } - } - } - - for k, v := range t.ordinalTanslations { - - for _, rule := range t.PluralsOrdinal() { - - if v[rule] == nil { - return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} - } - } - } - - for k, v := range t.rangeTanslations { - - for _, rule := range t.PluralsRange() { - - if v[rule] == nil { - return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} - } - } - } - - return nil -} diff --git a/vendor/github.com/go-playground/universal-translator/universal_translator.go b/vendor/github.com/go-playground/universal-translator/universal_translator.go deleted file mode 100644 index dbf707f..0000000 --- a/vendor/github.com/go-playground/universal-translator/universal_translator.go +++ /dev/null @@ -1,113 +0,0 @@ -package ut - -import ( - "strings" - - "github.com/go-playground/locales" -) - -// UniversalTranslator holds all locale & translation data -type UniversalTranslator struct { - translators map[string]Translator - fallback Translator -} - -// New returns a new UniversalTranslator instance set with -// the fallback locale and locales it should support -func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { - - t := &UniversalTranslator{ - translators: make(map[string]Translator), - } - - for _, v := range supportedLocales { - - trans := newTranslator(v) - t.translators[strings.ToLower(trans.Locale())] = trans - - if fallback.Locale() == v.Locale() { - t.fallback = trans - } - } - - if t.fallback == nil && fallback != nil { - t.fallback = newTranslator(fallback) - } - - return t -} - -// FindTranslator trys to find a Translator based on an array of locales -// and returns the first one it can find, otherwise returns the -// fallback translator. -func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { - - for _, locale := range locales { - - if trans, found = t.translators[strings.ToLower(locale)]; found { - return - } - } - - return t.fallback, false -} - -// GetTranslator returns the specified translator for the given locale, -// or fallback if not found -func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { - - if trans, found = t.translators[strings.ToLower(locale)]; found { - return - } - - return t.fallback, false -} - -// GetFallback returns the fallback locale -func (t *UniversalTranslator) GetFallback() Translator { - return t.fallback -} - -// AddTranslator adds the supplied translator, if it already exists the override param -// will be checked and if false an error will be returned, otherwise the translator will be -// overridden; if the fallback matches the supplied translator it will be overridden as well -// NOTE: this is normally only used when translator is embedded within a library -func (t *UniversalTranslator) AddTranslator(translator locales.Translator, override bool) error { - - lc := strings.ToLower(translator.Locale()) - _, ok := t.translators[lc] - if ok && !override { - return &ErrExistingTranslator{locale: translator.Locale()} - } - - trans := newTranslator(translator) - - if t.fallback.Locale() == translator.Locale() { - - // because it's optional to have a fallback, I don't impose that limitation - // don't know why you wouldn't but... - if !override { - return &ErrExistingTranslator{locale: translator.Locale()} - } - - t.fallback = trans - } - - t.translators[lc] = trans - - return nil -} - -// VerifyTranslations runs through all locales and identifies any issues -// eg. missing plural rules for a locale -func (t *UniversalTranslator) VerifyTranslations() (err error) { - - for _, trans := range t.translators { - err = trans.VerifyTranslations() - if err != nil { - return - } - } - - return -} diff --git a/vendor/github.com/go-playground/validator/v10/.gitignore b/vendor/github.com/go-playground/validator/v10/.gitignore deleted file mode 100644 index 6e43fac..0000000 --- a/vendor/github.com/go-playground/validator/v10/.gitignore +++ /dev/null @@ -1,30 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -bin - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof -*.test -*.out -*.txt -cover.html -README.html diff --git a/vendor/github.com/go-playground/validator/v10/LICENSE b/vendor/github.com/go-playground/validator/v10/LICENSE deleted file mode 100644 index 6a2ae9a..0000000 --- a/vendor/github.com/go-playground/validator/v10/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Dean Karn - -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/go-playground/validator/v10/MAINTAINERS.md b/vendor/github.com/go-playground/validator/v10/MAINTAINERS.md deleted file mode 100644 index b809c4c..0000000 --- a/vendor/github.com/go-playground/validator/v10/MAINTAINERS.md +++ /dev/null @@ -1,16 +0,0 @@ -## Maintainers Guide - -### Semantic Versioning -Semantic versioning as defined [here](https://semver.org) must be strictly adhered to. - -### External Dependencies -Any new external dependencies MUST: -- Have a compatible LICENSE present. -- Be actively maintained. -- Be approved by @go-playground/admins - -### PR Merge Requirements -- Up-to-date branch. -- Passing tests and linting. -- CODEOWNERS approval. -- Tests that cover both the Happy and Unhappy paths. \ No newline at end of file diff --git a/vendor/github.com/go-playground/validator/v10/Makefile b/vendor/github.com/go-playground/validator/v10/Makefile deleted file mode 100644 index ec3455b..0000000 --- a/vendor/github.com/go-playground/validator/v10/Makefile +++ /dev/null @@ -1,18 +0,0 @@ -GOCMD=GO111MODULE=on go - -linters-install: - @golangci-lint --version >/dev/null 2>&1 || { \ - echo "installing linting tools..."; \ - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.41.1; \ - } - -lint: linters-install - golangci-lint run - -test: - $(GOCMD) test -cover -race ./... - -bench: - $(GOCMD) test -bench=. -benchmem ./... - -.PHONY: test lint linters-install \ No newline at end of file diff --git a/vendor/github.com/go-playground/validator/v10/README.md b/vendor/github.com/go-playground/validator/v10/README.md deleted file mode 100644 index 9d0a79e..0000000 --- a/vendor/github.com/go-playground/validator/v10/README.md +++ /dev/null @@ -1,338 +0,0 @@ -Package validator -================= -[![Join the chat at https://gitter.im/go-playground/validator](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-playground/validator?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -![Project status](https://img.shields.io/badge/version-10.11.1-green.svg) -[![Build Status](https://travis-ci.org/go-playground/validator.svg?branch=master)](https://travis-ci.org/go-playground/validator) -[![Coverage Status](https://coveralls.io/repos/go-playground/validator/badge.svg?branch=master&service=github)](https://coveralls.io/github/go-playground/validator?branch=master) -[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/validator)](https://goreportcard.com/report/github.com/go-playground/validator) -[![GoDoc](https://godoc.org/github.com/go-playground/validator?status.svg)](https://pkg.go.dev/github.com/go-playground/validator/v10) -![License](https://img.shields.io/dub/l/vibe-d.svg) - -Package validator implements value validations for structs and individual fields based on tags. - -It has the following **unique** features: - -- Cross Field and Cross Struct validations by using validation tags or custom validators. -- Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated. -- Ability to dive into both map keys and values for validation -- Handles type interface by determining it's underlying type prior to validation. -- Handles custom field types such as sql driver Valuer see [Valuer](https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29) -- Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs -- Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError -- Customizable i18n aware error messages. -- Default validator for the [gin](https://github.com/gin-gonic/gin) web framework; upgrading from v8 to v9 in gin see [here](https://github.com/go-playground/validator/tree/master/_examples/gin-upgrading-overriding) - -Installation ------------- - -Use go get. - - go get github.com/go-playground/validator/v10 - -Then import the validator package into your own code. - - import "github.com/go-playground/validator/v10" - -Error Return Value -------- - -Validation functions return type error - -They return type error to avoid the issue discussed in the following, where err is always != nil: - -* http://stackoverflow.com/a/29138676/3158232 -* https://github.com/go-playground/validator/issues/134 - -Validator returns only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so: - -```go -err := validate.Struct(mystruct) -validationErrors := err.(validator.ValidationErrors) - ``` - -Usage and documentation ------- - -Please see https://pkg.go.dev/github.com/go-playground/validator/v10 for detailed usage docs. - -##### Examples: - -- [Simple](https://github.com/go-playground/validator/blob/master/_examples/simple/main.go) -- [Custom Field Types](https://github.com/go-playground/validator/blob/master/_examples/custom/main.go) -- [Struct Level](https://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go) -- [Translations & Custom Errors](https://github.com/go-playground/validator/blob/master/_examples/translations/main.go) -- [Gin upgrade and/or override validator](https://github.com/go-playground/validator/tree/v9/_examples/gin-upgrading-overriding) -- [wash - an example application putting it all together](https://github.com/bluesuncorp/wash) - -Baked-in Validations ------- - -### Fields: - -| Tag | Description | -| - | - | -| eqcsfield | Field Equals Another Field (relative)| -| eqfield | Field Equals Another Field | -| fieldcontains | NOT DOCUMENTED IN doc.go | -| fieldexcludes | NOT DOCUMENTED IN doc.go | -| gtcsfield | Field Greater Than Another Relative Field | -| gtecsfield | Field Greater Than or Equal To Another Relative Field | -| gtefield | Field Greater Than or Equal To Another Field | -| gtfield | Field Greater Than Another Field | -| ltcsfield | Less Than Another Relative Field | -| ltecsfield | Less Than or Equal To Another Relative Field | -| ltefield | Less Than or Equal To Another Field | -| ltfield | Less Than Another Field | -| necsfield | Field Does Not Equal Another Field (relative) | -| nefield | Field Does Not Equal Another Field | - -### Network: - -| Tag | Description | -| - | - | -| cidr | Classless Inter-Domain Routing CIDR | -| cidrv4 | Classless Inter-Domain Routing CIDRv4 | -| cidrv6 | Classless Inter-Domain Routing CIDRv6 | -| datauri | Data URL | -| fqdn | Full Qualified Domain Name (FQDN) | -| hostname | Hostname RFC 952 | -| hostname_port | HostPort | -| hostname_rfc1123 | Hostname RFC 1123 | -| ip | Internet Protocol Address IP | -| ip4_addr | Internet Protocol Address IPv4 | -| ip6_addr | Internet Protocol Address IPv6 | -| ip_addr | Internet Protocol Address IP | -| ipv4 | Internet Protocol Address IPv4 | -| ipv6 | Internet Protocol Address IPv6 | -| mac | Media Access Control Address MAC | -| tcp4_addr | Transmission Control Protocol Address TCPv4 | -| tcp6_addr | Transmission Control Protocol Address TCPv6 | -| tcp_addr | Transmission Control Protocol Address TCP | -| udp4_addr | User Datagram Protocol Address UDPv4 | -| udp6_addr | User Datagram Protocol Address UDPv6 | -| udp_addr | User Datagram Protocol Address UDP | -| unix_addr | Unix domain socket end point Address | -| uri | URI String | -| url | URL String | -| url_encoded | URL Encoded | -| urn_rfc2141 | Urn RFC 2141 String | - -### Strings: - -| Tag | Description | -| - | - | -| alpha | Alpha Only | -| alphanum | Alphanumeric | -| alphanumunicode | Alphanumeric Unicode | -| alphaunicode | Alpha Unicode | -| ascii | ASCII | -| boolean | Boolean | -| contains | Contains | -| containsany | Contains Any | -| containsrune | Contains Rune | -| endsnotwith | Ends Not With | -| endswith | Ends With | -| excludes | Excludes | -| excludesall | Excludes All | -| excludesrune | Excludes Rune | -| lowercase | Lowercase | -| multibyte | Multi-Byte Characters | -| number | NOT DOCUMENTED IN doc.go | -| numeric | Numeric | -| printascii | Printable ASCII | -| startsnotwith | Starts Not With | -| startswith | Starts With | -| uppercase | Uppercase | - -### Format: -| Tag | Description | -| - | - | -| base64 | Base64 String | -| base64url | Base64URL String | -| bic | Business Identifier Code (ISO 9362) | -| bcp47_language_tag | Language tag (BCP 47) | -| btc_addr | Bitcoin Address | -| btc_addr_bech32 | Bitcoin Bech32 Address (segwit) | -| credit_card | Credit Card Number | -| datetime | Datetime | -| e164 | e164 formatted phone number | -| email | E-mail String -| eth_addr | Ethereum Address | -| hexadecimal | Hexadecimal String | -| hexcolor | Hexcolor String | -| hsl | HSL String | -| hsla | HSLA String | -| html | HTML Tags | -| html_encoded | HTML Encoded | -| isbn | International Standard Book Number | -| isbn10 | International Standard Book Number 10 | -| isbn13 | International Standard Book Number 13 | -| iso3166_1_alpha2 | Two-letter country code (ISO 3166-1 alpha-2) | -| iso3166_1_alpha3 | Three-letter country code (ISO 3166-1 alpha-3) | -| iso3166_1_alpha_numeric | Numeric country code (ISO 3166-1 numeric) | -| iso3166_2 | Country subdivision code (ISO 3166-2) | -| iso4217 | Currency code (ISO 4217) | -| json | JSON | -| jwt | JSON Web Token (JWT) | -| latitude | Latitude | -| longitude | Longitude | -| postcode_iso3166_alpha2 | Postcode | -| postcode_iso3166_alpha2_field | Postcode | -| rgb | RGB String | -| rgba | RGBA String | -| ssn | Social Security Number SSN | -| timezone | Timezone | -| uuid | Universally Unique Identifier UUID | -| uuid3 | Universally Unique Identifier UUID v3 | -| uuid3_rfc4122 | Universally Unique Identifier UUID v3 RFC4122 | -| uuid4 | Universally Unique Identifier UUID v4 | -| uuid4_rfc4122 | Universally Unique Identifier UUID v4 RFC4122 | -| uuid5 | Universally Unique Identifier UUID v5 | -| uuid5_rfc4122 | Universally Unique Identifier UUID v5 RFC4122 | -| uuid_rfc4122 | Universally Unique Identifier UUID RFC4122 | -| md4 | MD4 hash | -| md5 | MD5 hash | -| sha256 | SHA256 hash | -| sha384 | SHA384 hash | -| sha512 | SHA512 hash | -| ripemd128 | RIPEMD-128 hash | -| ripemd128 | RIPEMD-160 hash | -| tiger128 | TIGER128 hash | -| tiger160 | TIGER160 hash | -| tiger192 | TIGER192 hash | -| semver | Semantic Versioning 2.0.0 | -| ulid | Universally Unique Lexicographically Sortable Identifier ULID | - -### Comparisons: -| Tag | Description | -| - | - | -| eq | Equals | -| gt | Greater than| -| gte | Greater than or equal | -| lt | Less Than | -| lte | Less Than or Equal | -| ne | Not Equal | - -### Other: -| Tag | Description | -| - | - | -| dir | Directory | -| file | File path | -| isdefault | Is Default | -| len | Length | -| max | Maximum | -| min | Minimum | -| oneof | One Of | -| required | Required | -| required_if | Required If | -| required_unless | Required Unless | -| required_with | Required With | -| required_with_all | Required With All | -| required_without | Required Without | -| required_without_all | Required Without All | -| excluded_if | Excluded If | -| excluded_unless | Excluded Unless | -| excluded_with | Excluded With | -| excluded_with_all | Excluded With All | -| excluded_without | Excluded Without | -| excluded_without_all | Excluded Without All | -| unique | Unique | - -#### Aliases: -| Tag | Description | -| - | - | -| iscolor | hexcolor\|rgb\|rgba\|hsl\|hsla | -| country_code | iso3166_1_alpha2\|iso3166_1_alpha3\|iso3166_1_alpha_numeric | - -Benchmarks ------- -###### Run on MacBook Pro (15-inch, 2017) go version go1.10.2 darwin/amd64 -```go -goos: darwin -goarch: amd64 -pkg: github.com/go-playground/validator -BenchmarkFieldSuccess-8 20000000 83.6 ns/op 0 B/op 0 allocs/op -BenchmarkFieldSuccessParallel-8 50000000 26.8 ns/op 0 B/op 0 allocs/op -BenchmarkFieldFailure-8 5000000 291 ns/op 208 B/op 4 allocs/op -BenchmarkFieldFailureParallel-8 20000000 107 ns/op 208 B/op 4 allocs/op -BenchmarkFieldArrayDiveSuccess-8 2000000 623 ns/op 201 B/op 11 allocs/op -BenchmarkFieldArrayDiveSuccessParallel-8 10000000 237 ns/op 201 B/op 11 allocs/op -BenchmarkFieldArrayDiveFailure-8 2000000 859 ns/op 412 B/op 16 allocs/op -BenchmarkFieldArrayDiveFailureParallel-8 5000000 335 ns/op 413 B/op 16 allocs/op -BenchmarkFieldMapDiveSuccess-8 1000000 1292 ns/op 432 B/op 18 allocs/op -BenchmarkFieldMapDiveSuccessParallel-8 3000000 467 ns/op 432 B/op 18 allocs/op -BenchmarkFieldMapDiveFailure-8 1000000 1082 ns/op 512 B/op 16 allocs/op -BenchmarkFieldMapDiveFailureParallel-8 5000000 425 ns/op 512 B/op 16 allocs/op -BenchmarkFieldMapDiveWithKeysSuccess-8 1000000 1539 ns/op 480 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysSuccessParallel-8 3000000 613 ns/op 480 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysFailure-8 1000000 1413 ns/op 721 B/op 21 allocs/op -BenchmarkFieldMapDiveWithKeysFailureParallel-8 3000000 575 ns/op 721 B/op 21 allocs/op -BenchmarkFieldCustomTypeSuccess-8 10000000 216 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeSuccessParallel-8 20000000 82.2 ns/op 32 B/op 2 allocs/op -BenchmarkFieldCustomTypeFailure-8 5000000 274 ns/op 208 B/op 4 allocs/op -BenchmarkFieldCustomTypeFailureParallel-8 20000000 116 ns/op 208 B/op 4 allocs/op -BenchmarkFieldOrTagSuccess-8 2000000 740 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagSuccessParallel-8 3000000 474 ns/op 16 B/op 1 allocs/op -BenchmarkFieldOrTagFailure-8 3000000 471 ns/op 224 B/op 5 allocs/op -BenchmarkFieldOrTagFailureParallel-8 3000000 414 ns/op 224 B/op 5 allocs/op -BenchmarkStructLevelValidationSuccess-8 10000000 213 ns/op 32 B/op 2 allocs/op -BenchmarkStructLevelValidationSuccessParallel-8 20000000 91.8 ns/op 32 B/op 2 allocs/op -BenchmarkStructLevelValidationFailure-8 3000000 473 ns/op 304 B/op 8 allocs/op -BenchmarkStructLevelValidationFailureParallel-8 10000000 234 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCustomTypeSuccess-8 5000000 385 ns/op 32 B/op 2 allocs/op -BenchmarkStructSimpleCustomTypeSuccessParallel-8 10000000 161 ns/op 32 B/op 2 allocs/op -BenchmarkStructSimpleCustomTypeFailure-8 2000000 640 ns/op 424 B/op 9 allocs/op -BenchmarkStructSimpleCustomTypeFailureParallel-8 5000000 318 ns/op 440 B/op 10 allocs/op -BenchmarkStructFilteredSuccess-8 2000000 597 ns/op 288 B/op 9 allocs/op -BenchmarkStructFilteredSuccessParallel-8 10000000 266 ns/op 288 B/op 9 allocs/op -BenchmarkStructFilteredFailure-8 3000000 454 ns/op 256 B/op 7 allocs/op -BenchmarkStructFilteredFailureParallel-8 10000000 214 ns/op 256 B/op 7 allocs/op -BenchmarkStructPartialSuccess-8 3000000 502 ns/op 256 B/op 6 allocs/op -BenchmarkStructPartialSuccessParallel-8 10000000 225 ns/op 256 B/op 6 allocs/op -BenchmarkStructPartialFailure-8 2000000 702 ns/op 480 B/op 11 allocs/op -BenchmarkStructPartialFailureParallel-8 5000000 329 ns/op 480 B/op 11 allocs/op -BenchmarkStructExceptSuccess-8 2000000 793 ns/op 496 B/op 12 allocs/op -BenchmarkStructExceptSuccessParallel-8 10000000 193 ns/op 240 B/op 5 allocs/op -BenchmarkStructExceptFailure-8 2000000 639 ns/op 464 B/op 10 allocs/op -BenchmarkStructExceptFailureParallel-8 5000000 300 ns/op 464 B/op 10 allocs/op -BenchmarkStructSimpleCrossFieldSuccess-8 3000000 417 ns/op 72 B/op 3 allocs/op -BenchmarkStructSimpleCrossFieldSuccessParallel-8 10000000 163 ns/op 72 B/op 3 allocs/op -BenchmarkStructSimpleCrossFieldFailure-8 2000000 645 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCrossFieldFailureParallel-8 5000000 285 ns/op 304 B/op 8 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccess-8 3000000 588 ns/op 80 B/op 4 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldSuccessParallel-8 10000000 221 ns/op 80 B/op 4 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailure-8 2000000 868 ns/op 320 B/op 9 allocs/op -BenchmarkStructSimpleCrossStructCrossFieldFailureParallel-8 5000000 337 ns/op 320 B/op 9 allocs/op -BenchmarkStructSimpleSuccess-8 5000000 260 ns/op 0 B/op 0 allocs/op -BenchmarkStructSimpleSuccessParallel-8 20000000 90.6 ns/op 0 B/op 0 allocs/op -BenchmarkStructSimpleFailure-8 2000000 619 ns/op 424 B/op 9 allocs/op -BenchmarkStructSimpleFailureParallel-8 5000000 296 ns/op 424 B/op 9 allocs/op -BenchmarkStructComplexSuccess-8 1000000 1454 ns/op 128 B/op 8 allocs/op -BenchmarkStructComplexSuccessParallel-8 3000000 579 ns/op 128 B/op 8 allocs/op -BenchmarkStructComplexFailure-8 300000 4140 ns/op 3041 B/op 53 allocs/op -BenchmarkStructComplexFailureParallel-8 1000000 2127 ns/op 3041 B/op 53 allocs/op -BenchmarkOneof-8 10000000 140 ns/op 0 B/op 0 allocs/op -BenchmarkOneofParallel-8 20000000 70.1 ns/op 0 B/op 0 allocs/op -``` - -Complementary Software ----------------------- - -Here is a list of software that complements using this library either pre or post validation. - -* [form](https://github.com/go-playground/form) - Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support. -* [mold](https://github.com/go-playground/mold) - A general library to help modify or set data within data structures and other objects - -How to Contribute ------- - -Make a pull request... - -License -------- -Distributed under MIT License, please see license file within the code for more details. - -Maintainers ------------ -This project has grown large enough that more than one person is required to properly support the community. -If you are interested in becoming a maintainer please reach out to me https://github.com/deankarn diff --git a/vendor/github.com/go-playground/validator/v10/baked_in.go b/vendor/github.com/go-playground/validator/v10/baked_in.go deleted file mode 100644 index c9b1db4..0000000 --- a/vendor/github.com/go-playground/validator/v10/baked_in.go +++ /dev/null @@ -1,2526 +0,0 @@ -package validator - -import ( - "bytes" - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "net" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "sync" - "time" - "unicode/utf8" - - "golang.org/x/crypto/sha3" - "golang.org/x/text/language" - - urn "github.com/leodido/go-urn" -) - -// Func accepts a FieldLevel interface for all validation needs. The return -// value should be true when validation succeeds. -type Func func(fl FieldLevel) bool - -// FuncCtx accepts a context.Context and FieldLevel interface for all -// validation needs. The return value should be true when validation succeeds. -type FuncCtx func(ctx context.Context, fl FieldLevel) bool - -// wrapFunc wraps noramal Func makes it compatible with FuncCtx -func wrapFunc(fn Func) FuncCtx { - if fn == nil { - return nil // be sure not to wrap a bad function. - } - return func(ctx context.Context, fl FieldLevel) bool { - return fn(fl) - } -} - -var ( - restrictedTags = map[string]struct{}{ - diveTag: {}, - keysTag: {}, - endKeysTag: {}, - structOnlyTag: {}, - omitempty: {}, - skipValidationTag: {}, - utf8HexComma: {}, - utf8Pipe: {}, - noStructLevelTag: {}, - requiredTag: {}, - isdefault: {}, - } - - // bakedInAliases is a default mapping of a single validation tag that - // defines a common or complex set of validation(s) to simplify - // adding validation to structs. - bakedInAliases = map[string]string{ - "iscolor": "hexcolor|rgb|rgba|hsl|hsla", - "country_code": "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric", - } - - // bakedInValidators is the default map of ValidationFunc - // you can add, remove or even replace items to suite your needs, - // or even disregard and use your own map if so desired. - bakedInValidators = map[string]Func{ - "required": hasValue, - "required_if": requiredIf, - "required_unless": requiredUnless, - "required_with": requiredWith, - "required_with_all": requiredWithAll, - "required_without": requiredWithout, - "required_without_all": requiredWithoutAll, - "excluded_if": excludedIf, - "excluded_unless": excludedUnless, - "excluded_with": excludedWith, - "excluded_with_all": excludedWithAll, - "excluded_without": excludedWithout, - "excluded_without_all": excludedWithoutAll, - "isdefault": isDefault, - "len": hasLengthOf, - "min": hasMinOf, - "max": hasMaxOf, - "eq": isEq, - "ne": isNe, - "lt": isLt, - "lte": isLte, - "gt": isGt, - "gte": isGte, - "eqfield": isEqField, - "eqcsfield": isEqCrossStructField, - "necsfield": isNeCrossStructField, - "gtcsfield": isGtCrossStructField, - "gtecsfield": isGteCrossStructField, - "ltcsfield": isLtCrossStructField, - "ltecsfield": isLteCrossStructField, - "nefield": isNeField, - "gtefield": isGteField, - "gtfield": isGtField, - "ltefield": isLteField, - "ltfield": isLtField, - "fieldcontains": fieldContains, - "fieldexcludes": fieldExcludes, - "alpha": isAlpha, - "alphanum": isAlphanum, - "alphaunicode": isAlphaUnicode, - "alphanumunicode": isAlphanumUnicode, - "boolean": isBoolean, - "numeric": isNumeric, - "number": isNumber, - "hexadecimal": isHexadecimal, - "hexcolor": isHEXColor, - "rgb": isRGB, - "rgba": isRGBA, - "hsl": isHSL, - "hsla": isHSLA, - "e164": isE164, - "email": isEmail, - "url": isURL, - "uri": isURI, - "urn_rfc2141": isUrnRFC2141, // RFC 2141 - "file": isFile, - "base64": isBase64, - "base64url": isBase64URL, - "contains": contains, - "containsany": containsAny, - "containsrune": containsRune, - "excludes": excludes, - "excludesall": excludesAll, - "excludesrune": excludesRune, - "startswith": startsWith, - "endswith": endsWith, - "startsnotwith": startsNotWith, - "endsnotwith": endsNotWith, - "isbn": isISBN, - "isbn10": isISBN10, - "isbn13": isISBN13, - "eth_addr": isEthereumAddress, - "btc_addr": isBitcoinAddress, - "btc_addr_bech32": isBitcoinBech32Address, - "uuid": isUUID, - "uuid3": isUUID3, - "uuid4": isUUID4, - "uuid5": isUUID5, - "uuid_rfc4122": isUUIDRFC4122, - "uuid3_rfc4122": isUUID3RFC4122, - "uuid4_rfc4122": isUUID4RFC4122, - "uuid5_rfc4122": isUUID5RFC4122, - "ulid": isULID, - "md4": isMD4, - "md5": isMD5, - "sha256": isSHA256, - "sha384": isSHA384, - "sha512": isSHA512, - "ripemd128": isRIPEMD128, - "ripemd160": isRIPEMD160, - "tiger128": isTIGER128, - "tiger160": isTIGER160, - "tiger192": isTIGER192, - "ascii": isASCII, - "printascii": isPrintableASCII, - "multibyte": hasMultiByteCharacter, - "datauri": isDataURI, - "latitude": isLatitude, - "longitude": isLongitude, - "ssn": isSSN, - "ipv4": isIPv4, - "ipv6": isIPv6, - "ip": isIP, - "cidrv4": isCIDRv4, - "cidrv6": isCIDRv6, - "cidr": isCIDR, - "tcp4_addr": isTCP4AddrResolvable, - "tcp6_addr": isTCP6AddrResolvable, - "tcp_addr": isTCPAddrResolvable, - "udp4_addr": isUDP4AddrResolvable, - "udp6_addr": isUDP6AddrResolvable, - "udp_addr": isUDPAddrResolvable, - "ip4_addr": isIP4AddrResolvable, - "ip6_addr": isIP6AddrResolvable, - "ip_addr": isIPAddrResolvable, - "unix_addr": isUnixAddrResolvable, - "mac": isMAC, - "hostname": isHostnameRFC952, // RFC 952 - "hostname_rfc1123": isHostnameRFC1123, // RFC 1123 - "fqdn": isFQDN, - "unique": isUnique, - "oneof": isOneOf, - "html": isHTML, - "html_encoded": isHTMLEncoded, - "url_encoded": isURLEncoded, - "dir": isDir, - "json": isJSON, - "jwt": isJWT, - "hostname_port": isHostnamePort, - "lowercase": isLowercase, - "uppercase": isUppercase, - "datetime": isDatetime, - "timezone": isTimeZone, - "iso3166_1_alpha2": isIso3166Alpha2, - "iso3166_1_alpha3": isIso3166Alpha3, - "iso3166_1_alpha_numeric": isIso3166AlphaNumeric, - "iso3166_2": isIso31662, - "iso4217": isIso4217, - "iso4217_numeric": isIso4217Numeric, - "bcp47_language_tag": isBCP47LanguageTag, - "postcode_iso3166_alpha2": isPostcodeByIso3166Alpha2, - "postcode_iso3166_alpha2_field": isPostcodeByIso3166Alpha2Field, - "bic": isIsoBicFormat, - "semver": isSemverFormat, - "dns_rfc1035_label": isDnsRFC1035LabelFormat, - "credit_card": isCreditCard, - } -) - -var ( - oneofValsCache = map[string][]string{} - oneofValsCacheRWLock = sync.RWMutex{} -) - -func parseOneOfParam2(s string) []string { - oneofValsCacheRWLock.RLock() - vals, ok := oneofValsCache[s] - oneofValsCacheRWLock.RUnlock() - if !ok { - oneofValsCacheRWLock.Lock() - vals = splitParamsRegex.FindAllString(s, -1) - for i := 0; i < len(vals); i++ { - vals[i] = strings.Replace(vals[i], "'", "", -1) - } - oneofValsCache[s] = vals - oneofValsCacheRWLock.Unlock() - } - return vals -} - -func isURLEncoded(fl FieldLevel) bool { - return uRLEncodedRegex.MatchString(fl.Field().String()) -} - -func isHTMLEncoded(fl FieldLevel) bool { - return hTMLEncodedRegex.MatchString(fl.Field().String()) -} - -func isHTML(fl FieldLevel) bool { - return hTMLRegex.MatchString(fl.Field().String()) -} - -func isOneOf(fl FieldLevel) bool { - vals := parseOneOfParam2(fl.Param()) - - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - for i := 0; i < len(vals); i++ { - if vals[i] == v { - return true - } - } - return false -} - -// isUnique is the validation function for validating if each array|slice|map value is unique -func isUnique(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - v := reflect.ValueOf(struct{}{}) - - switch field.Kind() { - case reflect.Slice, reflect.Array: - elem := field.Type().Elem() - if elem.Kind() == reflect.Ptr { - elem = elem.Elem() - } - - if param == "" { - m := reflect.MakeMap(reflect.MapOf(elem, v.Type())) - - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(reflect.Indirect(field.Index(i)), v) - } - return field.Len() == m.Len() - } - - sf, ok := elem.FieldByName(param) - if !ok { - panic(fmt.Sprintf("Bad field name %s", param)) - } - - sfTyp := sf.Type - if sfTyp.Kind() == reflect.Ptr { - sfTyp = sfTyp.Elem() - } - - m := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type())) - for i := 0; i < field.Len(); i++ { - m.SetMapIndex(reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param)), v) - } - return field.Len() == m.Len() - case reflect.Map: - m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) - - for _, k := range field.MapKeys() { - m.SetMapIndex(field.MapIndex(k), v) - } - return field.Len() == m.Len() - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } -} - -// isMAC is the validation function for validating if the field's value is a valid MAC address. -func isMAC(fl FieldLevel) bool { - _, err := net.ParseMAC(fl.Field().String()) - - return err == nil -} - -// isCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address. -func isCIDRv4(fl FieldLevel) bool { - ip, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil && ip.To4() != nil -} - -// isCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address. -func isCIDRv6(fl FieldLevel) bool { - ip, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil && ip.To4() == nil -} - -// isCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address. -func isCIDR(fl FieldLevel) bool { - _, _, err := net.ParseCIDR(fl.Field().String()) - - return err == nil -} - -// isIPv4 is the validation function for validating if a value is a valid v4 IP address. -func isIPv4(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) - - return ip != nil && ip.To4() != nil -} - -// isIPv6 is the validation function for validating if the field's value is a valid v6 IP address. -func isIPv6(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) - - return ip != nil && ip.To4() == nil -} - -// isIP is the validation function for validating if the field's value is a valid v4 or v6 IP address. -func isIP(fl FieldLevel) bool { - ip := net.ParseIP(fl.Field().String()) - - return ip != nil -} - -// isSSN is the validation function for validating if the field's value is a valid SSN. -func isSSN(fl FieldLevel) bool { - field := fl.Field() - - if field.Len() != 11 { - return false - } - - return sSNRegex.MatchString(field.String()) -} - -// isLongitude is the validation function for validating if the field's value is a valid longitude coordinate. -func isLongitude(fl FieldLevel) bool { - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', -1, 32) - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', -1, 64) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - - return longitudeRegex.MatchString(v) -} - -// isLatitude is the validation function for validating if the field's value is a valid latitude coordinate. -func isLatitude(fl FieldLevel) bool { - field := fl.Field() - - var v string - switch field.Kind() { - case reflect.String: - v = field.String() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - v = strconv.FormatInt(field.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - v = strconv.FormatUint(field.Uint(), 10) - case reflect.Float32: - v = strconv.FormatFloat(field.Float(), 'f', -1, 32) - case reflect.Float64: - v = strconv.FormatFloat(field.Float(), 'f', -1, 64) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - - return latitudeRegex.MatchString(v) -} - -// isDataURI is the validation function for validating if the field's value is a valid data URI. -func isDataURI(fl FieldLevel) bool { - uri := strings.SplitN(fl.Field().String(), ",", 2) - - if len(uri) != 2 { - return false - } - - if !dataURIRegex.MatchString(uri[0]) { - return false - } - - return base64Regex.MatchString(uri[1]) -} - -// hasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character. -func hasMultiByteCharacter(fl FieldLevel) bool { - field := fl.Field() - - if field.Len() == 0 { - return true - } - - return multibyteRegex.MatchString(field.String()) -} - -// isPrintableASCII is the validation function for validating if the field's value is a valid printable ASCII character. -func isPrintableASCII(fl FieldLevel) bool { - return printableASCIIRegex.MatchString(fl.Field().String()) -} - -// isASCII is the validation function for validating if the field's value is a valid ASCII character. -func isASCII(fl FieldLevel) bool { - return aSCIIRegex.MatchString(fl.Field().String()) -} - -// isUUID5 is the validation function for validating if the field's value is a valid v5 UUID. -func isUUID5(fl FieldLevel) bool { - return uUID5Regex.MatchString(fl.Field().String()) -} - -// isUUID4 is the validation function for validating if the field's value is a valid v4 UUID. -func isUUID4(fl FieldLevel) bool { - return uUID4Regex.MatchString(fl.Field().String()) -} - -// isUUID3 is the validation function for validating if the field's value is a valid v3 UUID. -func isUUID3(fl FieldLevel) bool { - return uUID3Regex.MatchString(fl.Field().String()) -} - -// isUUID is the validation function for validating if the field's value is a valid UUID of any version. -func isUUID(fl FieldLevel) bool { - return uUIDRegex.MatchString(fl.Field().String()) -} - -// isUUID5RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v5 UUID. -func isUUID5RFC4122(fl FieldLevel) bool { - return uUID5RFC4122Regex.MatchString(fl.Field().String()) -} - -// isUUID4RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v4 UUID. -func isUUID4RFC4122(fl FieldLevel) bool { - return uUID4RFC4122Regex.MatchString(fl.Field().String()) -} - -// isUUID3RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v3 UUID. -func isUUID3RFC4122(fl FieldLevel) bool { - return uUID3RFC4122Regex.MatchString(fl.Field().String()) -} - -// isUUIDRFC4122 is the validation function for validating if the field's value is a valid RFC4122 UUID of any version. -func isUUIDRFC4122(fl FieldLevel) bool { - return uUIDRFC4122Regex.MatchString(fl.Field().String()) -} - -// isULID is the validation function for validating if the field's value is a valid ULID. -func isULID(fl FieldLevel) bool { - return uLIDRegex.MatchString(fl.Field().String()) -} - -// isMD4 is the validation function for validating if the field's value is a valid MD4. -func isMD4(fl FieldLevel) bool { - return md4Regex.MatchString(fl.Field().String()) -} - -// isMD5 is the validation function for validating if the field's value is a valid MD5. -func isMD5(fl FieldLevel) bool { - return md5Regex.MatchString(fl.Field().String()) -} - -// isSHA256 is the validation function for validating if the field's value is a valid SHA256. -func isSHA256(fl FieldLevel) bool { - return sha256Regex.MatchString(fl.Field().String()) -} - -// isSHA384 is the validation function for validating if the field's value is a valid SHA384. -func isSHA384(fl FieldLevel) bool { - return sha384Regex.MatchString(fl.Field().String()) -} - -// isSHA512 is the validation function for validating if the field's value is a valid SHA512. -func isSHA512(fl FieldLevel) bool { - return sha512Regex.MatchString(fl.Field().String()) -} - -// isRIPEMD128 is the validation function for validating if the field's value is a valid PIPEMD128. -func isRIPEMD128(fl FieldLevel) bool { - return ripemd128Regex.MatchString(fl.Field().String()) -} - -// isRIPEMD160 is the validation function for validating if the field's value is a valid PIPEMD160. -func isRIPEMD160(fl FieldLevel) bool { - return ripemd160Regex.MatchString(fl.Field().String()) -} - -// isTIGER128 is the validation function for validating if the field's value is a valid TIGER128. -func isTIGER128(fl FieldLevel) bool { - return tiger128Regex.MatchString(fl.Field().String()) -} - -// isTIGER160 is the validation function for validating if the field's value is a valid TIGER160. -func isTIGER160(fl FieldLevel) bool { - return tiger160Regex.MatchString(fl.Field().String()) -} - -// isTIGER192 is the validation function for validating if the field's value is a valid isTIGER192. -func isTIGER192(fl FieldLevel) bool { - return tiger192Regex.MatchString(fl.Field().String()) -} - -// isISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN. -func isISBN(fl FieldLevel) bool { - return isISBN10(fl) || isISBN13(fl) -} - -// isISBN13 is the validation function for validating if the field's value is a valid v13 ISBN. -func isISBN13(fl FieldLevel) bool { - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4) - - if !iSBN13Regex.MatchString(s) { - return false - } - - var checksum int32 - var i int32 - - factor := []int32{1, 3} - - for i = 0; i < 12; i++ { - checksum += factor[i%2] * int32(s[i]-'0') - } - - return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0 -} - -// isISBN10 is the validation function for validating if the field's value is a valid v10 ISBN. -func isISBN10(fl FieldLevel) bool { - s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3) - - if !iSBN10Regex.MatchString(s) { - return false - } - - var checksum int32 - var i int32 - - for i = 0; i < 9; i++ { - checksum += (i + 1) * int32(s[i]-'0') - } - - if s[9] == 'X' { - checksum += 10 * 10 - } else { - checksum += 10 * int32(s[9]-'0') - } - - return checksum%11 == 0 -} - -// isEthereumAddress is the validation function for validating if the field's value is a valid Ethereum address. -func isEthereumAddress(fl FieldLevel) bool { - address := fl.Field().String() - - if !ethAddressRegex.MatchString(address) { - return false - } - - if ethAddressRegexUpper.MatchString(address) || ethAddressRegexLower.MatchString(address) { - return true - } - - // Checksum validation. Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md - address = address[2:] // Skip "0x" prefix. - h := sha3.NewLegacyKeccak256() - // hash.Hash's io.Writer implementation says it never returns an error. https://golang.org/pkg/hash/#Hash - _, _ = h.Write([]byte(strings.ToLower(address))) - hash := hex.EncodeToString(h.Sum(nil)) - - for i := 0; i < len(address); i++ { - if address[i] <= '9' { // Skip 0-9 digits: they don't have upper/lower-case. - continue - } - if hash[i] > '7' && address[i] >= 'a' || hash[i] <= '7' && address[i] <= 'F' { - return false - } - } - - return true -} - -// isBitcoinAddress is the validation function for validating if the field's value is a valid btc address -func isBitcoinAddress(fl FieldLevel) bool { - address := fl.Field().String() - - if !btcAddressRegex.MatchString(address) { - return false - } - - alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") - - decode := [25]byte{} - - for _, n := range []byte(address) { - d := bytes.IndexByte(alphabet, n) - - for i := 24; i >= 0; i-- { - d += 58 * int(decode[i]) - decode[i] = byte(d % 256) - d /= 256 - } - } - - h := sha256.New() - _, _ = h.Write(decode[:21]) - d := h.Sum([]byte{}) - h = sha256.New() - _, _ = h.Write(d) - - validchecksum := [4]byte{} - computedchecksum := [4]byte{} - - copy(computedchecksum[:], h.Sum(d[:0])) - copy(validchecksum[:], decode[21:]) - - return validchecksum == computedchecksum -} - -// isBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address -func isBitcoinBech32Address(fl FieldLevel) bool { - address := fl.Field().String() - - if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) { - return false - } - - am := len(address) % 8 - - if am == 0 || am == 3 || am == 5 { - return false - } - - address = strings.ToLower(address) - - alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l" - - hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc - addr := address[3:] - dp := make([]int, 0, len(addr)) - - for _, c := range addr { - dp = append(dp, strings.IndexRune(alphabet, c)) - } - - ver := dp[0] - - if ver < 0 || ver > 16 { - return false - } - - if ver == 0 { - if len(address) != 42 && len(address) != 62 { - return false - } - } - - values := append(hr, dp...) - - GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} - - p := 1 - - for _, v := range values { - b := p >> 25 - p = (p&0x1ffffff)<<5 ^ v - - for i := 0; i < 5; i++ { - if (b>>uint(i))&1 == 1 { - p ^= GEN[i] - } - } - } - - if p != 1 { - return false - } - - b := uint(0) - acc := 0 - mv := (1 << 5) - 1 - var sw []int - - for _, v := range dp[1 : len(dp)-6] { - acc = (acc << 5) | v - b += 5 - for b >= 8 { - b -= 8 - sw = append(sw, (acc>>b)&mv) - } - } - - if len(sw) < 2 || len(sw) > 40 { - return false - } - - return true -} - -// excludesRune is the validation function for validating that the field's value does not contain the rune specified within the param. -func excludesRune(fl FieldLevel) bool { - return !containsRune(fl) -} - -// excludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param. -func excludesAll(fl FieldLevel) bool { - return !containsAny(fl) -} - -// excludes is the validation function for validating that the field's value does not contain the text specified within the param. -func excludes(fl FieldLevel) bool { - return !contains(fl) -} - -// containsRune is the validation function for validating that the field's value contains the rune specified within the param. -func containsRune(fl FieldLevel) bool { - r, _ := utf8.DecodeRuneInString(fl.Param()) - - return strings.ContainsRune(fl.Field().String(), r) -} - -// containsAny is the validation function for validating that the field's value contains any of the characters specified within the param. -func containsAny(fl FieldLevel) bool { - return strings.ContainsAny(fl.Field().String(), fl.Param()) -} - -// contains is the validation function for validating that the field's value contains the text specified within the param. -func contains(fl FieldLevel) bool { - return strings.Contains(fl.Field().String(), fl.Param()) -} - -// startsWith is the validation function for validating that the field's value starts with the text specified within the param. -func startsWith(fl FieldLevel) bool { - return strings.HasPrefix(fl.Field().String(), fl.Param()) -} - -// endsWith is the validation function for validating that the field's value ends with the text specified within the param. -func endsWith(fl FieldLevel) bool { - return strings.HasSuffix(fl.Field().String(), fl.Param()) -} - -// startsNotWith is the validation function for validating that the field's value does not start with the text specified within the param. -func startsNotWith(fl FieldLevel) bool { - return !startsWith(fl) -} - -// endsNotWith is the validation function for validating that the field's value does not end with the text specified within the param. -func endsNotWith(fl FieldLevel) bool { - return !endsWith(fl) -} - -// fieldContains is the validation function for validating if the current field's value contains the field specified by the param's value. -func fieldContains(fl FieldLevel) bool { - field := fl.Field() - - currentField, _, ok := fl.GetStructFieldOK() - - if !ok { - return false - } - - return strings.Contains(field.String(), currentField.String()) -} - -// fieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value. -func fieldExcludes(fl FieldLevel) bool { - field := fl.Field() - - currentField, _, ok := fl.GetStructFieldOK() - if !ok { - return true - } - - return !strings.Contains(field.String(), currentField.String()) -} - -// isNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value. -func isNeField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - - if !ok || currentKind != kind { - return true - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() != currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() != currentField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() != currentField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) != int64(currentField.Len()) - - case reflect.Bool: - return field.Bool() != currentField.Bool() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - - t := currentField.Interface().(time.Time) - fieldTime := field.Interface().(time.Time) - - return !fieldTime.Equal(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return true - } - } - - // default reflect.String: - return field.String() != currentField.String() -} - -// isNe is the validation function for validating that the field's value does not equal the provided param value. -func isNe(fl FieldLevel) bool { - return !isEq(fl) -} - -// isLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value. -func isLteCrossStructField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() <= topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() <= topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() <= topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) <= int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) - - return fieldTime.Before(topTime) || fieldTime.Equal(topTime) - } - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - } - - // default reflect.String: - return field.String() <= topField.String() -} - -// isLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value. -// NOTE: This is exposed for use within your own custom functions and not intended to be called directly. -func isLtCrossStructField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() < topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() < topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() < topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) < int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) - - return fieldTime.Before(topTime) - } - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - } - - // default reflect.String: - return field.String() < topField.String() -} - -// isGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value. -func isGteCrossStructField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() >= topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() >= topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() >= topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) >= int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) - - return fieldTime.After(topTime) || fieldTime.Equal(topTime) - } - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - } - - // default reflect.String: - return field.String() >= topField.String() -} - -// isGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value. -func isGtCrossStructField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() > topField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() > topField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() > topField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) > int64(topField.Len()) - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - - fieldTime := field.Convert(timeType).Interface().(time.Time) - topTime := topField.Convert(timeType).Interface().(time.Time) - - return fieldTime.After(topTime) - } - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - } - - // default reflect.String: - return field.String() > topField.String() -} - -// isNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value. -func isNeCrossStructField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - topField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return true - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return topField.Int() != field.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return topField.Uint() != field.Uint() - - case reflect.Float32, reflect.Float64: - return topField.Float() != field.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(topField.Len()) != int64(field.Len()) - - case reflect.Bool: - return topField.Bool() != field.Bool() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - - t := field.Convert(timeType).Interface().(time.Time) - fieldTime := topField.Convert(timeType).Interface().(time.Time) - - return !fieldTime.Equal(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return true - } - } - - // default reflect.String: - return topField.String() != field.String() -} - -// isEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value. -func isEqCrossStructField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - topField, topKind, ok := fl.GetStructFieldOK() - if !ok || topKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return topField.Int() == field.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return topField.Uint() == field.Uint() - - case reflect.Float32, reflect.Float64: - return topField.Float() == field.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(topField.Len()) == int64(field.Len()) - - case reflect.Bool: - return topField.Bool() == field.Bool() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) { - - t := field.Convert(timeType).Interface().(time.Time) - fieldTime := topField.Convert(timeType).Interface().(time.Time) - - return fieldTime.Equal(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != topField.Type() { - return false - } - } - - // default reflect.String: - return topField.String() == field.String() -} - -// isEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value. -func isEqField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() == currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() == currentField.Uint() - - case reflect.Float32, reflect.Float64: - return field.Float() == currentField.Float() - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) == int64(currentField.Len()) - - case reflect.Bool: - return field.Bool() == currentField.Bool() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) - - return fieldTime.Equal(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - } - - // default reflect.String: - return field.String() == currentField.String() -} - -// isEq is the validation function for validating if the current field's value is equal to the param's value. -func isEq(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - return field.String() == param - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) == p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() == p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() == p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() == p - - case reflect.Bool: - p := asBool(param) - - return field.Bool() == p - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isPostcodeByIso3166Alpha2 validates by value which is country code in iso 3166 alpha 2 -// example: `postcode_iso3166_alpha2=US` -func isPostcodeByIso3166Alpha2(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - reg, found := postCodeRegexDict[param] - if !found { - return false - } - - return reg.MatchString(field.String()) -} - -// isPostcodeByIso3166Alpha2Field validates by field which represents for a value of country code in iso 3166 alpha 2 -// example: `postcode_iso3166_alpha2_field=CountryCode` -func isPostcodeByIso3166Alpha2Field(fl FieldLevel) bool { - field := fl.Field() - params := parseOneOfParam2(fl.Param()) - - if len(params) != 1 { - return false - } - - currentField, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), params[0]) - if !found { - return false - } - - if kind != reflect.String { - panic(fmt.Sprintf("Bad field type %T", currentField.Interface())) - } - - reg, found := postCodeRegexDict[currentField.String()] - if !found { - return false - } - - return reg.MatchString(field.String()) -} - -// isBase64 is the validation function for validating if the current field's value is a valid base 64. -func isBase64(fl FieldLevel) bool { - return base64Regex.MatchString(fl.Field().String()) -} - -// isBase64URL is the validation function for validating if the current field's value is a valid base64 URL safe string. -func isBase64URL(fl FieldLevel) bool { - return base64URLRegex.MatchString(fl.Field().String()) -} - -// isURI is the validation function for validating if the current field's value is a valid URI. -func isURI(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - case reflect.String: - - s := field.String() - - // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 - // emulate browser and strip the '#' suffix prior to validation. see issue-#237 - if i := strings.Index(s, "#"); i > -1 { - s = s[:i] - } - - if len(s) == 0 { - return false - } - - _, err := url.ParseRequestURI(s) - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isURL is the validation function for validating if the current field's value is a valid URL. -func isURL(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - case reflect.String: - - var i int - s := field.String() - - // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195 - // emulate browser and strip the '#' suffix prior to validation. see issue-#237 - if i = strings.Index(s, "#"); i > -1 { - s = s[:i] - } - - if len(s) == 0 { - return false - } - - url, err := url.ParseRequestURI(s) - - if err != nil || url.Scheme == "" { - return false - } - - return true - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141. -func isUrnRFC2141(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - case reflect.String: - - str := field.String() - - _, match := urn.Parse([]byte(str)) - - return match - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isFile is the validation function for validating if the current field's value is a valid file path. -func isFile(fl FieldLevel) bool { - field := fl.Field() - - switch field.Kind() { - case reflect.String: - fileInfo, err := os.Stat(field.String()) - if err != nil { - return false - } - - return !fileInfo.IsDir() - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number. -func isE164(fl FieldLevel) bool { - return e164Regex.MatchString(fl.Field().String()) -} - -// isEmail is the validation function for validating if the current field's value is a valid email address. -func isEmail(fl FieldLevel) bool { - return emailRegex.MatchString(fl.Field().String()) -} - -// isHSLA is the validation function for validating if the current field's value is a valid HSLA color. -func isHSLA(fl FieldLevel) bool { - return hslaRegex.MatchString(fl.Field().String()) -} - -// isHSL is the validation function for validating if the current field's value is a valid HSL color. -func isHSL(fl FieldLevel) bool { - return hslRegex.MatchString(fl.Field().String()) -} - -// isRGBA is the validation function for validating if the current field's value is a valid RGBA color. -func isRGBA(fl FieldLevel) bool { - return rgbaRegex.MatchString(fl.Field().String()) -} - -// isRGB is the validation function for validating if the current field's value is a valid RGB color. -func isRGB(fl FieldLevel) bool { - return rgbRegex.MatchString(fl.Field().String()) -} - -// isHEXColor is the validation function for validating if the current field's value is a valid HEX color. -func isHEXColor(fl FieldLevel) bool { - return hexColorRegex.MatchString(fl.Field().String()) -} - -// isHexadecimal is the validation function for validating if the current field's value is a valid hexadecimal. -func isHexadecimal(fl FieldLevel) bool { - return hexadecimalRegex.MatchString(fl.Field().String()) -} - -// isNumber is the validation function for validating if the current field's value is a valid number. -func isNumber(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: - return true - default: - return numberRegex.MatchString(fl.Field().String()) - } -} - -// isNumeric is the validation function for validating if the current field's value is a valid numeric value. -func isNumeric(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64: - return true - default: - return numericRegex.MatchString(fl.Field().String()) - } -} - -// isAlphanum is the validation function for validating if the current field's value is a valid alphanumeric value. -func isAlphanum(fl FieldLevel) bool { - return alphaNumericRegex.MatchString(fl.Field().String()) -} - -// isAlpha is the validation function for validating if the current field's value is a valid alpha value. -func isAlpha(fl FieldLevel) bool { - return alphaRegex.MatchString(fl.Field().String()) -} - -// isAlphanumUnicode is the validation function for validating if the current field's value is a valid alphanumeric unicode value. -func isAlphanumUnicode(fl FieldLevel) bool { - return alphaUnicodeNumericRegex.MatchString(fl.Field().String()) -} - -// isAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value. -func isAlphaUnicode(fl FieldLevel) bool { - return alphaUnicodeRegex.MatchString(fl.Field().String()) -} - -// isBoolean is the validation function for validating if the current field's value is a valid boolean value or can be safely converted to a boolean value. -func isBoolean(fl FieldLevel) bool { - switch fl.Field().Kind() { - case reflect.Bool: - return true - default: - _, err := strconv.ParseBool(fl.Field().String()) - return err == nil - } -} - -// isDefault is the opposite of required aka hasValue -func isDefault(fl FieldLevel) bool { - return !hasValue(fl) -} - -// hasValue is the validation function for validating if the current field's value is not the default static value. -func hasValue(fl FieldLevel) bool { - field := fl.Field() - switch field.Kind() { - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return !field.IsNil() - default: - if fl.(*validate).fldIsPointer && field.Interface() != nil { - return true - } - return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() - } -} - -// requireCheckField is a func for check field kind -func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue bool) bool { - field := fl.Field() - kind := field.Kind() - var nullable, found bool - if len(param) > 0 { - field, kind, nullable, found = fl.GetStructFieldOKAdvanced2(fl.Parent(), param) - if !found { - return defaultNotFoundValue - } - } - switch kind { - case reflect.Invalid: - return defaultNotFoundValue - case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func: - return field.IsNil() - default: - if nullable && field.Interface() != nil { - return false - } - return field.IsValid() && field.Interface() == reflect.Zero(field.Type()).Interface() - } -} - -// requireCheckFieldValue is a func for check field value -func requireCheckFieldValue(fl FieldLevel, param string, value string, defaultNotFoundValue bool) bool { - field, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), param) - if !found { - return defaultNotFoundValue - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return field.Int() == asInt(value) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return field.Uint() == asUint(value) - - case reflect.Float32, reflect.Float64: - return field.Float() == asFloat(value) - - case reflect.Slice, reflect.Map, reflect.Array: - return int64(field.Len()) == asInt(value) - - case reflect.Bool: - return field.Bool() == asBool(value) - } - - // default reflect.String: - return field.String() == value -} - -// requiredIf is the validation function -// The field under validation must be present and not empty only if all the other specified fields are equal to the value following with the specified field. -func requiredIf(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - if len(params)%2 != 0 { - panic(fmt.Sprintf("Bad param number for required_if %s", fl.FieldName())) - } - for i := 0; i < len(params); i += 2 { - if !requireCheckFieldValue(fl, params[i], params[i+1], false) { - return true - } - } - return hasValue(fl) -} - -// excludedIf is the validation function -// The field under validation must not be present or is empty only if all the other specified fields are equal to the value following with the specified field. -func excludedIf(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - if len(params)%2 != 0 { - panic(fmt.Sprintf("Bad param number for excluded_if %s", fl.FieldName())) - } - - for i := 0; i < len(params); i += 2 { - if !requireCheckFieldValue(fl, params[i], params[i+1], false) { - return false - } - } - return true -} - -// requiredUnless is the validation function -// The field under validation must be present and not empty only unless all the other specified fields are equal to the value following with the specified field. -func requiredUnless(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - if len(params)%2 != 0 { - panic(fmt.Sprintf("Bad param number for required_unless %s", fl.FieldName())) - } - - for i := 0; i < len(params); i += 2 { - if requireCheckFieldValue(fl, params[i], params[i+1], false) { - return true - } - } - return hasValue(fl) -} - -// excludedUnless is the validation function -// The field under validation must not be present or is empty unless all the other specified fields are equal to the value following with the specified field. -func excludedUnless(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - if len(params)%2 != 0 { - panic(fmt.Sprintf("Bad param number for excluded_unless %s", fl.FieldName())) - } - for i := 0; i < len(params); i += 2 { - if !requireCheckFieldValue(fl, params[i], params[i+1], false) { - return true - } - } - return !hasValue(fl) -} - -// excludedWith is the validation function -// The field under validation must not be present or is empty if any of the other specified fields are present. -func excludedWith(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return !hasValue(fl) - } - } - return true -} - -// requiredWith is the validation function -// The field under validation must be present and not empty only if any of the other specified fields are present. -func requiredWith(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return hasValue(fl) - } - } - return true -} - -// excludedWithAll is the validation function -// The field under validation must not be present or is empty if all of the other specified fields are present. -func excludedWithAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if requireCheckFieldKind(fl, param, true) { - return true - } - } - return !hasValue(fl) -} - -// requiredWithAll is the validation function -// The field under validation must be present and not empty only if all of the other specified fields are present. -func requiredWithAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if requireCheckFieldKind(fl, param, true) { - return true - } - } - return hasValue(fl) -} - -// excludedWithout is the validation function -// The field under validation must not be present or is empty when any of the other specified fields are not present. -func excludedWithout(fl FieldLevel) bool { - if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { - return !hasValue(fl) - } - return true -} - -// requiredWithout is the validation function -// The field under validation must be present and not empty only when any of the other specified fields are not present. -func requiredWithout(fl FieldLevel) bool { - if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) { - return hasValue(fl) - } - return true -} - -// excludedWithoutAll is the validation function -// The field under validation must not be present or is empty when all of the other specified fields are not present. -func excludedWithoutAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return true - } - } - return !hasValue(fl) -} - -// requiredWithoutAll is the validation function -// The field under validation must be present and not empty only when all of the other specified fields are not present. -func requiredWithoutAll(fl FieldLevel) bool { - params := parseOneOfParam2(fl.Param()) - for _, param := range params { - if !requireCheckFieldKind(fl, param, true) { - return true - } - } - return hasValue(fl) -} - -// isGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value. -func isGteField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() >= currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() >= currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() >= currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) - - return fieldTime.After(t) || fieldTime.Equal(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - } - - // default reflect.String - return len(field.String()) >= len(currentField.String()) -} - -// isGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value. -func isGtField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() > currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() > currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() > currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) - - return fieldTime.After(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - } - - // default reflect.String - return len(field.String()) > len(currentField.String()) -} - -// isGte is the validation function for validating if the current field's value is greater than or equal to the param's value. -func isGte(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) >= p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) >= p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() >= p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() >= p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() >= p - - case reflect.Struct: - - if field.Type().ConvertibleTo(timeType) { - - now := time.Now().UTC() - t := field.Convert(timeType).Interface().(time.Time) - - return t.After(now) || t.Equal(now) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isGt is the validation function for validating if the current field's value is greater than the param's value. -func isGt(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) > p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) > p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() > p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() > p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() > p - case reflect.Struct: - - if field.Type().ConvertibleTo(timeType) { - - return field.Convert(timeType).Interface().(time.Time).After(time.Now().UTC()) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// hasLengthOf is the validation function for validating if the current field's value is equal to the param's value. -func hasLengthOf(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) == p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) == p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() == p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() == p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() == p - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// hasMinOf is the validation function for validating if the current field's value is greater than or equal to the param's value. -func hasMinOf(fl FieldLevel) bool { - return isGte(fl) -} - -// isLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value. -func isLteField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() <= currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() <= currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() <= currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) - - return fieldTime.Before(t) || fieldTime.Equal(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - } - - // default reflect.String - return len(field.String()) <= len(currentField.String()) -} - -// isLtField is the validation function for validating if the current field's value is less than the field specified by the param's value. -func isLtField(fl FieldLevel) bool { - field := fl.Field() - kind := field.Kind() - - currentField, currentKind, ok := fl.GetStructFieldOK() - if !ok || currentKind != kind { - return false - } - - switch kind { - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - - return field.Int() < currentField.Int() - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - - return field.Uint() < currentField.Uint() - - case reflect.Float32, reflect.Float64: - - return field.Float() < currentField.Float() - - case reflect.Struct: - - fieldType := field.Type() - - if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) { - - t := currentField.Convert(timeType).Interface().(time.Time) - fieldTime := field.Convert(timeType).Interface().(time.Time) - - return fieldTime.Before(t) - } - - // Not Same underlying type i.e. struct and time - if fieldType != currentField.Type() { - return false - } - } - - // default reflect.String - return len(field.String()) < len(currentField.String()) -} - -// isLte is the validation function for validating if the current field's value is less than or equal to the param's value. -func isLte(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) <= p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) <= p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() <= p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() <= p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() <= p - - case reflect.Struct: - - if field.Type().ConvertibleTo(timeType) { - - now := time.Now().UTC() - t := field.Convert(timeType).Interface().(time.Time) - - return t.Before(now) || t.Equal(now) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isLt is the validation function for validating if the current field's value is less than the param's value. -func isLt(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - switch field.Kind() { - - case reflect.String: - p := asInt(param) - - return int64(utf8.RuneCountInString(field.String())) < p - - case reflect.Slice, reflect.Map, reflect.Array: - p := asInt(param) - - return int64(field.Len()) < p - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p := asIntFromType(field.Type(), param) - - return field.Int() < p - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p := asUint(param) - - return field.Uint() < p - - case reflect.Float32, reflect.Float64: - p := asFloat(param) - - return field.Float() < p - - case reflect.Struct: - - if field.Type().ConvertibleTo(timeType) { - - return field.Convert(timeType).Interface().(time.Time).Before(time.Now().UTC()) - } - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// hasMaxOf is the validation function for validating if the current field's value is less than or equal to the param's value. -func hasMaxOf(fl FieldLevel) bool { - return isLte(fl) -} - -// isTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address. -func isTCP4AddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp4", fl.Field().String()) - return err == nil -} - -// isTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address. -func isTCP6AddrResolvable(fl FieldLevel) bool { - if !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp6", fl.Field().String()) - - return err == nil -} - -// isTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address. -func isTCPAddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) && !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveTCPAddr("tcp", fl.Field().String()) - - return err == nil -} - -// isUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address. -func isUDP4AddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp4", fl.Field().String()) - - return err == nil -} - -// isUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address. -func isUDP6AddrResolvable(fl FieldLevel) bool { - if !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp6", fl.Field().String()) - - return err == nil -} - -// isUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address. -func isUDPAddrResolvable(fl FieldLevel) bool { - if !isIP4Addr(fl) && !isIP6Addr(fl) { - return false - } - - _, err := net.ResolveUDPAddr("udp", fl.Field().String()) - - return err == nil -} - -// isIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address. -func isIP4AddrResolvable(fl FieldLevel) bool { - if !isIPv4(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip4", fl.Field().String()) - - return err == nil -} - -// isIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address. -func isIP6AddrResolvable(fl FieldLevel) bool { - if !isIPv6(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip6", fl.Field().String()) - - return err == nil -} - -// isIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address. -func isIPAddrResolvable(fl FieldLevel) bool { - if !isIP(fl) { - return false - } - - _, err := net.ResolveIPAddr("ip", fl.Field().String()) - - return err == nil -} - -// isUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address. -func isUnixAddrResolvable(fl FieldLevel) bool { - _, err := net.ResolveUnixAddr("unix", fl.Field().String()) - - return err == nil -} - -func isIP4Addr(fl FieldLevel) bool { - val := fl.Field().String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - val = val[0:idx] - } - - ip := net.ParseIP(val) - - return ip != nil && ip.To4() != nil -} - -func isIP6Addr(fl FieldLevel) bool { - val := fl.Field().String() - - if idx := strings.LastIndex(val, ":"); idx != -1 { - if idx != 0 && val[idx-1:idx] == "]" { - val = val[1 : idx-1] - } - } - - ip := net.ParseIP(val) - - return ip != nil && ip.To4() == nil -} - -func isHostnameRFC952(fl FieldLevel) bool { - return hostnameRegexRFC952.MatchString(fl.Field().String()) -} - -func isHostnameRFC1123(fl FieldLevel) bool { - return hostnameRegexRFC1123.MatchString(fl.Field().String()) -} - -func isFQDN(fl FieldLevel) bool { - val := fl.Field().String() - - if val == "" { - return false - } - - return fqdnRegexRFC1123.MatchString(val) -} - -// isDir is the validation function for validating if the current field's value is a valid directory. -func isDir(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - fileInfo, err := os.Stat(field.String()) - if err != nil { - return false - } - - return fileInfo.IsDir() - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isJSON is the validation function for validating if the current field's value is a valid json string. -func isJSON(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - val := field.String() - return json.Valid([]byte(val)) - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isJWT is the validation function for validating if the current field's value is a valid JWT string. -func isJWT(fl FieldLevel) bool { - return jWTRegex.MatchString(fl.Field().String()) -} - -// isHostnamePort validates a : combination for fields typically used for socket address. -func isHostnamePort(fl FieldLevel) bool { - val := fl.Field().String() - host, port, err := net.SplitHostPort(val) - if err != nil { - return false - } - // Port must be a iny <= 65535. - if portNum, err := strconv.ParseInt(port, 10, 32); err != nil || portNum > 65535 || portNum < 1 { - return false - } - - // If host is specified, it should match a DNS name - if host != "" { - return hostnameRegexRFC1123.MatchString(host) - } - return true -} - -// isLowercase is the validation function for validating if the current field's value is a lowercase string. -func isLowercase(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - if field.String() == "" { - return false - } - return field.String() == strings.ToLower(field.String()) - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isUppercase is the validation function for validating if the current field's value is an uppercase string. -func isUppercase(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - if field.String() == "" { - return false - } - return field.String() == strings.ToUpper(field.String()) - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isDatetime is the validation function for validating if the current field's value is a valid datetime string. -func isDatetime(fl FieldLevel) bool { - field := fl.Field() - param := fl.Param() - - if field.Kind() == reflect.String { - _, err := time.Parse(param, field.String()) - - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isTimeZone is the validation function for validating if the current field's value is a valid time zone string. -func isTimeZone(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - // empty value is converted to UTC by time.LoadLocation but disallow it as it is not a valid time zone name - if field.String() == "" { - return false - } - - // Local value is converted to the current system time zone by time.LoadLocation but disallow it as it is not a valid time zone name - if strings.ToLower(field.String()) == "local" { - return false - } - - _, err := time.LoadLocation(field.String()) - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-2 country code. -func isIso3166Alpha2(fl FieldLevel) bool { - val := fl.Field().String() - return iso3166_1_alpha2[val] -} - -// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-3 country code. -func isIso3166Alpha3(fl FieldLevel) bool { - val := fl.Field().String() - return iso3166_1_alpha3[val] -} - -// isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-numeric country code. -func isIso3166AlphaNumeric(fl FieldLevel) bool { - field := fl.Field() - - var code int - switch field.Kind() { - case reflect.String: - i, err := strconv.Atoi(field.String()) - if err != nil { - return false - } - code = i % 1000 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - code = int(field.Int() % 1000) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - code = int(field.Uint() % 1000) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - return iso3166_1_alpha_numeric[code] -} - -// isIso31662 is the validation function for validating if the current field's value is a valid iso3166-2 code. -func isIso31662(fl FieldLevel) bool { - val := fl.Field().String() - return iso3166_2[val] -} - -// isIso4217 is the validation function for validating if the current field's value is a valid iso4217 currency code. -func isIso4217(fl FieldLevel) bool { - val := fl.Field().String() - return iso4217[val] -} - -// isIso4217Numeric is the validation function for validating if the current field's value is a valid iso4217 numeric currency code. -func isIso4217Numeric(fl FieldLevel) bool { - field := fl.Field() - - var code int - switch field.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - code = int(field.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - code = int(field.Uint()) - default: - panic(fmt.Sprintf("Bad field type %T", field.Interface())) - } - return iso4217_numeric[code] -} - -// isBCP47LanguageTag is the validation function for validating if the current field's value is a valid BCP 47 language tag, as parsed by language.Parse -func isBCP47LanguageTag(fl FieldLevel) bool { - field := fl.Field() - - if field.Kind() == reflect.String { - _, err := language.Parse(field.String()) - return err == nil - } - - panic(fmt.Sprintf("Bad field type %T", field.Interface())) -} - -// isIsoBicFormat is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362 -func isIsoBicFormat(fl FieldLevel) bool { - bicString := fl.Field().String() - - return bicRegex.MatchString(bicString) -} - -// isSemverFormat is the validation function for validating if the current field's value is a valid semver version, defined in Semantic Versioning 2.0.0 -func isSemverFormat(fl FieldLevel) bool { - semverString := fl.Field().String() - - return semverRegex.MatchString(semverString) -} - -// isDnsRFC1035LabelFormat is the validation function -// for validating if the current field's value is -// a valid dns RFC 1035 label, defined in RFC 1035. -func isDnsRFC1035LabelFormat(fl FieldLevel) bool { - val := fl.Field().String() - return dnsRegexRFC1035Label.MatchString(val) -} - -// isCreditCard is the validation function for validating if the current field's value is a valid credit card number -func isCreditCard(fl FieldLevel) bool { - val := fl.Field().String() - var creditCard bytes.Buffer - segments := strings.Split(val, " ") - for _, segment := range segments { - if len(segment) < 3 { - return false - } - creditCard.WriteString(segment) - } - - ccDigits := strings.Split(creditCard.String(), "") - size := len(ccDigits) - if size < 12 || size > 19 { - return false - } - - sum := 0 - for i, digit := range ccDigits { - value, err := strconv.Atoi(digit) - if err != nil { - return false - } - if size%2 == 0 && i%2 == 0 || size%2 == 1 && i%2 == 1 { - v := value * 2 - if v >= 10 { - sum += 1 + (v % 10) - } else { - sum += v - } - } else { - sum += value - } - } - return (sum % 10) == 0 -} diff --git a/vendor/github.com/go-playground/validator/v10/cache.go b/vendor/github.com/go-playground/validator/v10/cache.go deleted file mode 100644 index 7b84c91..0000000 --- a/vendor/github.com/go-playground/validator/v10/cache.go +++ /dev/null @@ -1,327 +0,0 @@ -package validator - -import ( - "fmt" - "reflect" - "strings" - "sync" - "sync/atomic" -) - -type tagType uint8 - -const ( - typeDefault tagType = iota - typeOmitEmpty - typeIsDefault - typeNoStructLevel - typeStructOnly - typeDive - typeOr - typeKeys - typeEndKeys -) - -const ( - invalidValidation = "Invalid validation tag on field '%s'" - undefinedValidation = "Undefined validation function '%s' on field '%s'" - keysTagNotDefined = "'" + endKeysTag + "' tag encountered without a corresponding '" + keysTag + "' tag" -) - -type structCache struct { - lock sync.Mutex - m atomic.Value // map[reflect.Type]*cStruct -} - -func (sc *structCache) Get(key reflect.Type) (c *cStruct, found bool) { - c, found = sc.m.Load().(map[reflect.Type]*cStruct)[key] - return -} - -func (sc *structCache) Set(key reflect.Type, value *cStruct) { - m := sc.m.Load().(map[reflect.Type]*cStruct) - nm := make(map[reflect.Type]*cStruct, len(m)+1) - for k, v := range m { - nm[k] = v - } - nm[key] = value - sc.m.Store(nm) -} - -type tagCache struct { - lock sync.Mutex - m atomic.Value // map[string]*cTag -} - -func (tc *tagCache) Get(key string) (c *cTag, found bool) { - c, found = tc.m.Load().(map[string]*cTag)[key] - return -} - -func (tc *tagCache) Set(key string, value *cTag) { - m := tc.m.Load().(map[string]*cTag) - nm := make(map[string]*cTag, len(m)+1) - for k, v := range m { - nm[k] = v - } - nm[key] = value - tc.m.Store(nm) -} - -type cStruct struct { - name string - fields []*cField - fn StructLevelFuncCtx -} - -type cField struct { - idx int - name string - altName string - namesEqual bool - cTags *cTag -} - -type cTag struct { - tag string - aliasTag string - actualAliasTag string - param string - keys *cTag // only populated when using tag's 'keys' and 'endkeys' for map key validation - next *cTag - fn FuncCtx - typeof tagType - hasTag bool - hasAlias bool - hasParam bool // true if parameter used eg. eq= where the equal sign has been set - isBlockEnd bool // indicates the current tag represents the last validation in the block - runValidationWhenNil bool -} - -func (v *Validate) extractStructCache(current reflect.Value, sName string) *cStruct { - v.structCache.lock.Lock() - defer v.structCache.lock.Unlock() // leave as defer! because if inner panics, it will never get unlocked otherwise! - - typ := current.Type() - - // could have been multiple trying to access, but once first is done this ensures struct - // isn't parsed again. - cs, ok := v.structCache.Get(typ) - if ok { - return cs - } - - cs = &cStruct{name: sName, fields: make([]*cField, 0), fn: v.structLevelFuncs[typ]} - - numFields := current.NumField() - rules := v.rules[typ] - - var ctag *cTag - var fld reflect.StructField - var tag string - var customName string - - for i := 0; i < numFields; i++ { - - fld = typ.Field(i) - - if !fld.Anonymous && len(fld.PkgPath) > 0 { - continue - } - - if rtag, ok := rules[fld.Name]; ok { - tag = rtag - } else { - tag = fld.Tag.Get(v.tagName) - } - - if tag == skipValidationTag { - continue - } - - customName = fld.Name - - if v.hasTagNameFunc { - name := v.tagNameFunc(fld) - if len(name) > 0 { - customName = name - } - } - - // NOTE: cannot use shared tag cache, because tags may be equal, but things like alias may be different - // and so only struct level caching can be used instead of combined with Field tag caching - - if len(tag) > 0 { - ctag, _ = v.parseFieldTagsRecursive(tag, fld.Name, "", false) - } else { - // even if field doesn't have validations need cTag for traversing to potential inner/nested - // elements of the field. - ctag = new(cTag) - } - - cs.fields = append(cs.fields, &cField{ - idx: i, - name: fld.Name, - altName: customName, - cTags: ctag, - namesEqual: fld.Name == customName, - }) - } - v.structCache.Set(typ, cs) - return cs -} - -func (v *Validate) parseFieldTagsRecursive(tag string, fieldName string, alias string, hasAlias bool) (firstCtag *cTag, current *cTag) { - var t string - noAlias := len(alias) == 0 - tags := strings.Split(tag, tagSeparator) - - for i := 0; i < len(tags); i++ { - t = tags[i] - if noAlias { - alias = t - } - - // check map for alias and process new tags, otherwise process as usual - if tagsVal, found := v.aliases[t]; found { - if i == 0 { - firstCtag, current = v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) - } else { - next, curr := v.parseFieldTagsRecursive(tagsVal, fieldName, t, true) - current.next, current = next, curr - - } - continue - } - - var prevTag tagType - - if i == 0 { - current = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true, typeof: typeDefault} - firstCtag = current - } else { - prevTag = current.typeof - current.next = &cTag{aliasTag: alias, hasAlias: hasAlias, hasTag: true} - current = current.next - } - - switch t { - case diveTag: - current.typeof = typeDive - continue - - case keysTag: - current.typeof = typeKeys - - if i == 0 || prevTag != typeDive { - panic(fmt.Sprintf("'%s' tag must be immediately preceded by the '%s' tag", keysTag, diveTag)) - } - - current.typeof = typeKeys - - // need to pass along only keys tag - // need to increment i to skip over the keys tags - b := make([]byte, 0, 64) - - i++ - - for ; i < len(tags); i++ { - - b = append(b, tags[i]...) - b = append(b, ',') - - if tags[i] == endKeysTag { - break - } - } - - current.keys, _ = v.parseFieldTagsRecursive(string(b[:len(b)-1]), fieldName, "", false) - continue - - case endKeysTag: - current.typeof = typeEndKeys - - // if there are more in tags then there was no keysTag defined - // and an error should be thrown - if i != len(tags)-1 { - panic(keysTagNotDefined) - } - return - - case omitempty: - current.typeof = typeOmitEmpty - continue - - case structOnlyTag: - current.typeof = typeStructOnly - continue - - case noStructLevelTag: - current.typeof = typeNoStructLevel - continue - - default: - if t == isdefault { - current.typeof = typeIsDefault - } - // if a pipe character is needed within the param you must use the utf8Pipe representation "0x7C" - orVals := strings.Split(t, orSeparator) - - for j := 0; j < len(orVals); j++ { - vals := strings.SplitN(orVals[j], tagKeySeparator, 2) - if noAlias { - alias = vals[0] - current.aliasTag = alias - } else { - current.actualAliasTag = t - } - - if j > 0 { - current.next = &cTag{aliasTag: alias, actualAliasTag: current.actualAliasTag, hasAlias: hasAlias, hasTag: true} - current = current.next - } - current.hasParam = len(vals) > 1 - - current.tag = vals[0] - if len(current.tag) == 0 { - panic(strings.TrimSpace(fmt.Sprintf(invalidValidation, fieldName))) - } - - if wrapper, ok := v.validations[current.tag]; ok { - current.fn = wrapper.fn - current.runValidationWhenNil = wrapper.runValidatinOnNil - } else { - panic(strings.TrimSpace(fmt.Sprintf(undefinedValidation, current.tag, fieldName))) - } - - if len(orVals) > 1 { - current.typeof = typeOr - } - - if len(vals) > 1 { - current.param = strings.Replace(strings.Replace(vals[1], utf8HexComma, ",", -1), utf8Pipe, "|", -1) - } - } - current.isBlockEnd = true - } - } - return -} - -func (v *Validate) fetchCacheTag(tag string) *cTag { - // find cached tag - ctag, found := v.tagCache.Get(tag) - if !found { - v.tagCache.lock.Lock() - defer v.tagCache.lock.Unlock() - - // could have been multiple trying to access, but once first is done this ensures tag - // isn't parsed again. - ctag, found = v.tagCache.Get(tag) - if !found { - ctag, _ = v.parseFieldTagsRecursive(tag, "", "", false) - v.tagCache.Set(tag, ctag) - } - } - return ctag -} diff --git a/vendor/github.com/go-playground/validator/v10/country_codes.go b/vendor/github.com/go-playground/validator/v10/country_codes.go deleted file mode 100644 index 0d9eda0..0000000 --- a/vendor/github.com/go-playground/validator/v10/country_codes.go +++ /dev/null @@ -1,1132 +0,0 @@ -package validator - -var iso3166_1_alpha2 = map[string]bool{ - // see: https://www.iso.org/iso-3166-country-codes.html - "AF": true, "AX": true, "AL": true, "DZ": true, "AS": true, - "AD": true, "AO": true, "AI": true, "AQ": true, "AG": true, - "AR": true, "AM": true, "AW": true, "AU": true, "AT": true, - "AZ": true, "BS": true, "BH": true, "BD": true, "BB": true, - "BY": true, "BE": true, "BZ": true, "BJ": true, "BM": true, - "BT": true, "BO": true, "BQ": true, "BA": true, "BW": true, - "BV": true, "BR": true, "IO": true, "BN": true, "BG": true, - "BF": true, "BI": true, "KH": true, "CM": true, "CA": true, - "CV": true, "KY": true, "CF": true, "TD": true, "CL": true, - "CN": true, "CX": true, "CC": true, "CO": true, "KM": true, - "CG": true, "CD": true, "CK": true, "CR": true, "CI": true, - "HR": true, "CU": true, "CW": true, "CY": true, "CZ": true, - "DK": true, "DJ": true, "DM": true, "DO": true, "EC": true, - "EG": true, "SV": true, "GQ": true, "ER": true, "EE": true, - "ET": true, "FK": true, "FO": true, "FJ": true, "FI": true, - "FR": true, "GF": true, "PF": true, "TF": true, "GA": true, - "GM": true, "GE": true, "DE": true, "GH": true, "GI": true, - "GR": true, "GL": true, "GD": true, "GP": true, "GU": true, - "GT": true, "GG": true, "GN": true, "GW": true, "GY": true, - "HT": true, "HM": true, "VA": true, "HN": true, "HK": true, - "HU": true, "IS": true, "IN": true, "ID": true, "IR": true, - "IQ": true, "IE": true, "IM": true, "IL": true, "IT": true, - "JM": true, "JP": true, "JE": true, "JO": true, "KZ": true, - "KE": true, "KI": true, "KP": true, "KR": true, "KW": true, - "KG": true, "LA": true, "LV": true, "LB": true, "LS": true, - "LR": true, "LY": true, "LI": true, "LT": true, "LU": true, - "MO": true, "MK": true, "MG": true, "MW": true, "MY": true, - "MV": true, "ML": true, "MT": true, "MH": true, "MQ": true, - "MR": true, "MU": true, "YT": true, "MX": true, "FM": true, - "MD": true, "MC": true, "MN": true, "ME": true, "MS": true, - "MA": true, "MZ": true, "MM": true, "NA": true, "NR": true, - "NP": true, "NL": true, "NC": true, "NZ": true, "NI": true, - "NE": true, "NG": true, "NU": true, "NF": true, "MP": true, - "NO": true, "OM": true, "PK": true, "PW": true, "PS": true, - "PA": true, "PG": true, "PY": true, "PE": true, "PH": true, - "PN": true, "PL": true, "PT": true, "PR": true, "QA": true, - "RE": true, "RO": true, "RU": true, "RW": true, "BL": true, - "SH": true, "KN": true, "LC": true, "MF": true, "PM": true, - "VC": true, "WS": true, "SM": true, "ST": true, "SA": true, - "SN": true, "RS": true, "SC": true, "SL": true, "SG": true, - "SX": true, "SK": true, "SI": true, "SB": true, "SO": true, - "ZA": true, "GS": true, "SS": true, "ES": true, "LK": true, - "SD": true, "SR": true, "SJ": true, "SZ": true, "SE": true, - "CH": true, "SY": true, "TW": true, "TJ": true, "TZ": true, - "TH": true, "TL": true, "TG": true, "TK": true, "TO": true, - "TT": true, "TN": true, "TR": true, "TM": true, "TC": true, - "TV": true, "UG": true, "UA": true, "AE": true, "GB": true, - "US": true, "UM": true, "UY": true, "UZ": true, "VU": true, - "VE": true, "VN": true, "VG": true, "VI": true, "WF": true, - "EH": true, "YE": true, "ZM": true, "ZW": true, -} - -var iso3166_1_alpha3 = map[string]bool{ - // see: https://www.iso.org/iso-3166-country-codes.html - "AFG": true, "ALB": true, "DZA": true, "ASM": true, "AND": true, - "AGO": true, "AIA": true, "ATA": true, "ATG": true, "ARG": true, - "ARM": true, "ABW": true, "AUS": true, "AUT": true, "AZE": true, - "BHS": true, "BHR": true, "BGD": true, "BRB": true, "BLR": true, - "BEL": true, "BLZ": true, "BEN": true, "BMU": true, "BTN": true, - "BOL": true, "BES": true, "BIH": true, "BWA": true, "BVT": true, - "BRA": true, "IOT": true, "BRN": true, "BGR": true, "BFA": true, - "BDI": true, "CPV": true, "KHM": true, "CMR": true, "CAN": true, - "CYM": true, "CAF": true, "TCD": true, "CHL": true, "CHN": true, - "CXR": true, "CCK": true, "COL": true, "COM": true, "COD": true, - "COG": true, "COK": true, "CRI": true, "HRV": true, "CUB": true, - "CUW": true, "CYP": true, "CZE": true, "CIV": true, "DNK": true, - "DJI": true, "DMA": true, "DOM": true, "ECU": true, "EGY": true, - "SLV": true, "GNQ": true, "ERI": true, "EST": true, "SWZ": true, - "ETH": true, "FLK": true, "FRO": true, "FJI": true, "FIN": true, - "FRA": true, "GUF": true, "PYF": true, "ATF": true, "GAB": true, - "GMB": true, "GEO": true, "DEU": true, "GHA": true, "GIB": true, - "GRC": true, "GRL": true, "GRD": true, "GLP": true, "GUM": true, - "GTM": true, "GGY": true, "GIN": true, "GNB": true, "GUY": true, - "HTI": true, "HMD": true, "VAT": true, "HND": true, "HKG": true, - "HUN": true, "ISL": true, "IND": true, "IDN": true, "IRN": true, - "IRQ": true, "IRL": true, "IMN": true, "ISR": true, "ITA": true, - "JAM": true, "JPN": true, "JEY": true, "JOR": true, "KAZ": true, - "KEN": true, "KIR": true, "PRK": true, "KOR": true, "KWT": true, - "KGZ": true, "LAO": true, "LVA": true, "LBN": true, "LSO": true, - "LBR": true, "LBY": true, "LIE": true, "LTU": true, "LUX": true, - "MAC": true, "MDG": true, "MWI": true, "MYS": true, "MDV": true, - "MLI": true, "MLT": true, "MHL": true, "MTQ": true, "MRT": true, - "MUS": true, "MYT": true, "MEX": true, "FSM": true, "MDA": true, - "MCO": true, "MNG": true, "MNE": true, "MSR": true, "MAR": true, - "MOZ": true, "MMR": true, "NAM": true, "NRU": true, "NPL": true, - "NLD": true, "NCL": true, "NZL": true, "NIC": true, "NER": true, - "NGA": true, "NIU": true, "NFK": true, "MKD": true, "MNP": true, - "NOR": true, "OMN": true, "PAK": true, "PLW": true, "PSE": true, - "PAN": true, "PNG": true, "PRY": true, "PER": true, "PHL": true, - "PCN": true, "POL": true, "PRT": true, "PRI": true, "QAT": true, - "ROU": true, "RUS": true, "RWA": true, "REU": true, "BLM": true, - "SHN": true, "KNA": true, "LCA": true, "MAF": true, "SPM": true, - "VCT": true, "WSM": true, "SMR": true, "STP": true, "SAU": true, - "SEN": true, "SRB": true, "SYC": true, "SLE": true, "SGP": true, - "SXM": true, "SVK": true, "SVN": true, "SLB": true, "SOM": true, - "ZAF": true, "SGS": true, "SSD": true, "ESP": true, "LKA": true, - "SDN": true, "SUR": true, "SJM": true, "SWE": true, "CHE": true, - "SYR": true, "TWN": true, "TJK": true, "TZA": true, "THA": true, - "TLS": true, "TGO": true, "TKL": true, "TON": true, "TTO": true, - "TUN": true, "TUR": true, "TKM": true, "TCA": true, "TUV": true, - "UGA": true, "UKR": true, "ARE": true, "GBR": true, "UMI": true, - "USA": true, "URY": true, "UZB": true, "VUT": true, "VEN": true, - "VNM": true, "VGB": true, "VIR": true, "WLF": true, "ESH": true, - "YEM": true, "ZMB": true, "ZWE": true, "ALA": true, -} -var iso3166_1_alpha_numeric = map[int]bool{ - // see: https://www.iso.org/iso-3166-country-codes.html - 4: true, 8: true, 12: true, 16: true, 20: true, - 24: true, 660: true, 10: true, 28: true, 32: true, - 51: true, 533: true, 36: true, 40: true, 31: true, - 44: true, 48: true, 50: true, 52: true, 112: true, - 56: true, 84: true, 204: true, 60: true, 64: true, - 68: true, 535: true, 70: true, 72: true, 74: true, - 76: true, 86: true, 96: true, 100: true, 854: true, - 108: true, 132: true, 116: true, 120: true, 124: true, - 136: true, 140: true, 148: true, 152: true, 156: true, - 162: true, 166: true, 170: true, 174: true, 180: true, - 178: true, 184: true, 188: true, 191: true, 192: true, - 531: true, 196: true, 203: true, 384: true, 208: true, - 262: true, 212: true, 214: true, 218: true, 818: true, - 222: true, 226: true, 232: true, 233: true, 748: true, - 231: true, 238: true, 234: true, 242: true, 246: true, - 250: true, 254: true, 258: true, 260: true, 266: true, - 270: true, 268: true, 276: true, 288: true, 292: true, - 300: true, 304: true, 308: true, 312: true, 316: true, - 320: true, 831: true, 324: true, 624: true, 328: true, - 332: true, 334: true, 336: true, 340: true, 344: true, - 348: true, 352: true, 356: true, 360: true, 364: true, - 368: true, 372: true, 833: true, 376: true, 380: true, - 388: true, 392: true, 832: true, 400: true, 398: true, - 404: true, 296: true, 408: true, 410: true, 414: true, - 417: true, 418: true, 428: true, 422: true, 426: true, - 430: true, 434: true, 438: true, 440: true, 442: true, - 446: true, 450: true, 454: true, 458: true, 462: true, - 466: true, 470: true, 584: true, 474: true, 478: true, - 480: true, 175: true, 484: true, 583: true, 498: true, - 492: true, 496: true, 499: true, 500: true, 504: true, - 508: true, 104: true, 516: true, 520: true, 524: true, - 528: true, 540: true, 554: true, 558: true, 562: true, - 566: true, 570: true, 574: true, 807: true, 580: true, - 578: true, 512: true, 586: true, 585: true, 275: true, - 591: true, 598: true, 600: true, 604: true, 608: true, - 612: true, 616: true, 620: true, 630: true, 634: true, - 642: true, 643: true, 646: true, 638: true, 652: true, - 654: true, 659: true, 662: true, 663: true, 666: true, - 670: true, 882: true, 674: true, 678: true, 682: true, - 686: true, 688: true, 690: true, 694: true, 702: true, - 534: true, 703: true, 705: true, 90: true, 706: true, - 710: true, 239: true, 728: true, 724: true, 144: true, - 729: true, 740: true, 744: true, 752: true, 756: true, - 760: true, 158: true, 762: true, 834: true, 764: true, - 626: true, 768: true, 772: true, 776: true, 780: true, - 788: true, 792: true, 795: true, 796: true, 798: true, - 800: true, 804: true, 784: true, 826: true, 581: true, - 840: true, 858: true, 860: true, 548: true, 862: true, - 704: true, 92: true, 850: true, 876: true, 732: true, - 887: true, 894: true, 716: true, 248: true, -} - -var iso3166_2 = map[string]bool{ - "AD-02" : true, "AD-03" : true, "AD-04" : true, "AD-05" : true, "AD-06" : true, - "AD-07" : true, "AD-08" : true, "AE-AJ" : true, "AE-AZ" : true, "AE-DU" : true, - "AE-FU" : true, "AE-RK" : true, "AE-SH" : true, "AE-UQ" : true, "AF-BAL" : true, - "AF-BAM" : true, "AF-BDG" : true, "AF-BDS" : true, "AF-BGL" : true, "AF-DAY" : true, - "AF-FRA" : true, "AF-FYB" : true, "AF-GHA" : true, "AF-GHO" : true, "AF-HEL" : true, - "AF-HER" : true, "AF-JOW" : true, "AF-KAB" : true, "AF-KAN" : true, "AF-KAP" : true, - "AF-KDZ" : true, "AF-KHO" : true, "AF-KNR" : true, "AF-LAG" : true, "AF-LOG" : true, - "AF-NAN" : true, "AF-NIM" : true, "AF-NUR" : true, "AF-PAN" : true, "AF-PAR" : true, - "AF-PIA" : true, "AF-PKA" : true, "AF-SAM" : true, "AF-SAR" : true, "AF-TAK" : true, - "AF-URU" : true, "AF-WAR" : true, "AF-ZAB" : true, "AG-03" : true, "AG-04" : true, - "AG-05" : true, "AG-06" : true, "AG-07" : true, "AG-08" : true, "AG-10" : true, - "AG-11" : true, "AL-01" : true, "AL-02" : true, "AL-03" : true, "AL-04" : true, - "AL-05" : true, "AL-06" : true, "AL-07" : true, "AL-08" : true, "AL-09" : true, - "AL-10" : true, "AL-11" : true, "AL-12" : true, "AL-BR" : true, "AL-BU" : true, - "AL-DI" : true, "AL-DL" : true, "AL-DR" : true, "AL-DV" : true, "AL-EL" : true, - "AL-ER" : true, "AL-FR" : true, "AL-GJ" : true, "AL-GR" : true, "AL-HA" : true, - "AL-KA" : true, "AL-KB" : true, "AL-KC" : true, "AL-KO" : true, "AL-KR" : true, - "AL-KU" : true, "AL-LB" : true, "AL-LE" : true, "AL-LU" : true, "AL-MK" : true, - "AL-MM" : true, "AL-MR" : true, "AL-MT" : true, "AL-PG" : true, "AL-PQ" : true, - "AL-PR" : true, "AL-PU" : true, "AL-SH" : true, "AL-SK" : true, "AL-SR" : true, - "AL-TE" : true, "AL-TP" : true, "AL-TR" : true, "AL-VL" : true, "AM-AG" : true, - "AM-AR" : true, "AM-AV" : true, "AM-ER" : true, "AM-GR" : true, "AM-KT" : true, - "AM-LO" : true, "AM-SH" : true, "AM-SU" : true, "AM-TV" : true, "AM-VD" : true, - "AO-BGO" : true, "AO-BGU" : true, "AO-BIE" : true, "AO-CAB" : true, "AO-CCU" : true, - "AO-CNN" : true, "AO-CNO" : true, "AO-CUS" : true, "AO-HUA" : true, "AO-HUI" : true, - "AO-LNO" : true, "AO-LSU" : true, "AO-LUA" : true, "AO-MAL" : true, "AO-MOX" : true, - "AO-NAM" : true, "AO-UIG" : true, "AO-ZAI" : true, "AR-A" : true, "AR-B" : true, - "AR-C" : true, "AR-D" : true, "AR-E" : true, "AR-G" : true, "AR-H" : true, - "AR-J" : true, "AR-K" : true, "AR-L" : true, "AR-M" : true, "AR-N" : true, - "AR-P" : true, "AR-Q" : true, "AR-R" : true, "AR-S" : true, "AR-T" : true, - "AR-U" : true, "AR-V" : true, "AR-W" : true, "AR-X" : true, "AR-Y" : true, - "AR-Z" : true, "AT-1" : true, "AT-2" : true, "AT-3" : true, "AT-4" : true, - "AT-5" : true, "AT-6" : true, "AT-7" : true, "AT-8" : true, "AT-9" : true, - "AU-ACT" : true, "AU-NSW" : true, "AU-NT" : true, "AU-QLD" : true, "AU-SA" : true, - "AU-TAS" : true, "AU-VIC" : true, "AU-WA" : true, "AZ-ABS" : true, "AZ-AGA" : true, - "AZ-AGC" : true, "AZ-AGM" : true, "AZ-AGS" : true, "AZ-AGU" : true, "AZ-AST" : true, - "AZ-BA" : true, "AZ-BAB" : true, "AZ-BAL" : true, "AZ-BAR" : true, "AZ-BEY" : true, - "AZ-BIL" : true, "AZ-CAB" : true, "AZ-CAL" : true, "AZ-CUL" : true, "AZ-DAS" : true, - "AZ-FUZ" : true, "AZ-GA" : true, "AZ-GAD" : true, "AZ-GOR" : true, "AZ-GOY" : true, - "AZ-GYG" : true, "AZ-HAC" : true, "AZ-IMI" : true, "AZ-ISM" : true, "AZ-KAL" : true, - "AZ-KAN" : true, "AZ-KUR" : true, "AZ-LA" : true, "AZ-LAC" : true, "AZ-LAN" : true, - "AZ-LER" : true, "AZ-MAS" : true, "AZ-MI" : true, "AZ-NA" : true, "AZ-NEF" : true, - "AZ-NV" : true, "AZ-NX" : true, "AZ-OGU" : true, "AZ-ORD" : true, "AZ-QAB" : true, - "AZ-QAX" : true, "AZ-QAZ" : true, "AZ-QBA" : true, "AZ-QBI" : true, "AZ-QOB" : true, - "AZ-QUS" : true, "AZ-SA" : true, "AZ-SAB" : true, "AZ-SAD" : true, "AZ-SAH" : true, - "AZ-SAK" : true, "AZ-SAL" : true, "AZ-SAR" : true, "AZ-SAT" : true, "AZ-SBN" : true, - "AZ-SIY" : true, "AZ-SKR" : true, "AZ-SM" : true, "AZ-SMI" : true, "AZ-SMX" : true, - "AZ-SR" : true, "AZ-SUS" : true, "AZ-TAR" : true, "AZ-TOV" : true, "AZ-UCA" : true, - "AZ-XA" : true, "AZ-XAC" : true, "AZ-XCI" : true, "AZ-XIZ" : true, "AZ-XVD" : true, - "AZ-YAR" : true, "AZ-YE" : true, "AZ-YEV" : true, "AZ-ZAN" : true, "AZ-ZAQ" : true, - "AZ-ZAR" : true, "BA-01" : true, "BA-02" : true, "BA-03" : true, "BA-04" : true, - "BA-05" : true, "BA-06" : true, "BA-07" : true, "BA-08" : true, "BA-09" : true, - "BA-10" : true, "BA-BIH" : true, "BA-BRC" : true, "BA-SRP" : true, "BB-01" : true, - "BB-02" : true, "BB-03" : true, "BB-04" : true, "BB-05" : true, "BB-06" : true, - "BB-07" : true, "BB-08" : true, "BB-09" : true, "BB-10" : true, "BB-11" : true, - "BD-01" : true, "BD-02" : true, "BD-03" : true, "BD-04" : true, "BD-05" : true, - "BD-06" : true, "BD-07" : true, "BD-08" : true, "BD-09" : true, "BD-10" : true, - "BD-11" : true, "BD-12" : true, "BD-13" : true, "BD-14" : true, "BD-15" : true, - "BD-16" : true, "BD-17" : true, "BD-18" : true, "BD-19" : true, "BD-20" : true, - "BD-21" : true, "BD-22" : true, "BD-23" : true, "BD-24" : true, "BD-25" : true, - "BD-26" : true, "BD-27" : true, "BD-28" : true, "BD-29" : true, "BD-30" : true, - "BD-31" : true, "BD-32" : true, "BD-33" : true, "BD-34" : true, "BD-35" : true, - "BD-36" : true, "BD-37" : true, "BD-38" : true, "BD-39" : true, "BD-40" : true, - "BD-41" : true, "BD-42" : true, "BD-43" : true, "BD-44" : true, "BD-45" : true, - "BD-46" : true, "BD-47" : true, "BD-48" : true, "BD-49" : true, "BD-50" : true, - "BD-51" : true, "BD-52" : true, "BD-53" : true, "BD-54" : true, "BD-55" : true, - "BD-56" : true, "BD-57" : true, "BD-58" : true, "BD-59" : true, "BD-60" : true, - "BD-61" : true, "BD-62" : true, "BD-63" : true, "BD-64" : true, "BD-A" : true, - "BD-B" : true, "BD-C" : true, "BD-D" : true, "BD-E" : true, "BD-F" : true, - "BD-G" : true, "BE-BRU" : true, "BE-VAN" : true, "BE-VBR" : true, "BE-VLG" : true, - "BE-VLI" : true, "BE-VOV" : true, "BE-VWV" : true, "BE-WAL" : true, "BE-WBR" : true, - "BE-WHT" : true, "BE-WLG" : true, "BE-WLX" : true, "BE-WNA" : true, "BF-01" : true, - "BF-02" : true, "BF-03" : true, "BF-04" : true, "BF-05" : true, "BF-06" : true, - "BF-07" : true, "BF-08" : true, "BF-09" : true, "BF-10" : true, "BF-11" : true, - "BF-12" : true, "BF-13" : true, "BF-BAL" : true, "BF-BAM" : true, "BF-BAN" : true, - "BF-BAZ" : true, "BF-BGR" : true, "BF-BLG" : true, "BF-BLK" : true, "BF-COM" : true, - "BF-GAN" : true, "BF-GNA" : true, "BF-GOU" : true, "BF-HOU" : true, "BF-IOB" : true, - "BF-KAD" : true, "BF-KEN" : true, "BF-KMD" : true, "BF-KMP" : true, "BF-KOP" : true, - "BF-KOS" : true, "BF-KOT" : true, "BF-KOW" : true, "BF-LER" : true, "BF-LOR" : true, - "BF-MOU" : true, "BF-NAM" : true, "BF-NAO" : true, "BF-NAY" : true, "BF-NOU" : true, - "BF-OUB" : true, "BF-OUD" : true, "BF-PAS" : true, "BF-PON" : true, "BF-SEN" : true, - "BF-SIS" : true, "BF-SMT" : true, "BF-SNG" : true, "BF-SOM" : true, "BF-SOR" : true, - "BF-TAP" : true, "BF-TUI" : true, "BF-YAG" : true, "BF-YAT" : true, "BF-ZIR" : true, - "BF-ZON" : true, "BF-ZOU" : true, "BG-01" : true, "BG-02" : true, "BG-03" : true, - "BG-04" : true, "BG-05" : true, "BG-06" : true, "BG-07" : true, "BG-08" : true, - "BG-09" : true, "BG-10" : true, "BG-11" : true, "BG-12" : true, "BG-13" : true, - "BG-14" : true, "BG-15" : true, "BG-16" : true, "BG-17" : true, "BG-18" : true, - "BG-19" : true, "BG-20" : true, "BG-21" : true, "BG-22" : true, "BG-23" : true, - "BG-24" : true, "BG-25" : true, "BG-26" : true, "BG-27" : true, "BG-28" : true, - "BH-13" : true, "BH-14" : true, "BH-15" : true, "BH-16" : true, "BH-17" : true, - "BI-BB" : true, "BI-BL" : true, "BI-BM" : true, "BI-BR" : true, "BI-CA" : true, - "BI-CI" : true, "BI-GI" : true, "BI-KI" : true, "BI-KR" : true, "BI-KY" : true, - "BI-MA" : true, "BI-MU" : true, "BI-MW" : true, "BI-NG" : true, "BI-RT" : true, - "BI-RY" : true, "BJ-AK" : true, "BJ-AL" : true, "BJ-AQ" : true, "BJ-BO" : true, - "BJ-CO" : true, "BJ-DO" : true, "BJ-KO" : true, "BJ-LI" : true, "BJ-MO" : true, - "BJ-OU" : true, "BJ-PL" : true, "BJ-ZO" : true, "BN-BE" : true, "BN-BM" : true, - "BN-TE" : true, "BN-TU" : true, "BO-B" : true, "BO-C" : true, "BO-H" : true, - "BO-L" : true, "BO-N" : true, "BO-O" : true, "BO-P" : true, "BO-S" : true, - "BO-T" : true, "BQ-BO" : true, "BQ-SA" : true, "BQ-SE" : true, "BR-AC" : true, - "BR-AL" : true, "BR-AM" : true, "BR-AP" : true, "BR-BA" : true, "BR-CE" : true, - "BR-DF" : true, "BR-ES" : true, "BR-FN" : true, "BR-GO" : true, "BR-MA" : true, - "BR-MG" : true, "BR-MS" : true, "BR-MT" : true, "BR-PA" : true, "BR-PB" : true, - "BR-PE" : true, "BR-PI" : true, "BR-PR" : true, "BR-RJ" : true, "BR-RN" : true, - "BR-RO" : true, "BR-RR" : true, "BR-RS" : true, "BR-SC" : true, "BR-SE" : true, - "BR-SP" : true, "BR-TO" : true, "BS-AK" : true, "BS-BI" : true, "BS-BP" : true, - "BS-BY" : true, "BS-CE" : true, "BS-CI" : true, "BS-CK" : true, "BS-CO" : true, - "BS-CS" : true, "BS-EG" : true, "BS-EX" : true, "BS-FP" : true, "BS-GC" : true, - "BS-HI" : true, "BS-HT" : true, "BS-IN" : true, "BS-LI" : true, "BS-MC" : true, - "BS-MG" : true, "BS-MI" : true, "BS-NE" : true, "BS-NO" : true, "BS-NS" : true, - "BS-RC" : true, "BS-RI" : true, "BS-SA" : true, "BS-SE" : true, "BS-SO" : true, - "BS-SS" : true, "BS-SW" : true, "BS-WG" : true, "BT-11" : true, "BT-12" : true, - "BT-13" : true, "BT-14" : true, "BT-15" : true, "BT-21" : true, "BT-22" : true, - "BT-23" : true, "BT-24" : true, "BT-31" : true, "BT-32" : true, "BT-33" : true, - "BT-34" : true, "BT-41" : true, "BT-42" : true, "BT-43" : true, "BT-44" : true, - "BT-45" : true, "BT-GA" : true, "BT-TY" : true, "BW-CE" : true, "BW-GH" : true, - "BW-KG" : true, "BW-KL" : true, "BW-KW" : true, "BW-NE" : true, "BW-NW" : true, - "BW-SE" : true, "BW-SO" : true, "BY-BR" : true, "BY-HM" : true, "BY-HO" : true, - "BY-HR" : true, "BY-MA" : true, "BY-MI" : true, "BY-VI" : true, "BZ-BZ" : true, - "BZ-CY" : true, "BZ-CZL" : true, "BZ-OW" : true, "BZ-SC" : true, "BZ-TOL" : true, - "CA-AB" : true, "CA-BC" : true, "CA-MB" : true, "CA-NB" : true, "CA-NL" : true, - "CA-NS" : true, "CA-NT" : true, "CA-NU" : true, "CA-ON" : true, "CA-PE" : true, - "CA-QC" : true, "CA-SK" : true, "CA-YT" : true, "CD-BC" : true, "CD-BN" : true, - "CD-EQ" : true, "CD-KA" : true, "CD-KE" : true, "CD-KN" : true, "CD-KW" : true, - "CD-MA" : true, "CD-NK" : true, "CD-OR" : true, "CD-SK" : true, "CF-AC" : true, - "CF-BB" : true, "CF-BGF" : true, "CF-BK" : true, "CF-HK" : true, "CF-HM" : true, - "CF-HS" : true, "CF-KB" : true, "CF-KG" : true, "CF-LB" : true, "CF-MB" : true, - "CF-MP" : true, "CF-NM" : true, "CF-OP" : true, "CF-SE" : true, "CF-UK" : true, - "CF-VK" : true, "CG-11" : true, "CG-12" : true, "CG-13" : true, "CG-14" : true, - "CG-15" : true, "CG-2" : true, "CG-5" : true, "CG-7" : true, "CG-8" : true, - "CG-9" : true, "CG-BZV" : true, "CH-AG" : true, "CH-AI" : true, "CH-AR" : true, - "CH-BE" : true, "CH-BL" : true, "CH-BS" : true, "CH-FR" : true, "CH-GE" : true, - "CH-GL" : true, "CH-GR" : true, "CH-JU" : true, "CH-LU" : true, "CH-NE" : true, - "CH-NW" : true, "CH-OW" : true, "CH-SG" : true, "CH-SH" : true, "CH-SO" : true, - "CH-SZ" : true, "CH-TG" : true, "CH-TI" : true, "CH-UR" : true, "CH-VD" : true, - "CH-VS" : true, "CH-ZG" : true, "CH-ZH" : true, "CI-01" : true, "CI-02" : true, - "CI-03" : true, "CI-04" : true, "CI-05" : true, "CI-06" : true, "CI-07" : true, - "CI-08" : true, "CI-09" : true, "CI-10" : true, "CI-11" : true, "CI-12" : true, - "CI-13" : true, "CI-14" : true, "CI-15" : true, "CI-16" : true, "CI-17" : true, - "CI-18" : true, "CI-19" : true, "CL-AI" : true, "CL-AN" : true, "CL-AP" : true, - "CL-AR" : true, "CL-AT" : true, "CL-BI" : true, "CL-CO" : true, "CL-LI" : true, - "CL-LL" : true, "CL-LR" : true, "CL-MA" : true, "CL-ML" : true, "CL-RM" : true, - "CL-TA" : true, "CL-VS" : true, "CM-AD" : true, "CM-CE" : true, "CM-EN" : true, - "CM-ES" : true, "CM-LT" : true, "CM-NO" : true, "CM-NW" : true, "CM-OU" : true, - "CM-SU" : true, "CM-SW" : true, "CN-11" : true, "CN-12" : true, "CN-13" : true, - "CN-14" : true, "CN-15" : true, "CN-21" : true, "CN-22" : true, "CN-23" : true, - "CN-31" : true, "CN-32" : true, "CN-33" : true, "CN-34" : true, "CN-35" : true, - "CN-36" : true, "CN-37" : true, "CN-41" : true, "CN-42" : true, "CN-43" : true, - "CN-44" : true, "CN-45" : true, "CN-46" : true, "CN-50" : true, "CN-51" : true, - "CN-52" : true, "CN-53" : true, "CN-54" : true, "CN-61" : true, "CN-62" : true, - "CN-63" : true, "CN-64" : true, "CN-65" : true, "CN-71" : true, "CN-91" : true, - "CN-92" : true, "CO-AMA" : true, "CO-ANT" : true, "CO-ARA" : true, "CO-ATL" : true, - "CO-BOL" : true, "CO-BOY" : true, "CO-CAL" : true, "CO-CAQ" : true, "CO-CAS" : true, - "CO-CAU" : true, "CO-CES" : true, "CO-CHO" : true, "CO-COR" : true, "CO-CUN" : true, - "CO-DC" : true, "CO-GUA" : true, "CO-GUV" : true, "CO-HUI" : true, "CO-LAG" : true, - "CO-MAG" : true, "CO-MET" : true, "CO-NAR" : true, "CO-NSA" : true, "CO-PUT" : true, - "CO-QUI" : true, "CO-RIS" : true, "CO-SAN" : true, "CO-SAP" : true, "CO-SUC" : true, - "CO-TOL" : true, "CO-VAC" : true, "CO-VAU" : true, "CO-VID" : true, "CR-A" : true, - "CR-C" : true, "CR-G" : true, "CR-H" : true, "CR-L" : true, "CR-P" : true, - "CR-SJ" : true, "CU-01" : true, "CU-02" : true, "CU-03" : true, "CU-04" : true, - "CU-05" : true, "CU-06" : true, "CU-07" : true, "CU-08" : true, "CU-09" : true, - "CU-10" : true, "CU-11" : true, "CU-12" : true, "CU-13" : true, "CU-14" : true, - "CU-99" : true, "CV-B" : true, "CV-BR" : true, "CV-BV" : true, "CV-CA" : true, - "CV-CF" : true, "CV-CR" : true, "CV-MA" : true, "CV-MO" : true, "CV-PA" : true, - "CV-PN" : true, "CV-PR" : true, "CV-RB" : true, "CV-RG" : true, "CV-RS" : true, - "CV-S" : true, "CV-SD" : true, "CV-SF" : true, "CV-SL" : true, "CV-SM" : true, - "CV-SO" : true, "CV-SS" : true, "CV-SV" : true, "CV-TA" : true, "CV-TS" : true, - "CY-01" : true, "CY-02" : true, "CY-03" : true, "CY-04" : true, "CY-05" : true, - "CY-06" : true, "CZ-10" : true, "CZ-101" : true, "CZ-102" : true, "CZ-103" : true, - "CZ-104" : true, "CZ-105" : true, "CZ-106" : true, "CZ-107" : true, "CZ-108" : true, - "CZ-109" : true, "CZ-110" : true, "CZ-111" : true, "CZ-112" : true, "CZ-113" : true, - "CZ-114" : true, "CZ-115" : true, "CZ-116" : true, "CZ-117" : true, "CZ-118" : true, - "CZ-119" : true, "CZ-120" : true, "CZ-121" : true, "CZ-122" : true, "CZ-20" : true, - "CZ-201" : true, "CZ-202" : true, "CZ-203" : true, "CZ-204" : true, "CZ-205" : true, - "CZ-206" : true, "CZ-207" : true, "CZ-208" : true, "CZ-209" : true, "CZ-20A" : true, - "CZ-20B" : true, "CZ-20C" : true, "CZ-31" : true, "CZ-311" : true, "CZ-312" : true, - "CZ-313" : true, "CZ-314" : true, "CZ-315" : true, "CZ-316" : true, "CZ-317" : true, - "CZ-32" : true, "CZ-321" : true, "CZ-322" : true, "CZ-323" : true, "CZ-324" : true, - "CZ-325" : true, "CZ-326" : true, "CZ-327" : true, "CZ-41" : true, "CZ-411" : true, - "CZ-412" : true, "CZ-413" : true, "CZ-42" : true, "CZ-421" : true, "CZ-422" : true, - "CZ-423" : true, "CZ-424" : true, "CZ-425" : true, "CZ-426" : true, "CZ-427" : true, - "CZ-51" : true, "CZ-511" : true, "CZ-512" : true, "CZ-513" : true, "CZ-514" : true, - "CZ-52" : true, "CZ-521" : true, "CZ-522" : true, "CZ-523" : true, "CZ-524" : true, - "CZ-525" : true, "CZ-53" : true, "CZ-531" : true, "CZ-532" : true, "CZ-533" : true, - "CZ-534" : true, "CZ-63" : true, "CZ-631" : true, "CZ-632" : true, "CZ-633" : true, - "CZ-634" : true, "CZ-635" : true, "CZ-64" : true, "CZ-641" : true, "CZ-642" : true, - "CZ-643" : true, "CZ-644" : true, "CZ-645" : true, "CZ-646" : true, "CZ-647" : true, - "CZ-71" : true, "CZ-711" : true, "CZ-712" : true, "CZ-713" : true, "CZ-714" : true, - "CZ-715" : true, "CZ-72" : true, "CZ-721" : true, "CZ-722" : true, "CZ-723" : true, - "CZ-724" : true, "CZ-80" : true, "CZ-801" : true, "CZ-802" : true, "CZ-803" : true, - "CZ-804" : true, "CZ-805" : true, "CZ-806" : true, "DE-BB" : true, "DE-BE" : true, - "DE-BW" : true, "DE-BY" : true, "DE-HB" : true, "DE-HE" : true, "DE-HH" : true, - "DE-MV" : true, "DE-NI" : true, "DE-NW" : true, "DE-RP" : true, "DE-SH" : true, - "DE-SL" : true, "DE-SN" : true, "DE-ST" : true, "DE-TH" : true, "DJ-AR" : true, - "DJ-AS" : true, "DJ-DI" : true, "DJ-DJ" : true, "DJ-OB" : true, "DJ-TA" : true, - "DK-81" : true, "DK-82" : true, "DK-83" : true, "DK-84" : true, "DK-85" : true, - "DM-01" : true, "DM-02" : true, "DM-03" : true, "DM-04" : true, "DM-05" : true, - "DM-06" : true, "DM-07" : true, "DM-08" : true, "DM-09" : true, "DM-10" : true, - "DO-01" : true, "DO-02" : true, "DO-03" : true, "DO-04" : true, "DO-05" : true, - "DO-06" : true, "DO-07" : true, "DO-08" : true, "DO-09" : true, "DO-10" : true, - "DO-11" : true, "DO-12" : true, "DO-13" : true, "DO-14" : true, "DO-15" : true, - "DO-16" : true, "DO-17" : true, "DO-18" : true, "DO-19" : true, "DO-20" : true, - "DO-21" : true, "DO-22" : true, "DO-23" : true, "DO-24" : true, "DO-25" : true, - "DO-26" : true, "DO-27" : true, "DO-28" : true, "DO-29" : true, "DO-30" : true, - "DZ-01" : true, "DZ-02" : true, "DZ-03" : true, "DZ-04" : true, "DZ-05" : true, - "DZ-06" : true, "DZ-07" : true, "DZ-08" : true, "DZ-09" : true, "DZ-10" : true, - "DZ-11" : true, "DZ-12" : true, "DZ-13" : true, "DZ-14" : true, "DZ-15" : true, - "DZ-16" : true, "DZ-17" : true, "DZ-18" : true, "DZ-19" : true, "DZ-20" : true, - "DZ-21" : true, "DZ-22" : true, "DZ-23" : true, "DZ-24" : true, "DZ-25" : true, - "DZ-26" : true, "DZ-27" : true, "DZ-28" : true, "DZ-29" : true, "DZ-30" : true, - "DZ-31" : true, "DZ-32" : true, "DZ-33" : true, "DZ-34" : true, "DZ-35" : true, - "DZ-36" : true, "DZ-37" : true, "DZ-38" : true, "DZ-39" : true, "DZ-40" : true, - "DZ-41" : true, "DZ-42" : true, "DZ-43" : true, "DZ-44" : true, "DZ-45" : true, - "DZ-46" : true, "DZ-47" : true, "DZ-48" : true, "EC-A" : true, "EC-B" : true, - "EC-C" : true, "EC-D" : true, "EC-E" : true, "EC-F" : true, "EC-G" : true, - "EC-H" : true, "EC-I" : true, "EC-L" : true, "EC-M" : true, "EC-N" : true, - "EC-O" : true, "EC-P" : true, "EC-R" : true, "EC-S" : true, "EC-SD" : true, - "EC-SE" : true, "EC-T" : true, "EC-U" : true, "EC-W" : true, "EC-X" : true, - "EC-Y" : true, "EC-Z" : true, "EE-37" : true, "EE-39" : true, "EE-44" : true, - "EE-49" : true, "EE-51" : true, "EE-57" : true, "EE-59" : true, "EE-65" : true, - "EE-67" : true, "EE-70" : true, "EE-74" : true, "EE-78" : true, "EE-82" : true, - "EE-84" : true, "EE-86" : true, "EG-ALX" : true, "EG-ASN" : true, "EG-AST" : true, - "EG-BA" : true, "EG-BH" : true, "EG-BNS" : true, "EG-C" : true, "EG-DK" : true, - "EG-DT" : true, "EG-FYM" : true, "EG-GH" : true, "EG-GZ" : true, "EG-HU" : true, - "EG-IS" : true, "EG-JS" : true, "EG-KB" : true, "EG-KFS" : true, "EG-KN" : true, - "EG-MN" : true, "EG-MNF" : true, "EG-MT" : true, "EG-PTS" : true, "EG-SHG" : true, - "EG-SHR" : true, "EG-SIN" : true, "EG-SU" : true, "EG-SUZ" : true, "EG-WAD" : true, - "ER-AN" : true, "ER-DK" : true, "ER-DU" : true, "ER-GB" : true, "ER-MA" : true, - "ER-SK" : true, "ES-A" : true, "ES-AB" : true, "ES-AL" : true, "ES-AN" : true, - "ES-AR" : true, "ES-AS" : true, "ES-AV" : true, "ES-B" : true, "ES-BA" : true, - "ES-BI" : true, "ES-BU" : true, "ES-C" : true, "ES-CA" : true, "ES-CB" : true, - "ES-CC" : true, "ES-CE" : true, "ES-CL" : true, "ES-CM" : true, "ES-CN" : true, - "ES-CO" : true, "ES-CR" : true, "ES-CS" : true, "ES-CT" : true, "ES-CU" : true, - "ES-EX" : true, "ES-GA" : true, "ES-GC" : true, "ES-GI" : true, "ES-GR" : true, - "ES-GU" : true, "ES-H" : true, "ES-HU" : true, "ES-IB" : true, "ES-J" : true, - "ES-L" : true, "ES-LE" : true, "ES-LO" : true, "ES-LU" : true, "ES-M" : true, - "ES-MA" : true, "ES-MC" : true, "ES-MD" : true, "ES-ML" : true, "ES-MU" : true, - "ES-NA" : true, "ES-NC" : true, "ES-O" : true, "ES-OR" : true, "ES-P" : true, - "ES-PM" : true, "ES-PO" : true, "ES-PV" : true, "ES-RI" : true, "ES-S" : true, - "ES-SA" : true, "ES-SE" : true, "ES-SG" : true, "ES-SO" : true, "ES-SS" : true, - "ES-T" : true, "ES-TE" : true, "ES-TF" : true, "ES-TO" : true, "ES-V" : true, - "ES-VA" : true, "ES-VC" : true, "ES-VI" : true, "ES-Z" : true, "ES-ZA" : true, - "ET-AA" : true, "ET-AF" : true, "ET-AM" : true, "ET-BE" : true, "ET-DD" : true, - "ET-GA" : true, "ET-HA" : true, "ET-OR" : true, "ET-SN" : true, "ET-SO" : true, - "ET-TI" : true, "FI-01" : true, "FI-02" : true, "FI-03" : true, "FI-04" : true, - "FI-05" : true, "FI-06" : true, "FI-07" : true, "FI-08" : true, "FI-09" : true, - "FI-10" : true, "FI-11" : true, "FI-12" : true, "FI-13" : true, "FI-14" : true, - "FI-15" : true, "FI-16" : true, "FI-17" : true, "FI-18" : true, "FI-19" : true, - "FJ-C" : true, "FJ-E" : true, "FJ-N" : true, "FJ-R" : true, "FJ-W" : true, - "FM-KSA" : true, "FM-PNI" : true, "FM-TRK" : true, "FM-YAP" : true, "FR-01" : true, - "FR-02" : true, "FR-03" : true, "FR-04" : true, "FR-05" : true, "FR-06" : true, - "FR-07" : true, "FR-08" : true, "FR-09" : true, "FR-10" : true, "FR-11" : true, - "FR-12" : true, "FR-13" : true, "FR-14" : true, "FR-15" : true, "FR-16" : true, - "FR-17" : true, "FR-18" : true, "FR-19" : true, "FR-21" : true, "FR-22" : true, - "FR-23" : true, "FR-24" : true, "FR-25" : true, "FR-26" : true, "FR-27" : true, - "FR-28" : true, "FR-29" : true, "FR-2A" : true, "FR-2B" : true, "FR-30" : true, - "FR-31" : true, "FR-32" : true, "FR-33" : true, "FR-34" : true, "FR-35" : true, - "FR-36" : true, "FR-37" : true, "FR-38" : true, "FR-39" : true, "FR-40" : true, - "FR-41" : true, "FR-42" : true, "FR-43" : true, "FR-44" : true, "FR-45" : true, - "FR-46" : true, "FR-47" : true, "FR-48" : true, "FR-49" : true, "FR-50" : true, - "FR-51" : true, "FR-52" : true, "FR-53" : true, "FR-54" : true, "FR-55" : true, - "FR-56" : true, "FR-57" : true, "FR-58" : true, "FR-59" : true, "FR-60" : true, - "FR-61" : true, "FR-62" : true, "FR-63" : true, "FR-64" : true, "FR-65" : true, - "FR-66" : true, "FR-67" : true, "FR-68" : true, "FR-69" : true, "FR-70" : true, - "FR-71" : true, "FR-72" : true, "FR-73" : true, "FR-74" : true, "FR-75" : true, - "FR-76" : true, "FR-77" : true, "FR-78" : true, "FR-79" : true, "FR-80" : true, - "FR-81" : true, "FR-82" : true, "FR-83" : true, "FR-84" : true, "FR-85" : true, - "FR-86" : true, "FR-87" : true, "FR-88" : true, "FR-89" : true, "FR-90" : true, - "FR-91" : true, "FR-92" : true, "FR-93" : true, "FR-94" : true, "FR-95" : true, - "FR-ARA" : true, "FR-BFC" : true, "FR-BL" : true, "FR-BRE" : true, "FR-COR" : true, - "FR-CP" : true, "FR-CVL" : true, "FR-GES" : true, "FR-GF" : true, "FR-GP" : true, - "FR-GUA" : true, "FR-HDF" : true, "FR-IDF" : true, "FR-LRE" : true, "FR-MAY" : true, - "FR-MF" : true, "FR-MQ" : true, "FR-NAQ" : true, "FR-NC" : true, "FR-NOR" : true, - "FR-OCC" : true, "FR-PAC" : true, "FR-PDL" : true, "FR-PF" : true, "FR-PM" : true, - "FR-RE" : true, "FR-TF" : true, "FR-WF" : true, "FR-YT" : true, "GA-1" : true, - "GA-2" : true, "GA-3" : true, "GA-4" : true, "GA-5" : true, "GA-6" : true, - "GA-7" : true, "GA-8" : true, "GA-9" : true, "GB-ABC" : true, "GB-ABD" : true, - "GB-ABE" : true, "GB-AGB" : true, "GB-AGY" : true, "GB-AND" : true, "GB-ANN" : true, - "GB-ANS" : true, "GB-BAS" : true, "GB-BBD" : true, "GB-BDF" : true, "GB-BDG" : true, - "GB-BEN" : true, "GB-BEX" : true, "GB-BFS" : true, "GB-BGE" : true, "GB-BGW" : true, - "GB-BIR" : true, "GB-BKM" : true, "GB-BMH" : true, "GB-BNE" : true, "GB-BNH" : true, - "GB-BNS" : true, "GB-BOL" : true, "GB-BPL" : true, "GB-BRC" : true, "GB-BRD" : true, - "GB-BRY" : true, "GB-BST" : true, "GB-BUR" : true, "GB-CAM" : true, "GB-CAY" : true, - "GB-CBF" : true, "GB-CCG" : true, "GB-CGN" : true, "GB-CHE" : true, "GB-CHW" : true, - "GB-CLD" : true, "GB-CLK" : true, "GB-CMA" : true, "GB-CMD" : true, "GB-CMN" : true, - "GB-CON" : true, "GB-COV" : true, "GB-CRF" : true, "GB-CRY" : true, "GB-CWY" : true, - "GB-DAL" : true, "GB-DBY" : true, "GB-DEN" : true, "GB-DER" : true, "GB-DEV" : true, - "GB-DGY" : true, "GB-DNC" : true, "GB-DND" : true, "GB-DOR" : true, "GB-DRS" : true, - "GB-DUD" : true, "GB-DUR" : true, "GB-EAL" : true, "GB-EAW" : true, "GB-EAY" : true, - "GB-EDH" : true, "GB-EDU" : true, "GB-ELN" : true, "GB-ELS" : true, "GB-ENF" : true, - "GB-ENG" : true, "GB-ERW" : true, "GB-ERY" : true, "GB-ESS" : true, "GB-ESX" : true, - "GB-FAL" : true, "GB-FIF" : true, "GB-FLN" : true, "GB-FMO" : true, "GB-GAT" : true, - "GB-GBN" : true, "GB-GLG" : true, "GB-GLS" : true, "GB-GRE" : true, "GB-GWN" : true, - "GB-HAL" : true, "GB-HAM" : true, "GB-HAV" : true, "GB-HCK" : true, "GB-HEF" : true, - "GB-HIL" : true, "GB-HLD" : true, "GB-HMF" : true, "GB-HNS" : true, "GB-HPL" : true, - "GB-HRT" : true, "GB-HRW" : true, "GB-HRY" : true, "GB-IOS" : true, "GB-IOW" : true, - "GB-ISL" : true, "GB-IVC" : true, "GB-KEC" : true, "GB-KEN" : true, "GB-KHL" : true, - "GB-KIR" : true, "GB-KTT" : true, "GB-KWL" : true, "GB-LAN" : true, "GB-LBC" : true, - "GB-LBH" : true, "GB-LCE" : true, "GB-LDS" : true, "GB-LEC" : true, "GB-LEW" : true, - "GB-LIN" : true, "GB-LIV" : true, "GB-LND" : true, "GB-LUT" : true, "GB-MAN" : true, - "GB-MDB" : true, "GB-MDW" : true, "GB-MEA" : true, "GB-MIK" : true, "GD-01" : true, - "GB-MLN" : true, "GB-MON" : true, "GB-MRT" : true, "GB-MRY" : true, "GB-MTY" : true, - "GB-MUL" : true, "GB-NAY" : true, "GB-NBL" : true, "GB-NEL" : true, "GB-NET" : true, - "GB-NFK" : true, "GB-NGM" : true, "GB-NIR" : true, "GB-NLK" : true, "GB-NLN" : true, - "GB-NMD" : true, "GB-NSM" : true, "GB-NTH" : true, "GB-NTL" : true, "GB-NTT" : true, - "GB-NTY" : true, "GB-NWM" : true, "GB-NWP" : true, "GB-NYK" : true, "GB-OLD" : true, - "GB-ORK" : true, "GB-OXF" : true, "GB-PEM" : true, "GB-PKN" : true, "GB-PLY" : true, - "GB-POL" : true, "GB-POR" : true, "GB-POW" : true, "GB-PTE" : true, "GB-RCC" : true, - "GB-RCH" : true, "GB-RCT" : true, "GB-RDB" : true, "GB-RDG" : true, "GB-RFW" : true, - "GB-RIC" : true, "GB-ROT" : true, "GB-RUT" : true, "GB-SAW" : true, "GB-SAY" : true, - "GB-SCB" : true, "GB-SCT" : true, "GB-SFK" : true, "GB-SFT" : true, "GB-SGC" : true, - "GB-SHF" : true, "GB-SHN" : true, "GB-SHR" : true, "GB-SKP" : true, "GB-SLF" : true, - "GB-SLG" : true, "GB-SLK" : true, "GB-SND" : true, "GB-SOL" : true, "GB-SOM" : true, - "GB-SOS" : true, "GB-SRY" : true, "GB-STE" : true, "GB-STG" : true, "GB-STH" : true, - "GB-STN" : true, "GB-STS" : true, "GB-STT" : true, "GB-STY" : true, "GB-SWA" : true, - "GB-SWD" : true, "GB-SWK" : true, "GB-TAM" : true, "GB-TFW" : true, "GB-THR" : true, - "GB-TOB" : true, "GB-TOF" : true, "GB-TRF" : true, "GB-TWH" : true, "GB-UKM" : true, - "GB-VGL" : true, "GB-WAR" : true, "GB-WBK" : true, "GB-WDU" : true, "GB-WFT" : true, - "GB-WGN" : true, "GB-WIL" : true, "GB-WKF" : true, "GB-WLL" : true, "GB-WLN" : true, - "GB-WLS" : true, "GB-WLV" : true, "GB-WND" : true, "GB-WNM" : true, "GB-WOK" : true, - "GB-WOR" : true, "GB-WRL" : true, "GB-WRT" : true, "GB-WRX" : true, "GB-WSM" : true, - "GB-WSX" : true, "GB-YOR" : true, "GB-ZET" : true, "GD-02" : true, "GD-03" : true, - "GD-04" : true, "GD-05" : true, "GD-06" : true, "GD-10" : true, "GE-AB" : true, - "GE-AJ" : true, "GE-GU" : true, "GE-IM" : true, "GE-KA" : true, "GE-KK" : true, - "GE-MM" : true, "GE-RL" : true, "GE-SJ" : true, "GE-SK" : true, "GE-SZ" : true, - "GE-TB" : true, "GH-AA" : true, "GH-AH" : true, "GH-BA" : true, "GH-CP" : true, - "GH-EP" : true, "GH-NP" : true, "GH-TV" : true, "GH-UE" : true, "GH-UW" : true, - "GH-WP" : true, "GL-KU" : true, "GL-QA" : true, "GL-QE" : true, "GL-SM" : true, - "GM-B" : true, "GM-L" : true, "GM-M" : true, "GM-N" : true, "GM-U" : true, - "GM-W" : true, "GN-B" : true, "GN-BE" : true, "GN-BF" : true, "GN-BK" : true, - "GN-C" : true, "GN-CO" : true, "GN-D" : true, "GN-DB" : true, "GN-DI" : true, - "GN-DL" : true, "GN-DU" : true, "GN-F" : true, "GN-FA" : true, "GN-FO" : true, - "GN-FR" : true, "GN-GA" : true, "GN-GU" : true, "GN-K" : true, "GN-KA" : true, - "GN-KB" : true, "GN-KD" : true, "GN-KE" : true, "GN-KN" : true, "GN-KO" : true, - "GN-KS" : true, "GN-L" : true, "GN-LA" : true, "GN-LE" : true, "GN-LO" : true, - "GN-M" : true, "GN-MC" : true, "GN-MD" : true, "GN-ML" : true, "GN-MM" : true, - "GN-N" : true, "GN-NZ" : true, "GN-PI" : true, "GN-SI" : true, "GN-TE" : true, - "GN-TO" : true, "GN-YO" : true, "GQ-AN" : true, "GQ-BN" : true, "GQ-BS" : true, - "GQ-C" : true, "GQ-CS" : true, "GQ-I" : true, "GQ-KN" : true, "GQ-LI" : true, - "GQ-WN" : true, "GR-01" : true, "GR-03" : true, "GR-04" : true, "GR-05" : true, - "GR-06" : true, "GR-07" : true, "GR-11" : true, "GR-12" : true, "GR-13" : true, - "GR-14" : true, "GR-15" : true, "GR-16" : true, "GR-17" : true, "GR-21" : true, - "GR-22" : true, "GR-23" : true, "GR-24" : true, "GR-31" : true, "GR-32" : true, - "GR-33" : true, "GR-34" : true, "GR-41" : true, "GR-42" : true, "GR-43" : true, - "GR-44" : true, "GR-51" : true, "GR-52" : true, "GR-53" : true, "GR-54" : true, - "GR-55" : true, "GR-56" : true, "GR-57" : true, "GR-58" : true, "GR-59" : true, - "GR-61" : true, "GR-62" : true, "GR-63" : true, "GR-64" : true, "GR-69" : true, - "GR-71" : true, "GR-72" : true, "GR-73" : true, "GR-81" : true, "GR-82" : true, - "GR-83" : true, "GR-84" : true, "GR-85" : true, "GR-91" : true, "GR-92" : true, - "GR-93" : true, "GR-94" : true, "GR-A" : true, "GR-A1" : true, "GR-B" : true, - "GR-C" : true, "GR-D" : true, "GR-E" : true, "GR-F" : true, "GR-G" : true, - "GR-H" : true, "GR-I" : true, "GR-J" : true, "GR-K" : true, "GR-L" : true, - "GR-M" : true, "GT-AV" : true, "GT-BV" : true, "GT-CM" : true, "GT-CQ" : true, - "GT-ES" : true, "GT-GU" : true, "GT-HU" : true, "GT-IZ" : true, "GT-JA" : true, - "GT-JU" : true, "GT-PE" : true, "GT-PR" : true, "GT-QC" : true, "GT-QZ" : true, - "GT-RE" : true, "GT-SA" : true, "GT-SM" : true, "GT-SO" : true, "GT-SR" : true, - "GT-SU" : true, "GT-TO" : true, "GT-ZA" : true, "GW-BA" : true, "GW-BL" : true, - "GW-BM" : true, "GW-BS" : true, "GW-CA" : true, "GW-GA" : true, "GW-L" : true, - "GW-N" : true, "GW-OI" : true, "GW-QU" : true, "GW-S" : true, "GW-TO" : true, - "GY-BA" : true, "GY-CU" : true, "GY-DE" : true, "GY-EB" : true, "GY-ES" : true, - "GY-MA" : true, "GY-PM" : true, "GY-PT" : true, "GY-UD" : true, "GY-UT" : true, - "HN-AT" : true, "HN-CH" : true, "HN-CL" : true, "HN-CM" : true, "HN-CP" : true, - "HN-CR" : true, "HN-EP" : true, "HN-FM" : true, "HN-GD" : true, "HN-IB" : true, - "HN-IN" : true, "HN-LE" : true, "HN-LP" : true, "HN-OC" : true, "HN-OL" : true, - "HN-SB" : true, "HN-VA" : true, "HN-YO" : true, "HR-01" : true, "HR-02" : true, - "HR-03" : true, "HR-04" : true, "HR-05" : true, "HR-06" : true, "HR-07" : true, - "HR-08" : true, "HR-09" : true, "HR-10" : true, "HR-11" : true, "HR-12" : true, - "HR-13" : true, "HR-14" : true, "HR-15" : true, "HR-16" : true, "HR-17" : true, - "HR-18" : true, "HR-19" : true, "HR-20" : true, "HR-21" : true, "HT-AR" : true, - "HT-CE" : true, "HT-GA" : true, "HT-ND" : true, "HT-NE" : true, "HT-NO" : true, - "HT-OU" : true, "HT-SD" : true, "HT-SE" : true, "HU-BA" : true, "HU-BC" : true, - "HU-BE" : true, "HU-BK" : true, "HU-BU" : true, "HU-BZ" : true, "HU-CS" : true, - "HU-DE" : true, "HU-DU" : true, "HU-EG" : true, "HU-ER" : true, "HU-FE" : true, - "HU-GS" : true, "HU-GY" : true, "HU-HB" : true, "HU-HE" : true, "HU-HV" : true, - "HU-JN" : true, "HU-KE" : true, "HU-KM" : true, "HU-KV" : true, "HU-MI" : true, - "HU-NK" : true, "HU-NO" : true, "HU-NY" : true, "HU-PE" : true, "HU-PS" : true, - "HU-SD" : true, "HU-SF" : true, "HU-SH" : true, "HU-SK" : true, "HU-SN" : true, - "HU-SO" : true, "HU-SS" : true, "HU-ST" : true, "HU-SZ" : true, "HU-TB" : true, - "HU-TO" : true, "HU-VA" : true, "HU-VE" : true, "HU-VM" : true, "HU-ZA" : true, - "HU-ZE" : true, "ID-AC" : true, "ID-BA" : true, "ID-BB" : true, "ID-BE" : true, - "ID-BT" : true, "ID-GO" : true, "ID-IJ" : true, "ID-JA" : true, "ID-JB" : true, - "ID-JI" : true, "ID-JK" : true, "ID-JT" : true, "ID-JW" : true, "ID-KA" : true, - "ID-KB" : true, "ID-KI" : true, "ID-KR" : true, "ID-KS" : true, "ID-KT" : true, - "ID-LA" : true, "ID-MA" : true, "ID-ML" : true, "ID-MU" : true, "ID-NB" : true, - "ID-NT" : true, "ID-NU" : true, "ID-PA" : true, "ID-PB" : true, "ID-RI" : true, - "ID-SA" : true, "ID-SB" : true, "ID-SG" : true, "ID-SL" : true, "ID-SM" : true, - "ID-SN" : true, "ID-SR" : true, "ID-SS" : true, "ID-ST" : true, "ID-SU" : true, - "ID-YO" : true, "IE-C" : true, "IE-CE" : true, "IE-CN" : true, "IE-CO" : true, - "IE-CW" : true, "IE-D" : true, "IE-DL" : true, "IE-G" : true, "IE-KE" : true, - "IE-KK" : true, "IE-KY" : true, "IE-L" : true, "IE-LD" : true, "IE-LH" : true, - "IE-LK" : true, "IE-LM" : true, "IE-LS" : true, "IE-M" : true, "IE-MH" : true, - "IE-MN" : true, "IE-MO" : true, "IE-OY" : true, "IE-RN" : true, "IE-SO" : true, - "IE-TA" : true, "IE-U" : true, "IE-WD" : true, "IE-WH" : true, "IE-WW" : true, - "IE-WX" : true, "IL-D" : true, "IL-HA" : true, "IL-JM" : true, "IL-M" : true, - "IL-TA" : true, "IL-Z" : true, "IN-AN" : true, "IN-AP" : true, "IN-AR" : true, - "IN-AS" : true, "IN-BR" : true, "IN-CH" : true, "IN-CT" : true, "IN-DD" : true, - "IN-DL" : true, "IN-DN" : true, "IN-GA" : true, "IN-GJ" : true, "IN-HP" : true, - "IN-HR" : true, "IN-JH" : true, "IN-JK" : true, "IN-KA" : true, "IN-KL" : true, - "IN-LD" : true, "IN-MH" : true, "IN-ML" : true, "IN-MN" : true, "IN-MP" : true, - "IN-MZ" : true, "IN-NL" : true, "IN-OR" : true, "IN-PB" : true, "IN-PY" : true, - "IN-RJ" : true, "IN-SK" : true, "IN-TN" : true, "IN-TR" : true, "IN-UP" : true, - "IN-UT" : true, "IN-WB" : true, "IQ-AN" : true, "IQ-AR" : true, "IQ-BA" : true, - "IQ-BB" : true, "IQ-BG" : true, "IQ-DA" : true, "IQ-DI" : true, "IQ-DQ" : true, - "IQ-KA" : true, "IQ-MA" : true, "IQ-MU" : true, "IQ-NA" : true, "IQ-NI" : true, - "IQ-QA" : true, "IQ-SD" : true, "IQ-SW" : true, "IQ-TS" : true, "IQ-WA" : true, - "IR-01" : true, "IR-02" : true, "IR-03" : true, "IR-04" : true, "IR-05" : true, - "IR-06" : true, "IR-07" : true, "IR-08" : true, "IR-10" : true, "IR-11" : true, - "IR-12" : true, "IR-13" : true, "IR-14" : true, "IR-15" : true, "IR-16" : true, - "IR-17" : true, "IR-18" : true, "IR-19" : true, "IR-20" : true, "IR-21" : true, - "IR-22" : true, "IR-23" : true, "IR-24" : true, "IR-25" : true, "IR-26" : true, - "IR-27" : true, "IR-28" : true, "IR-29" : true, "IR-30" : true, "IR-31" : true, - "IS-0" : true, "IS-1" : true, "IS-2" : true, "IS-3" : true, "IS-4" : true, - "IS-5" : true, "IS-6" : true, "IS-7" : true, "IS-8" : true, "IT-21" : true, - "IT-23" : true, "IT-25" : true, "IT-32" : true, "IT-34" : true, "IT-36" : true, - "IT-42" : true, "IT-45" : true, "IT-52" : true, "IT-55" : true, "IT-57" : true, - "IT-62" : true, "IT-65" : true, "IT-67" : true, "IT-72" : true, "IT-75" : true, - "IT-77" : true, "IT-78" : true, "IT-82" : true, "IT-88" : true, "IT-AG" : true, - "IT-AL" : true, "IT-AN" : true, "IT-AO" : true, "IT-AP" : true, "IT-AQ" : true, - "IT-AR" : true, "IT-AT" : true, "IT-AV" : true, "IT-BA" : true, "IT-BG" : true, - "IT-BI" : true, "IT-BL" : true, "IT-BN" : true, "IT-BO" : true, "IT-BR" : true, - "IT-BS" : true, "IT-BT" : true, "IT-BZ" : true, "IT-CA" : true, "IT-CB" : true, - "IT-CE" : true, "IT-CH" : true, "IT-CI" : true, "IT-CL" : true, "IT-CN" : true, - "IT-CO" : true, "IT-CR" : true, "IT-CS" : true, "IT-CT" : true, "IT-CZ" : true, - "IT-EN" : true, "IT-FC" : true, "IT-FE" : true, "IT-FG" : true, "IT-FI" : true, - "IT-FM" : true, "IT-FR" : true, "IT-GE" : true, "IT-GO" : true, "IT-GR" : true, - "IT-IM" : true, "IT-IS" : true, "IT-KR" : true, "IT-LC" : true, "IT-LE" : true, - "IT-LI" : true, "IT-LO" : true, "IT-LT" : true, "IT-LU" : true, "IT-MB" : true, - "IT-MC" : true, "IT-ME" : true, "IT-MI" : true, "IT-MN" : true, "IT-MO" : true, - "IT-MS" : true, "IT-MT" : true, "IT-NA" : true, "IT-NO" : true, "IT-NU" : true, - "IT-OG" : true, "IT-OR" : true, "IT-OT" : true, "IT-PA" : true, "IT-PC" : true, - "IT-PD" : true, "IT-PE" : true, "IT-PG" : true, "IT-PI" : true, "IT-PN" : true, - "IT-PO" : true, "IT-PR" : true, "IT-PT" : true, "IT-PU" : true, "IT-PV" : true, - "IT-PZ" : true, "IT-RA" : true, "IT-RC" : true, "IT-RE" : true, "IT-RG" : true, - "IT-RI" : true, "IT-RM" : true, "IT-RN" : true, "IT-RO" : true, "IT-SA" : true, - "IT-SI" : true, "IT-SO" : true, "IT-SP" : true, "IT-SR" : true, "IT-SS" : true, - "IT-SV" : true, "IT-TA" : true, "IT-TE" : true, "IT-TN" : true, "IT-TO" : true, - "IT-TP" : true, "IT-TR" : true, "IT-TS" : true, "IT-TV" : true, "IT-UD" : true, - "IT-VA" : true, "IT-VB" : true, "IT-VC" : true, "IT-VE" : true, "IT-VI" : true, - "IT-VR" : true, "IT-VS" : true, "IT-VT" : true, "IT-VV" : true, "JM-01" : true, - "JM-02" : true, "JM-03" : true, "JM-04" : true, "JM-05" : true, "JM-06" : true, - "JM-07" : true, "JM-08" : true, "JM-09" : true, "JM-10" : true, "JM-11" : true, - "JM-12" : true, "JM-13" : true, "JM-14" : true, "JO-AJ" : true, "JO-AM" : true, - "JO-AQ" : true, "JO-AT" : true, "JO-AZ" : true, "JO-BA" : true, "JO-IR" : true, - "JO-JA" : true, "JO-KA" : true, "JO-MA" : true, "JO-MD" : true, "JO-MN" : true, - "JP-01" : true, "JP-02" : true, "JP-03" : true, "JP-04" : true, "JP-05" : true, - "JP-06" : true, "JP-07" : true, "JP-08" : true, "JP-09" : true, "JP-10" : true, - "JP-11" : true, "JP-12" : true, "JP-13" : true, "JP-14" : true, "JP-15" : true, - "JP-16" : true, "JP-17" : true, "JP-18" : true, "JP-19" : true, "JP-20" : true, - "JP-21" : true, "JP-22" : true, "JP-23" : true, "JP-24" : true, "JP-25" : true, - "JP-26" : true, "JP-27" : true, "JP-28" : true, "JP-29" : true, "JP-30" : true, - "JP-31" : true, "JP-32" : true, "JP-33" : true, "JP-34" : true, "JP-35" : true, - "JP-36" : true, "JP-37" : true, "JP-38" : true, "JP-39" : true, "JP-40" : true, - "JP-41" : true, "JP-42" : true, "JP-43" : true, "JP-44" : true, "JP-45" : true, - "JP-46" : true, "JP-47" : true, "KE-110" : true, "KE-200" : true, "KE-300" : true, - "KE-400" : true, "KE-500" : true, "KE-700" : true, "KE-800" : true, "KG-B" : true, - "KG-C" : true, "KG-GB" : true, "KG-J" : true, "KG-N" : true, "KG-O" : true, - "KG-T" : true, "KG-Y" : true, "KH-1" : true, "KH-10" : true, "KH-11" : true, - "KH-12" : true, "KH-13" : true, "KH-14" : true, "KH-15" : true, "KH-16" : true, - "KH-17" : true, "KH-18" : true, "KH-19" : true, "KH-2" : true, "KH-20" : true, - "KH-21" : true, "KH-22" : true, "KH-23" : true, "KH-24" : true, "KH-3" : true, - "KH-4" : true, "KH-5" : true, "KH-6" : true, "KH-7" : true, "KH-8" : true, - "KH-9" : true, "KI-G" : true, "KI-L" : true, "KI-P" : true, "KM-A" : true, - "KM-G" : true, "KM-M" : true, "KN-01" : true, "KN-02" : true, "KN-03" : true, - "KN-04" : true, "KN-05" : true, "KN-06" : true, "KN-07" : true, "KN-08" : true, - "KN-09" : true, "KN-10" : true, "KN-11" : true, "KN-12" : true, "KN-13" : true, - "KN-15" : true, "KN-K" : true, "KN-N" : true, "KP-01" : true, "KP-02" : true, - "KP-03" : true, "KP-04" : true, "KP-05" : true, "KP-06" : true, "KP-07" : true, - "KP-08" : true, "KP-09" : true, "KP-10" : true, "KP-13" : true, "KR-11" : true, - "KR-26" : true, "KR-27" : true, "KR-28" : true, "KR-29" : true, "KR-30" : true, - "KR-31" : true, "KR-41" : true, "KR-42" : true, "KR-43" : true, "KR-44" : true, - "KR-45" : true, "KR-46" : true, "KR-47" : true, "KR-48" : true, "KR-49" : true, - "KW-AH" : true, "KW-FA" : true, "KW-HA" : true, "KW-JA" : true, "KW-KU" : true, - "KW-MU" : true, "KZ-AKM" : true, "KZ-AKT" : true, "KZ-ALA" : true, "KZ-ALM" : true, - "KZ-AST" : true, "KZ-ATY" : true, "KZ-KAR" : true, "KZ-KUS" : true, "KZ-KZY" : true, - "KZ-MAN" : true, "KZ-PAV" : true, "KZ-SEV" : true, "KZ-VOS" : true, "KZ-YUZ" : true, - "KZ-ZAP" : true, "KZ-ZHA" : true, "LA-AT" : true, "LA-BK" : true, "LA-BL" : true, - "LA-CH" : true, "LA-HO" : true, "LA-KH" : true, "LA-LM" : true, "LA-LP" : true, - "LA-OU" : true, "LA-PH" : true, "LA-SL" : true, "LA-SV" : true, "LA-VI" : true, - "LA-VT" : true, "LA-XA" : true, "LA-XE" : true, "LA-XI" : true, "LA-XS" : true, - "LB-AK" : true, "LB-AS" : true, "LB-BA" : true, "LB-BH" : true, "LB-BI" : true, - "LB-JA" : true, "LB-JL" : true, "LB-NA" : true, "LI-01" : true, "LI-02" : true, - "LI-03" : true, "LI-04" : true, "LI-05" : true, "LI-06" : true, "LI-07" : true, - "LI-08" : true, "LI-09" : true, "LI-10" : true, "LI-11" : true, "LK-1" : true, - "LK-11" : true, "LK-12" : true, "LK-13" : true, "LK-2" : true, "LK-21" : true, - "LK-22" : true, "LK-23" : true, "LK-3" : true, "LK-31" : true, "LK-32" : true, - "LK-33" : true, "LK-4" : true, "LK-41" : true, "LK-42" : true, "LK-43" : true, - "LK-44" : true, "LK-45" : true, "LK-5" : true, "LK-51" : true, "LK-52" : true, - "LK-53" : true, "LK-6" : true, "LK-61" : true, "LK-62" : true, "LK-7" : true, - "LK-71" : true, "LK-72" : true, "LK-8" : true, "LK-81" : true, "LK-82" : true, - "LK-9" : true, "LK-91" : true, "LK-92" : true, "LR-BG" : true, "LR-BM" : true, - "LR-CM" : true, "LR-GB" : true, "LR-GG" : true, "LR-GK" : true, "LR-LO" : true, - "LR-MG" : true, "LR-MO" : true, "LR-MY" : true, "LR-NI" : true, "LR-RI" : true, - "LR-SI" : true, "LS-A" : true, "LS-B" : true, "LS-C" : true, "LS-D" : true, - "LS-E" : true, "LS-F" : true, "LS-G" : true, "LS-H" : true, "LS-J" : true, - "LS-K" : true, "LT-AL" : true, "LT-KL" : true, "LT-KU" : true, "LT-MR" : true, - "LT-PN" : true, "LT-SA" : true, "LT-TA" : true, "LT-TE" : true, "LT-UT" : true, - "LT-VL" : true, "LU-D" : true, "LU-G" : true, "LU-L" : true, "LV-001" : true, - "LV-002" : true, "LV-003" : true, "LV-004" : true, "LV-005" : true, "LV-006" : true, - "LV-007" : true, "LV-008" : true, "LV-009" : true, "LV-010" : true, "LV-011" : true, - "LV-012" : true, "LV-013" : true, "LV-014" : true, "LV-015" : true, "LV-016" : true, - "LV-017" : true, "LV-018" : true, "LV-019" : true, "LV-020" : true, "LV-021" : true, - "LV-022" : true, "LV-023" : true, "LV-024" : true, "LV-025" : true, "LV-026" : true, - "LV-027" : true, "LV-028" : true, "LV-029" : true, "LV-030" : true, "LV-031" : true, - "LV-032" : true, "LV-033" : true, "LV-034" : true, "LV-035" : true, "LV-036" : true, - "LV-037" : true, "LV-038" : true, "LV-039" : true, "LV-040" : true, "LV-041" : true, - "LV-042" : true, "LV-043" : true, "LV-044" : true, "LV-045" : true, "LV-046" : true, - "LV-047" : true, "LV-048" : true, "LV-049" : true, "LV-050" : true, "LV-051" : true, - "LV-052" : true, "LV-053" : true, "LV-054" : true, "LV-055" : true, "LV-056" : true, - "LV-057" : true, "LV-058" : true, "LV-059" : true, "LV-060" : true, "LV-061" : true, - "LV-062" : true, "LV-063" : true, "LV-064" : true, "LV-065" : true, "LV-066" : true, - "LV-067" : true, "LV-068" : true, "LV-069" : true, "LV-070" : true, "LV-071" : true, - "LV-072" : true, "LV-073" : true, "LV-074" : true, "LV-075" : true, "LV-076" : true, - "LV-077" : true, "LV-078" : true, "LV-079" : true, "LV-080" : true, "LV-081" : true, - "LV-082" : true, "LV-083" : true, "LV-084" : true, "LV-085" : true, "LV-086" : true, - "LV-087" : true, "LV-088" : true, "LV-089" : true, "LV-090" : true, "LV-091" : true, - "LV-092" : true, "LV-093" : true, "LV-094" : true, "LV-095" : true, "LV-096" : true, - "LV-097" : true, "LV-098" : true, "LV-099" : true, "LV-100" : true, "LV-101" : true, - "LV-102" : true, "LV-103" : true, "LV-104" : true, "LV-105" : true, "LV-106" : true, - "LV-107" : true, "LV-108" : true, "LV-109" : true, "LV-110" : true, "LV-DGV" : true, - "LV-JEL" : true, "LV-JKB" : true, "LV-JUR" : true, "LV-LPX" : true, "LV-REZ" : true, - "LV-RIX" : true, "LV-VEN" : true, "LV-VMR" : true, "LY-BA" : true, "LY-BU" : true, - "LY-DR" : true, "LY-GT" : true, "LY-JA" : true, "LY-JB" : true, "LY-JG" : true, - "LY-JI" : true, "LY-JU" : true, "LY-KF" : true, "LY-MB" : true, "LY-MI" : true, - "LY-MJ" : true, "LY-MQ" : true, "LY-NL" : true, "LY-NQ" : true, "LY-SB" : true, - "LY-SR" : true, "LY-TB" : true, "LY-WA" : true, "LY-WD" : true, "LY-WS" : true, - "LY-ZA" : true, "MA-01" : true, "MA-02" : true, "MA-03" : true, "MA-04" : true, - "MA-05" : true, "MA-06" : true, "MA-07" : true, "MA-08" : true, "MA-09" : true, - "MA-10" : true, "MA-11" : true, "MA-12" : true, "MA-13" : true, "MA-14" : true, - "MA-15" : true, "MA-16" : true, "MA-AGD" : true, "MA-AOU" : true, "MA-ASZ" : true, - "MA-AZI" : true, "MA-BEM" : true, "MA-BER" : true, "MA-BES" : true, "MA-BOD" : true, - "MA-BOM" : true, "MA-CAS" : true, "MA-CHE" : true, "MA-CHI" : true, "MA-CHT" : true, - "MA-ERR" : true, "MA-ESI" : true, "MA-ESM" : true, "MA-FAH" : true, "MA-FES" : true, - "MA-FIG" : true, "MA-GUE" : true, "MA-HAJ" : true, "MA-HAO" : true, "MA-HOC" : true, - "MA-IFR" : true, "MA-INE" : true, "MA-JDI" : true, "MA-JRA" : true, "MA-KEN" : true, - "MA-KES" : true, "MA-KHE" : true, "MA-KHN" : true, "MA-KHO" : true, "MA-LAA" : true, - "MA-LAR" : true, "MA-MED" : true, "MA-MEK" : true, "MA-MMD" : true, "MA-MMN" : true, - "MA-MOH" : true, "MA-MOU" : true, "MA-NAD" : true, "MA-NOU" : true, "MA-OUA" : true, - "MA-OUD" : true, "MA-OUJ" : true, "MA-RAB" : true, "MA-SAF" : true, "MA-SAL" : true, - "MA-SEF" : true, "MA-SET" : true, "MA-SIK" : true, "MA-SKH" : true, "MA-SYB" : true, - "MA-TAI" : true, "MA-TAO" : true, "MA-TAR" : true, "MA-TAT" : true, "MA-TAZ" : true, - "MA-TET" : true, "MA-TIZ" : true, "MA-TNG" : true, "MA-TNT" : true, "MA-ZAG" : true, - "MC-CL" : true, "MC-CO" : true, "MC-FO" : true, "MC-GA" : true, "MC-JE" : true, - "MC-LA" : true, "MC-MA" : true, "MC-MC" : true, "MC-MG" : true, "MC-MO" : true, - "MC-MU" : true, "MC-PH" : true, "MC-SD" : true, "MC-SO" : true, "MC-SP" : true, - "MC-SR" : true, "MC-VR" : true, "MD-AN" : true, "MD-BA" : true, "MD-BD" : true, - "MD-BR" : true, "MD-BS" : true, "MD-CA" : true, "MD-CL" : true, "MD-CM" : true, - "MD-CR" : true, "MD-CS" : true, "MD-CT" : true, "MD-CU" : true, "MD-DO" : true, - "MD-DR" : true, "MD-DU" : true, "MD-ED" : true, "MD-FA" : true, "MD-FL" : true, - "MD-GA" : true, "MD-GL" : true, "MD-HI" : true, "MD-IA" : true, "MD-LE" : true, - "MD-NI" : true, "MD-OC" : true, "MD-OR" : true, "MD-RE" : true, "MD-RI" : true, - "MD-SD" : true, "MD-SI" : true, "MD-SN" : true, "MD-SO" : true, "MD-ST" : true, - "MD-SV" : true, "MD-TA" : true, "MD-TE" : true, "MD-UN" : true, "ME-01" : true, - "ME-02" : true, "ME-03" : true, "ME-04" : true, "ME-05" : true, "ME-06" : true, - "ME-07" : true, "ME-08" : true, "ME-09" : true, "ME-10" : true, "ME-11" : true, - "ME-12" : true, "ME-13" : true, "ME-14" : true, "ME-15" : true, "ME-16" : true, - "ME-17" : true, "ME-18" : true, "ME-19" : true, "ME-20" : true, "ME-21" : true, - "MG-A" : true, "MG-D" : true, "MG-F" : true, "MG-M" : true, "MG-T" : true, - "MG-U" : true, "MH-ALK" : true, "MH-ALL" : true, "MH-ARN" : true, "MH-AUR" : true, - "MH-EBO" : true, "MH-ENI" : true, "MH-JAB" : true, "MH-JAL" : true, "MH-KIL" : true, - "MH-KWA" : true, "MH-L" : true, "MH-LAE" : true, "MH-LIB" : true, "MH-LIK" : true, - "MH-MAJ" : true, "MH-MAL" : true, "MH-MEJ" : true, "MH-MIL" : true, "MH-NMK" : true, - "MH-NMU" : true, "MH-RON" : true, "MH-T" : true, "MH-UJA" : true, "MH-UTI" : true, - "MH-WTJ" : true, "MH-WTN" : true, "MK-01" : true, "MK-02" : true, "MK-03" : true, - "MK-04" : true, "MK-05" : true, "MK-06" : true, "MK-07" : true, "MK-08" : true, - "MK-09" : true, "MK-10" : true, "MK-11" : true, "MK-12" : true, "MK-13" : true, - "MK-14" : true, "MK-15" : true, "MK-16" : true, "MK-17" : true, "MK-18" : true, - "MK-19" : true, "MK-20" : true, "MK-21" : true, "MK-22" : true, "MK-23" : true, - "MK-24" : true, "MK-25" : true, "MK-26" : true, "MK-27" : true, "MK-28" : true, - "MK-29" : true, "MK-30" : true, "MK-31" : true, "MK-32" : true, "MK-33" : true, - "MK-34" : true, "MK-35" : true, "MK-36" : true, "MK-37" : true, "MK-38" : true, - "MK-39" : true, "MK-40" : true, "MK-41" : true, "MK-42" : true, "MK-43" : true, - "MK-44" : true, "MK-45" : true, "MK-46" : true, "MK-47" : true, "MK-48" : true, - "MK-49" : true, "MK-50" : true, "MK-51" : true, "MK-52" : true, "MK-53" : true, - "MK-54" : true, "MK-55" : true, "MK-56" : true, "MK-57" : true, "MK-58" : true, - "MK-59" : true, "MK-60" : true, "MK-61" : true, "MK-62" : true, "MK-63" : true, - "MK-64" : true, "MK-65" : true, "MK-66" : true, "MK-67" : true, "MK-68" : true, - "MK-69" : true, "MK-70" : true, "MK-71" : true, "MK-72" : true, "MK-73" : true, - "MK-74" : true, "MK-75" : true, "MK-76" : true, "MK-77" : true, "MK-78" : true, - "MK-79" : true, "MK-80" : true, "MK-81" : true, "MK-82" : true, "MK-83" : true, - "MK-84" : true, "ML-1" : true, "ML-2" : true, "ML-3" : true, "ML-4" : true, - "ML-5" : true, "ML-6" : true, "ML-7" : true, "ML-8" : true, "ML-BK0" : true, - "MM-01" : true, "MM-02" : true, "MM-03" : true, "MM-04" : true, "MM-05" : true, - "MM-06" : true, "MM-07" : true, "MM-11" : true, "MM-12" : true, "MM-13" : true, - "MM-14" : true, "MM-15" : true, "MM-16" : true, "MM-17" : true, "MN-035" : true, - "MN-037" : true, "MN-039" : true, "MN-041" : true, "MN-043" : true, "MN-046" : true, - "MN-047" : true, "MN-049" : true, "MN-051" : true, "MN-053" : true, "MN-055" : true, - "MN-057" : true, "MN-059" : true, "MN-061" : true, "MN-063" : true, "MN-064" : true, - "MN-065" : true, "MN-067" : true, "MN-069" : true, "MN-071" : true, "MN-073" : true, - "MN-1" : true, "MR-01" : true, "MR-02" : true, "MR-03" : true, "MR-04" : true, - "MR-05" : true, "MR-06" : true, "MR-07" : true, "MR-08" : true, "MR-09" : true, - "MR-10" : true, "MR-11" : true, "MR-12" : true, "MR-NKC" : true, "MT-01" : true, - "MT-02" : true, "MT-03" : true, "MT-04" : true, "MT-05" : true, "MT-06" : true, - "MT-07" : true, "MT-08" : true, "MT-09" : true, "MT-10" : true, "MT-11" : true, - "MT-12" : true, "MT-13" : true, "MT-14" : true, "MT-15" : true, "MT-16" : true, - "MT-17" : true, "MT-18" : true, "MT-19" : true, "MT-20" : true, "MT-21" : true, - "MT-22" : true, "MT-23" : true, "MT-24" : true, "MT-25" : true, "MT-26" : true, - "MT-27" : true, "MT-28" : true, "MT-29" : true, "MT-30" : true, "MT-31" : true, - "MT-32" : true, "MT-33" : true, "MT-34" : true, "MT-35" : true, "MT-36" : true, - "MT-37" : true, "MT-38" : true, "MT-39" : true, "MT-40" : true, "MT-41" : true, - "MT-42" : true, "MT-43" : true, "MT-44" : true, "MT-45" : true, "MT-46" : true, - "MT-47" : true, "MT-48" : true, "MT-49" : true, "MT-50" : true, "MT-51" : true, - "MT-52" : true, "MT-53" : true, "MT-54" : true, "MT-55" : true, "MT-56" : true, - "MT-57" : true, "MT-58" : true, "MT-59" : true, "MT-60" : true, "MT-61" : true, - "MT-62" : true, "MT-63" : true, "MT-64" : true, "MT-65" : true, "MT-66" : true, - "MT-67" : true, "MT-68" : true, "MU-AG" : true, "MU-BL" : true, "MU-BR" : true, - "MU-CC" : true, "MU-CU" : true, "MU-FL" : true, "MU-GP" : true, "MU-MO" : true, - "MU-PA" : true, "MU-PL" : true, "MU-PU" : true, "MU-PW" : true, "MU-QB" : true, - "MU-RO" : true, "MU-RP" : true, "MU-SA" : true, "MU-VP" : true, "MV-00" : true, - "MV-01" : true, "MV-02" : true, "MV-03" : true, "MV-04" : true, "MV-05" : true, - "MV-07" : true, "MV-08" : true, "MV-12" : true, "MV-13" : true, "MV-14" : true, - "MV-17" : true, "MV-20" : true, "MV-23" : true, "MV-24" : true, "MV-25" : true, - "MV-26" : true, "MV-27" : true, "MV-28" : true, "MV-29" : true, "MV-CE" : true, - "MV-MLE" : true, "MV-NC" : true, "MV-NO" : true, "MV-SC" : true, "MV-SU" : true, - "MV-UN" : true, "MV-US" : true, "MW-BA" : true, "MW-BL" : true, "MW-C" : true, - "MW-CK" : true, "MW-CR" : true, "MW-CT" : true, "MW-DE" : true, "MW-DO" : true, - "MW-KR" : true, "MW-KS" : true, "MW-LI" : true, "MW-LK" : true, "MW-MC" : true, - "MW-MG" : true, "MW-MH" : true, "MW-MU" : true, "MW-MW" : true, "MW-MZ" : true, - "MW-N" : true, "MW-NB" : true, "MW-NE" : true, "MW-NI" : true, "MW-NK" : true, - "MW-NS" : true, "MW-NU" : true, "MW-PH" : true, "MW-RU" : true, "MW-S" : true, - "MW-SA" : true, "MW-TH" : true, "MW-ZO" : true, "MX-AGU" : true, "MX-BCN" : true, - "MX-BCS" : true, "MX-CAM" : true, "MX-CHH" : true, "MX-CHP" : true, "MX-COA" : true, - "MX-COL" : true, "MX-DIF" : true, "MX-DUR" : true, "MX-GRO" : true, "MX-GUA" : true, - "MX-HID" : true, "MX-JAL" : true, "MX-MEX" : true, "MX-MIC" : true, "MX-MOR" : true, - "MX-NAY" : true, "MX-NLE" : true, "MX-OAX" : true, "MX-PUE" : true, "MX-QUE" : true, - "MX-ROO" : true, "MX-SIN" : true, "MX-SLP" : true, "MX-SON" : true, "MX-TAB" : true, - "MX-TAM" : true, "MX-TLA" : true, "MX-VER" : true, "MX-YUC" : true, "MX-ZAC" : true, - "MY-01" : true, "MY-02" : true, "MY-03" : true, "MY-04" : true, "MY-05" : true, - "MY-06" : true, "MY-07" : true, "MY-08" : true, "MY-09" : true, "MY-10" : true, - "MY-11" : true, "MY-12" : true, "MY-13" : true, "MY-14" : true, "MY-15" : true, - "MY-16" : true, "MZ-A" : true, "MZ-B" : true, "MZ-G" : true, "MZ-I" : true, - "MZ-L" : true, "MZ-MPM" : true, "MZ-N" : true, "MZ-P" : true, "MZ-Q" : true, - "MZ-S" : true, "MZ-T" : true, "NA-CA" : true, "NA-ER" : true, "NA-HA" : true, - "NA-KA" : true, "NA-KH" : true, "NA-KU" : true, "NA-OD" : true, "NA-OH" : true, - "NA-OK" : true, "NA-ON" : true, "NA-OS" : true, "NA-OT" : true, "NA-OW" : true, - "NE-1" : true, "NE-2" : true, "NE-3" : true, "NE-4" : true, "NE-5" : true, - "NE-6" : true, "NE-7" : true, "NE-8" : true, "NG-AB" : true, "NG-AD" : true, - "NG-AK" : true, "NG-AN" : true, "NG-BA" : true, "NG-BE" : true, "NG-BO" : true, - "NG-BY" : true, "NG-CR" : true, "NG-DE" : true, "NG-EB" : true, "NG-ED" : true, - "NG-EK" : true, "NG-EN" : true, "NG-FC" : true, "NG-GO" : true, "NG-IM" : true, - "NG-JI" : true, "NG-KD" : true, "NG-KE" : true, "NG-KN" : true, "NG-KO" : true, - "NG-KT" : true, "NG-KW" : true, "NG-LA" : true, "NG-NA" : true, "NG-NI" : true, - "NG-OG" : true, "NG-ON" : true, "NG-OS" : true, "NG-OY" : true, "NG-PL" : true, - "NG-RI" : true, "NG-SO" : true, "NG-TA" : true, "NG-YO" : true, "NG-ZA" : true, - "NI-AN" : true, "NI-AS" : true, "NI-BO" : true, "NI-CA" : true, "NI-CI" : true, - "NI-CO" : true, "NI-ES" : true, "NI-GR" : true, "NI-JI" : true, "NI-LE" : true, - "NI-MD" : true, "NI-MN" : true, "NI-MS" : true, "NI-MT" : true, "NI-NS" : true, - "NI-RI" : true, "NI-SJ" : true, "NL-AW" : true, "NL-BQ1" : true, "NL-BQ2" : true, - "NL-BQ3" : true, "NL-CW" : true, "NL-DR" : true, "NL-FL" : true, "NL-FR" : true, - "NL-GE" : true, "NL-GR" : true, "NL-LI" : true, "NL-NB" : true, "NL-NH" : true, - "NL-OV" : true, "NL-SX" : true, "NL-UT" : true, "NL-ZE" : true, "NL-ZH" : true, - "NO-01" : true, "NO-02" : true, "NO-03" : true, "NO-04" : true, "NO-05" : true, - "NO-06" : true, "NO-07" : true, "NO-08" : true, "NO-09" : true, "NO-10" : true, - "NO-11" : true, "NO-12" : true, "NO-14" : true, "NO-15" : true, "NO-16" : true, - "NO-17" : true, "NO-18" : true, "NO-19" : true, "NO-20" : true, "NO-21" : true, - "NO-22" : true, "NP-1" : true, "NP-2" : true, "NP-3" : true, "NP-4" : true, - "NP-5" : true, "NP-BA" : true, "NP-BH" : true, "NP-DH" : true, "NP-GA" : true, - "NP-JA" : true, "NP-KA" : true, "NP-KO" : true, "NP-LU" : true, "NP-MA" : true, - "NP-ME" : true, "NP-NA" : true, "NP-RA" : true, "NP-SA" : true, "NP-SE" : true, - "NR-01" : true, "NR-02" : true, "NR-03" : true, "NR-04" : true, "NR-05" : true, - "NR-06" : true, "NR-07" : true, "NR-08" : true, "NR-09" : true, "NR-10" : true, - "NR-11" : true, "NR-12" : true, "NR-13" : true, "NR-14" : true, "NZ-AUK" : true, - "NZ-BOP" : true, "NZ-CAN" : true, "NZ-CIT" : true, "NZ-GIS" : true, "NZ-HKB" : true, - "NZ-MBH" : true, "NZ-MWT" : true, "NZ-N" : true, "NZ-NSN" : true, "NZ-NTL" : true, - "NZ-OTA" : true, "NZ-S" : true, "NZ-STL" : true, "NZ-TAS" : true, "NZ-TKI" : true, - "NZ-WGN" : true, "NZ-WKO" : true, "NZ-WTC" : true, "OM-BA" : true, "OM-BU" : true, - "OM-DA" : true, "OM-MA" : true, "OM-MU" : true, "OM-SH" : true, "OM-WU" : true, - "OM-ZA" : true, "OM-ZU" : true, "PA-1" : true, "PA-2" : true, "PA-3" : true, - "PA-4" : true, "PA-5" : true, "PA-6" : true, "PA-7" : true, "PA-8" : true, - "PA-9" : true, "PA-EM" : true, "PA-KY" : true, "PA-NB" : true, "PE-AMA" : true, - "PE-ANC" : true, "PE-APU" : true, "PE-ARE" : true, "PE-AYA" : true, "PE-CAJ" : true, - "PE-CAL" : true, "PE-CUS" : true, "PE-HUC" : true, "PE-HUV" : true, "PE-ICA" : true, - "PE-JUN" : true, "PE-LAL" : true, "PE-LAM" : true, "PE-LIM" : true, "PE-LMA" : true, - "PE-LOR" : true, "PE-MDD" : true, "PE-MOQ" : true, "PE-PAS" : true, "PE-PIU" : true, - "PE-PUN" : true, "PE-SAM" : true, "PE-TAC" : true, "PE-TUM" : true, "PE-UCA" : true, - "PG-CPK" : true, "PG-CPM" : true, "PG-EBR" : true, "PG-EHG" : true, "PG-EPW" : true, - "PG-ESW" : true, "PG-GPK" : true, "PG-MBA" : true, "PG-MPL" : true, "PG-MPM" : true, - "PG-MRL" : true, "PG-NCD" : true, "PG-NIK" : true, "PG-NPP" : true, "PG-NSB" : true, - "PG-SAN" : true, "PG-SHM" : true, "PG-WBK" : true, "PG-WHM" : true, "PG-WPD" : true, - "PH-00" : true, "PH-01" : true, "PH-02" : true, "PH-03" : true, "PH-05" : true, - "PH-06" : true, "PH-07" : true, "PH-08" : true, "PH-09" : true, "PH-10" : true, - "PH-11" : true, "PH-12" : true, "PH-13" : true, "PH-14" : true, "PH-15" : true, - "PH-40" : true, "PH-41" : true, "PH-ABR" : true, "PH-AGN" : true, "PH-AGS" : true, - "PH-AKL" : true, "PH-ALB" : true, "PH-ANT" : true, "PH-APA" : true, "PH-AUR" : true, - "PH-BAN" : true, "PH-BAS" : true, "PH-BEN" : true, "PH-BIL" : true, "PH-BOH" : true, - "PH-BTG" : true, "PH-BTN" : true, "PH-BUK" : true, "PH-BUL" : true, "PH-CAG" : true, - "PH-CAM" : true, "PH-CAN" : true, "PH-CAP" : true, "PH-CAS" : true, "PH-CAT" : true, - "PH-CAV" : true, "PH-CEB" : true, "PH-COM" : true, "PH-DAO" : true, "PH-DAS" : true, - "PH-DAV" : true, "PH-DIN" : true, "PH-EAS" : true, "PH-GUI" : true, "PH-IFU" : true, - "PH-ILI" : true, "PH-ILN" : true, "PH-ILS" : true, "PH-ISA" : true, "PH-KAL" : true, - "PH-LAG" : true, "PH-LAN" : true, "PH-LAS" : true, "PH-LEY" : true, "PH-LUN" : true, - "PH-MAD" : true, "PH-MAG" : true, "PH-MAS" : true, "PH-MDC" : true, "PH-MDR" : true, - "PH-MOU" : true, "PH-MSC" : true, "PH-MSR" : true, "PH-NCO" : true, "PH-NEC" : true, - "PH-NER" : true, "PH-NSA" : true, "PH-NUE" : true, "PH-NUV" : true, "PH-PAM" : true, - "PH-PAN" : true, "PH-PLW" : true, "PH-QUE" : true, "PH-QUI" : true, "PH-RIZ" : true, - "PH-ROM" : true, "PH-SAR" : true, "PH-SCO" : true, "PH-SIG" : true, "PH-SLE" : true, - "PH-SLU" : true, "PH-SOR" : true, "PH-SUK" : true, "PH-SUN" : true, "PH-SUR" : true, - "PH-TAR" : true, "PH-TAW" : true, "PH-WSA" : true, "PH-ZAN" : true, "PH-ZAS" : true, - "PH-ZMB" : true, "PH-ZSI" : true, "PK-BA" : true, "PK-GB" : true, "PK-IS" : true, - "PK-JK" : true, "PK-KP" : true, "PK-PB" : true, "PK-SD" : true, "PK-TA" : true, - "PL-DS" : true, "PL-KP" : true, "PL-LB" : true, "PL-LD" : true, "PL-LU" : true, - "PL-MA" : true, "PL-MZ" : true, "PL-OP" : true, "PL-PD" : true, "PL-PK" : true, - "PL-PM" : true, "PL-SK" : true, "PL-SL" : true, "PL-WN" : true, "PL-WP" : true, - "PL-ZP" : true, "PS-BTH" : true, "PS-DEB" : true, "PS-GZA" : true, "PS-HBN" : true, - "PS-JEM" : true, "PS-JEN" : true, "PS-JRH" : true, "PS-KYS" : true, "PS-NBS" : true, - "PS-NGZ" : true, "PS-QQA" : true, "PS-RBH" : true, "PS-RFH" : true, "PS-SLT" : true, - "PS-TBS" : true, "PS-TKM" : true, "PT-01" : true, "PT-02" : true, "PT-03" : true, - "PT-04" : true, "PT-05" : true, "PT-06" : true, "PT-07" : true, "PT-08" : true, - "PT-09" : true, "PT-10" : true, "PT-11" : true, "PT-12" : true, "PT-13" : true, - "PT-14" : true, "PT-15" : true, "PT-16" : true, "PT-17" : true, "PT-18" : true, - "PT-20" : true, "PT-30" : true, "PW-002" : true, "PW-004" : true, "PW-010" : true, - "PW-050" : true, "PW-100" : true, "PW-150" : true, "PW-212" : true, "PW-214" : true, - "PW-218" : true, "PW-222" : true, "PW-224" : true, "PW-226" : true, "PW-227" : true, - "PW-228" : true, "PW-350" : true, "PW-370" : true, "PY-1" : true, "PY-10" : true, - "PY-11" : true, "PY-12" : true, "PY-13" : true, "PY-14" : true, "PY-15" : true, - "PY-16" : true, "PY-19" : true, "PY-2" : true, "PY-3" : true, "PY-4" : true, - "PY-5" : true, "PY-6" : true, "PY-7" : true, "PY-8" : true, "PY-9" : true, - "PY-ASU" : true, "QA-DA" : true, "QA-KH" : true, "QA-MS" : true, "QA-RA" : true, - "QA-US" : true, "QA-WA" : true, "QA-ZA" : true, "RO-AB" : true, "RO-AG" : true, - "RO-AR" : true, "RO-B" : true, "RO-BC" : true, "RO-BH" : true, "RO-BN" : true, - "RO-BR" : true, "RO-BT" : true, "RO-BV" : true, "RO-BZ" : true, "RO-CJ" : true, - "RO-CL" : true, "RO-CS" : true, "RO-CT" : true, "RO-CV" : true, "RO-DB" : true, - "RO-DJ" : true, "RO-GJ" : true, "RO-GL" : true, "RO-GR" : true, "RO-HD" : true, - "RO-HR" : true, "RO-IF" : true, "RO-IL" : true, "RO-IS" : true, "RO-MH" : true, - "RO-MM" : true, "RO-MS" : true, "RO-NT" : true, "RO-OT" : true, "RO-PH" : true, - "RO-SB" : true, "RO-SJ" : true, "RO-SM" : true, "RO-SV" : true, "RO-TL" : true, - "RO-TM" : true, "RO-TR" : true, "RO-VL" : true, "RO-VN" : true, "RO-VS" : true, - "RS-00" : true, "RS-01" : true, "RS-02" : true, "RS-03" : true, "RS-04" : true, - "RS-05" : true, "RS-06" : true, "RS-07" : true, "RS-08" : true, "RS-09" : true, - "RS-10" : true, "RS-11" : true, "RS-12" : true, "RS-13" : true, "RS-14" : true, - "RS-15" : true, "RS-16" : true, "RS-17" : true, "RS-18" : true, "RS-19" : true, - "RS-20" : true, "RS-21" : true, "RS-22" : true, "RS-23" : true, "RS-24" : true, - "RS-25" : true, "RS-26" : true, "RS-27" : true, "RS-28" : true, "RS-29" : true, - "RS-KM" : true, "RS-VO" : true, "RU-AD" : true, "RU-AL" : true, "RU-ALT" : true, - "RU-AMU" : true, "RU-ARK" : true, "RU-AST" : true, "RU-BA" : true, "RU-BEL" : true, - "RU-BRY" : true, "RU-BU" : true, "RU-CE" : true, "RU-CHE" : true, "RU-CHU" : true, - "RU-CU" : true, "RU-DA" : true, "RU-IN" : true, "RU-IRK" : true, "RU-IVA" : true, - "RU-KAM" : true, "RU-KB" : true, "RU-KC" : true, "RU-KDA" : true, "RU-KEM" : true, - "RU-KGD" : true, "RU-KGN" : true, "RU-KHA" : true, "RU-KHM" : true, "RU-KIR" : true, - "RU-KK" : true, "RU-KL" : true, "RU-KLU" : true, "RU-KO" : true, "RU-KOS" : true, - "RU-KR" : true, "RU-KRS" : true, "RU-KYA" : true, "RU-LEN" : true, "RU-LIP" : true, - "RU-MAG" : true, "RU-ME" : true, "RU-MO" : true, "RU-MOS" : true, "RU-MOW" : true, - "RU-MUR" : true, "RU-NEN" : true, "RU-NGR" : true, "RU-NIZ" : true, "RU-NVS" : true, - "RU-OMS" : true, "RU-ORE" : true, "RU-ORL" : true, "RU-PER" : true, "RU-PNZ" : true, - "RU-PRI" : true, "RU-PSK" : true, "RU-ROS" : true, "RU-RYA" : true, "RU-SA" : true, - "RU-SAK" : true, "RU-SAM" : true, "RU-SAR" : true, "RU-SE" : true, "RU-SMO" : true, - "RU-SPE" : true, "RU-STA" : true, "RU-SVE" : true, "RU-TA" : true, "RU-TAM" : true, - "RU-TOM" : true, "RU-TUL" : true, "RU-TVE" : true, "RU-TY" : true, "RU-TYU" : true, - "RU-UD" : true, "RU-ULY" : true, "RU-VGG" : true, "RU-VLA" : true, "RU-VLG" : true, - "RU-VOR" : true, "RU-YAN" : true, "RU-YAR" : true, "RU-YEV" : true, "RU-ZAB" : true, - "RW-01" : true, "RW-02" : true, "RW-03" : true, "RW-04" : true, "RW-05" : true, - "SA-01" : true, "SA-02" : true, "SA-03" : true, "SA-04" : true, "SA-05" : true, - "SA-06" : true, "SA-07" : true, "SA-08" : true, "SA-09" : true, "SA-10" : true, - "SA-11" : true, "SA-12" : true, "SA-14" : true, "SB-CE" : true, "SB-CH" : true, - "SB-CT" : true, "SB-GU" : true, "SB-IS" : true, "SB-MK" : true, "SB-ML" : true, - "SB-RB" : true, "SB-TE" : true, "SB-WE" : true, "SC-01" : true, "SC-02" : true, - "SC-03" : true, "SC-04" : true, "SC-05" : true, "SC-06" : true, "SC-07" : true, - "SC-08" : true, "SC-09" : true, "SC-10" : true, "SC-11" : true, "SC-12" : true, - "SC-13" : true, "SC-14" : true, "SC-15" : true, "SC-16" : true, "SC-17" : true, - "SC-18" : true, "SC-19" : true, "SC-20" : true, "SC-21" : true, "SC-22" : true, - "SC-23" : true, "SC-24" : true, "SC-25" : true, "SD-DC" : true, "SD-DE" : true, - "SD-DN" : true, "SD-DS" : true, "SD-DW" : true, "SD-GD" : true, "SD-GZ" : true, - "SD-KA" : true, "SD-KH" : true, "SD-KN" : true, "SD-KS" : true, "SD-NB" : true, - "SD-NO" : true, "SD-NR" : true, "SD-NW" : true, "SD-RS" : true, "SD-SI" : true, - "SE-AB" : true, "SE-AC" : true, "SE-BD" : true, "SE-C" : true, "SE-D" : true, - "SE-E" : true, "SE-F" : true, "SE-G" : true, "SE-H" : true, "SE-I" : true, - "SE-K" : true, "SE-M" : true, "SE-N" : true, "SE-O" : true, "SE-S" : true, - "SE-T" : true, "SE-U" : true, "SE-W" : true, "SE-X" : true, "SE-Y" : true, - "SE-Z" : true, "SG-01" : true, "SG-02" : true, "SG-03" : true, "SG-04" : true, - "SG-05" : true, "SH-AC" : true, "SH-HL" : true, "SH-TA" : true, "SI-001" : true, - "SI-002" : true, "SI-003" : true, "SI-004" : true, "SI-005" : true, "SI-006" : true, - "SI-007" : true, "SI-008" : true, "SI-009" : true, "SI-010" : true, "SI-011" : true, - "SI-012" : true, "SI-013" : true, "SI-014" : true, "SI-015" : true, "SI-016" : true, - "SI-017" : true, "SI-018" : true, "SI-019" : true, "SI-020" : true, "SI-021" : true, - "SI-022" : true, "SI-023" : true, "SI-024" : true, "SI-025" : true, "SI-026" : true, - "SI-027" : true, "SI-028" : true, "SI-029" : true, "SI-030" : true, "SI-031" : true, - "SI-032" : true, "SI-033" : true, "SI-034" : true, "SI-035" : true, "SI-036" : true, - "SI-037" : true, "SI-038" : true, "SI-039" : true, "SI-040" : true, "SI-041" : true, - "SI-042" : true, "SI-043" : true, "SI-044" : true, "SI-045" : true, "SI-046" : true, - "SI-047" : true, "SI-048" : true, "SI-049" : true, "SI-050" : true, "SI-051" : true, - "SI-052" : true, "SI-053" : true, "SI-054" : true, "SI-055" : true, "SI-056" : true, - "SI-057" : true, "SI-058" : true, "SI-059" : true, "SI-060" : true, "SI-061" : true, - "SI-062" : true, "SI-063" : true, "SI-064" : true, "SI-065" : true, "SI-066" : true, - "SI-067" : true, "SI-068" : true, "SI-069" : true, "SI-070" : true, "SI-071" : true, - "SI-072" : true, "SI-073" : true, "SI-074" : true, "SI-075" : true, "SI-076" : true, - "SI-077" : true, "SI-078" : true, "SI-079" : true, "SI-080" : true, "SI-081" : true, - "SI-082" : true, "SI-083" : true, "SI-084" : true, "SI-085" : true, "SI-086" : true, - "SI-087" : true, "SI-088" : true, "SI-089" : true, "SI-090" : true, "SI-091" : true, - "SI-092" : true, "SI-093" : true, "SI-094" : true, "SI-095" : true, "SI-096" : true, - "SI-097" : true, "SI-098" : true, "SI-099" : true, "SI-100" : true, "SI-101" : true, - "SI-102" : true, "SI-103" : true, "SI-104" : true, "SI-105" : true, "SI-106" : true, - "SI-107" : true, "SI-108" : true, "SI-109" : true, "SI-110" : true, "SI-111" : true, - "SI-112" : true, "SI-113" : true, "SI-114" : true, "SI-115" : true, "SI-116" : true, - "SI-117" : true, "SI-118" : true, "SI-119" : true, "SI-120" : true, "SI-121" : true, - "SI-122" : true, "SI-123" : true, "SI-124" : true, "SI-125" : true, "SI-126" : true, - "SI-127" : true, "SI-128" : true, "SI-129" : true, "SI-130" : true, "SI-131" : true, - "SI-132" : true, "SI-133" : true, "SI-134" : true, "SI-135" : true, "SI-136" : true, - "SI-137" : true, "SI-138" : true, "SI-139" : true, "SI-140" : true, "SI-141" : true, - "SI-142" : true, "SI-143" : true, "SI-144" : true, "SI-146" : true, "SI-147" : true, - "SI-148" : true, "SI-149" : true, "SI-150" : true, "SI-151" : true, "SI-152" : true, - "SI-153" : true, "SI-154" : true, "SI-155" : true, "SI-156" : true, "SI-157" : true, - "SI-158" : true, "SI-159" : true, "SI-160" : true, "SI-161" : true, "SI-162" : true, - "SI-163" : true, "SI-164" : true, "SI-165" : true, "SI-166" : true, "SI-167" : true, - "SI-168" : true, "SI-169" : true, "SI-170" : true, "SI-171" : true, "SI-172" : true, - "SI-173" : true, "SI-174" : true, "SI-175" : true, "SI-176" : true, "SI-177" : true, - "SI-178" : true, "SI-179" : true, "SI-180" : true, "SI-181" : true, "SI-182" : true, - "SI-183" : true, "SI-184" : true, "SI-185" : true, "SI-186" : true, "SI-187" : true, - "SI-188" : true, "SI-189" : true, "SI-190" : true, "SI-191" : true, "SI-192" : true, - "SI-193" : true, "SI-194" : true, "SI-195" : true, "SI-196" : true, "SI-197" : true, - "SI-198" : true, "SI-199" : true, "SI-200" : true, "SI-201" : true, "SI-202" : true, - "SI-203" : true, "SI-204" : true, "SI-205" : true, "SI-206" : true, "SI-207" : true, - "SI-208" : true, "SI-209" : true, "SI-210" : true, "SI-211" : true, "SK-BC" : true, - "SK-BL" : true, "SK-KI" : true, "SK-NI" : true, "SK-PV" : true, "SK-TA" : true, - "SK-TC" : true, "SK-ZI" : true, "SL-E" : true, "SL-N" : true, "SL-S" : true, - "SL-W" : true, "SM-01" : true, "SM-02" : true, "SM-03" : true, "SM-04" : true, - "SM-05" : true, "SM-06" : true, "SM-07" : true, "SM-08" : true, "SM-09" : true, - "SN-DB" : true, "SN-DK" : true, "SN-FK" : true, "SN-KA" : true, "SN-KD" : true, - "SN-KE" : true, "SN-KL" : true, "SN-LG" : true, "SN-MT" : true, "SN-SE" : true, - "SN-SL" : true, "SN-TC" : true, "SN-TH" : true, "SN-ZG" : true, "SO-AW" : true, - "SO-BK" : true, "SO-BN" : true, "SO-BR" : true, "SO-BY" : true, "SO-GA" : true, - "SO-GE" : true, "SO-HI" : true, "SO-JD" : true, "SO-JH" : true, "SO-MU" : true, - "SO-NU" : true, "SO-SA" : true, "SO-SD" : true, "SO-SH" : true, "SO-SO" : true, - "SO-TO" : true, "SO-WO" : true, "SR-BR" : true, "SR-CM" : true, "SR-CR" : true, - "SR-MA" : true, "SR-NI" : true, "SR-PM" : true, "SR-PR" : true, "SR-SA" : true, - "SR-SI" : true, "SR-WA" : true, "SS-BN" : true, "SS-BW" : true, "SS-EC" : true, - "SS-EE8" : true, "SS-EW" : true, "SS-JG" : true, "SS-LK" : true, "SS-NU" : true, - "SS-UY" : true, "SS-WR" : true, "ST-P" : true, "ST-S" : true, "SV-AH" : true, - "SV-CA" : true, "SV-CH" : true, "SV-CU" : true, "SV-LI" : true, "SV-MO" : true, - "SV-PA" : true, "SV-SA" : true, "SV-SM" : true, "SV-SO" : true, "SV-SS" : true, - "SV-SV" : true, "SV-UN" : true, "SV-US" : true, "SY-DI" : true, "SY-DR" : true, - "SY-DY" : true, "SY-HA" : true, "SY-HI" : true, "SY-HL" : true, "SY-HM" : true, - "SY-ID" : true, "SY-LA" : true, "SY-QU" : true, "SY-RA" : true, "SY-RD" : true, - "SY-SU" : true, "SY-TA" : true, "SZ-HH" : true, "SZ-LU" : true, "SZ-MA" : true, - "SZ-SH" : true, "TD-BA" : true, "TD-BG" : true, "TD-BO" : true, "TD-CB" : true, - "TD-EN" : true, "TD-GR" : true, "TD-HL" : true, "TD-KA" : true, "TD-LC" : true, - "TD-LO" : true, "TD-LR" : true, "TD-MA" : true, "TD-MC" : true, "TD-ME" : true, - "TD-MO" : true, "TD-ND" : true, "TD-OD" : true, "TD-SA" : true, "TD-SI" : true, - "TD-TA" : true, "TD-TI" : true, "TD-WF" : true, "TG-C" : true, "TG-K" : true, - "TG-M" : true, "TG-P" : true, "TG-S" : true, "TH-10" : true, "TH-11" : true, - "TH-12" : true, "TH-13" : true, "TH-14" : true, "TH-15" : true, "TH-16" : true, - "TH-17" : true, "TH-18" : true, "TH-19" : true, "TH-20" : true, "TH-21" : true, - "TH-22" : true, "TH-23" : true, "TH-24" : true, "TH-25" : true, "TH-26" : true, - "TH-27" : true, "TH-30" : true, "TH-31" : true, "TH-32" : true, "TH-33" : true, - "TH-34" : true, "TH-35" : true, "TH-36" : true, "TH-37" : true, "TH-39" : true, - "TH-40" : true, "TH-41" : true, "TH-42" : true, "TH-43" : true, "TH-44" : true, - "TH-45" : true, "TH-46" : true, "TH-47" : true, "TH-48" : true, "TH-49" : true, - "TH-50" : true, "TH-51" : true, "TH-52" : true, "TH-53" : true, "TH-54" : true, - "TH-55" : true, "TH-56" : true, "TH-57" : true, "TH-58" : true, "TH-60" : true, - "TH-61" : true, "TH-62" : true, "TH-63" : true, "TH-64" : true, "TH-65" : true, - "TH-66" : true, "TH-67" : true, "TH-70" : true, "TH-71" : true, "TH-72" : true, - "TH-73" : true, "TH-74" : true, "TH-75" : true, "TH-76" : true, "TH-77" : true, - "TH-80" : true, "TH-81" : true, "TH-82" : true, "TH-83" : true, "TH-84" : true, - "TH-85" : true, "TH-86" : true, "TH-90" : true, "TH-91" : true, "TH-92" : true, - "TH-93" : true, "TH-94" : true, "TH-95" : true, "TH-96" : true, "TH-S" : true, - "TJ-GB" : true, "TJ-KT" : true, "TJ-SU" : true, "TL-AL" : true, "TL-AN" : true, - "TL-BA" : true, "TL-BO" : true, "TL-CO" : true, "TL-DI" : true, "TL-ER" : true, - "TL-LA" : true, "TL-LI" : true, "TL-MF" : true, "TL-MT" : true, "TL-OE" : true, - "TL-VI" : true, "TM-A" : true, "TM-B" : true, "TM-D" : true, "TM-L" : true, - "TM-M" : true, "TM-S" : true, "TN-11" : true, "TN-12" : true, "TN-13" : true, - "TN-14" : true, "TN-21" : true, "TN-22" : true, "TN-23" : true, "TN-31" : true, - "TN-32" : true, "TN-33" : true, "TN-34" : true, "TN-41" : true, "TN-42" : true, - "TN-43" : true, "TN-51" : true, "TN-52" : true, "TN-53" : true, "TN-61" : true, - "TN-71" : true, "TN-72" : true, "TN-73" : true, "TN-81" : true, "TN-82" : true, - "TN-83" : true, "TO-01" : true, "TO-02" : true, "TO-03" : true, "TO-04" : true, - "TO-05" : true, "TR-01" : true, "TR-02" : true, "TR-03" : true, "TR-04" : true, - "TR-05" : true, "TR-06" : true, "TR-07" : true, "TR-08" : true, "TR-09" : true, - "TR-10" : true, "TR-11" : true, "TR-12" : true, "TR-13" : true, "TR-14" : true, - "TR-15" : true, "TR-16" : true, "TR-17" : true, "TR-18" : true, "TR-19" : true, - "TR-20" : true, "TR-21" : true, "TR-22" : true, "TR-23" : true, "TR-24" : true, - "TR-25" : true, "TR-26" : true, "TR-27" : true, "TR-28" : true, "TR-29" : true, - "TR-30" : true, "TR-31" : true, "TR-32" : true, "TR-33" : true, "TR-34" : true, - "TR-35" : true, "TR-36" : true, "TR-37" : true, "TR-38" : true, "TR-39" : true, - "TR-40" : true, "TR-41" : true, "TR-42" : true, "TR-43" : true, "TR-44" : true, - "TR-45" : true, "TR-46" : true, "TR-47" : true, "TR-48" : true, "TR-49" : true, - "TR-50" : true, "TR-51" : true, "TR-52" : true, "TR-53" : true, "TR-54" : true, - "TR-55" : true, "TR-56" : true, "TR-57" : true, "TR-58" : true, "TR-59" : true, - "TR-60" : true, "TR-61" : true, "TR-62" : true, "TR-63" : true, "TR-64" : true, - "TR-65" : true, "TR-66" : true, "TR-67" : true, "TR-68" : true, "TR-69" : true, - "TR-70" : true, "TR-71" : true, "TR-72" : true, "TR-73" : true, "TR-74" : true, - "TR-75" : true, "TR-76" : true, "TR-77" : true, "TR-78" : true, "TR-79" : true, - "TR-80" : true, "TR-81" : true, "TT-ARI" : true, "TT-CHA" : true, "TT-CTT" : true, - "TT-DMN" : true, "TT-ETO" : true, "TT-PED" : true, "TT-POS" : true, "TT-PRT" : true, - "TT-PTF" : true, "TT-RCM" : true, "TT-SFO" : true, "TT-SGE" : true, "TT-SIP" : true, - "TT-SJL" : true, "TT-TUP" : true, "TT-WTO" : true, "TV-FUN" : true, "TV-NIT" : true, - "TV-NKF" : true, "TV-NKL" : true, "TV-NMA" : true, "TV-NMG" : true, "TV-NUI" : true, - "TV-VAI" : true, "TW-CHA" : true, "TW-CYI" : true, "TW-CYQ" : true, "TW-HSQ" : true, - "TW-HSZ" : true, "TW-HUA" : true, "TW-ILA" : true, "TW-KEE" : true, "TW-KHH" : true, - "TW-KHQ" : true, "TW-MIA" : true, "TW-NAN" : true, "TW-PEN" : true, "TW-PIF" : true, - "TW-TAO" : true, "TW-TNN" : true, "TW-TNQ" : true, "TW-TPE" : true, "TW-TPQ" : true, - "TW-TTT" : true, "TW-TXG" : true, "TW-TXQ" : true, "TW-YUN" : true, "TZ-01" : true, - "TZ-02" : true, "TZ-03" : true, "TZ-04" : true, "TZ-05" : true, "TZ-06" : true, - "TZ-07" : true, "TZ-08" : true, "TZ-09" : true, "TZ-10" : true, "TZ-11" : true, - "TZ-12" : true, "TZ-13" : true, "TZ-14" : true, "TZ-15" : true, "TZ-16" : true, - "TZ-17" : true, "TZ-18" : true, "TZ-19" : true, "TZ-20" : true, "TZ-21" : true, - "TZ-22" : true, "TZ-23" : true, "TZ-24" : true, "TZ-25" : true, "TZ-26" : true, - "UA-05" : true, "UA-07" : true, "UA-09" : true, "UA-12" : true, "UA-14" : true, - "UA-18" : true, "UA-21" : true, "UA-23" : true, "UA-26" : true, "UA-30" : true, - "UA-32" : true, "UA-35" : true, "UA-40" : true, "UA-43" : true, "UA-46" : true, - "UA-48" : true, "UA-51" : true, "UA-53" : true, "UA-56" : true, "UA-59" : true, - "UA-61" : true, "UA-63" : true, "UA-65" : true, "UA-68" : true, "UA-71" : true, - "UA-74" : true, "UA-77" : true, "UG-101" : true, "UG-102" : true, "UG-103" : true, - "UG-104" : true, "UG-105" : true, "UG-106" : true, "UG-107" : true, "UG-108" : true, - "UG-109" : true, "UG-110" : true, "UG-111" : true, "UG-112" : true, "UG-113" : true, - "UG-114" : true, "UG-115" : true, "UG-116" : true, "UG-201" : true, "UG-202" : true, - "UG-203" : true, "UG-204" : true, "UG-205" : true, "UG-206" : true, "UG-207" : true, - "UG-208" : true, "UG-209" : true, "UG-210" : true, "UG-211" : true, "UG-212" : true, - "UG-213" : true, "UG-214" : true, "UG-215" : true, "UG-216" : true, "UG-217" : true, - "UG-218" : true, "UG-219" : true, "UG-220" : true, "UG-221" : true, "UG-222" : true, - "UG-223" : true, "UG-224" : true, "UG-301" : true, "UG-302" : true, "UG-303" : true, - "UG-304" : true, "UG-305" : true, "UG-306" : true, "UG-307" : true, "UG-308" : true, - "UG-309" : true, "UG-310" : true, "UG-311" : true, "UG-312" : true, "UG-313" : true, - "UG-314" : true, "UG-315" : true, "UG-316" : true, "UG-317" : true, "UG-318" : true, - "UG-319" : true, "UG-320" : true, "UG-321" : true, "UG-401" : true, "UG-402" : true, - "UG-403" : true, "UG-404" : true, "UG-405" : true, "UG-406" : true, "UG-407" : true, - "UG-408" : true, "UG-409" : true, "UG-410" : true, "UG-411" : true, "UG-412" : true, - "UG-413" : true, "UG-414" : true, "UG-415" : true, "UG-416" : true, "UG-417" : true, - "UG-418" : true, "UG-419" : true, "UG-C" : true, "UG-E" : true, "UG-N" : true, - "UG-W" : true, "UM-67" : true, "UM-71" : true, "UM-76" : true, "UM-79" : true, - "UM-81" : true, "UM-84" : true, "UM-86" : true, "UM-89" : true, "UM-95" : true, - "US-AK" : true, "US-AL" : true, "US-AR" : true, "US-AS" : true, "US-AZ" : true, - "US-CA" : true, "US-CO" : true, "US-CT" : true, "US-DC" : true, "US-DE" : true, - "US-FL" : true, "US-GA" : true, "US-GU" : true, "US-HI" : true, "US-IA" : true, - "US-ID" : true, "US-IL" : true, "US-IN" : true, "US-KS" : true, "US-KY" : true, - "US-LA" : true, "US-MA" : true, "US-MD" : true, "US-ME" : true, "US-MI" : true, - "US-MN" : true, "US-MO" : true, "US-MP" : true, "US-MS" : true, "US-MT" : true, - "US-NC" : true, "US-ND" : true, "US-NE" : true, "US-NH" : true, "US-NJ" : true, - "US-NM" : true, "US-NV" : true, "US-NY" : true, "US-OH" : true, "US-OK" : true, - "US-OR" : true, "US-PA" : true, "US-PR" : true, "US-RI" : true, "US-SC" : true, - "US-SD" : true, "US-TN" : true, "US-TX" : true, "US-UM" : true, "US-UT" : true, - "US-VA" : true, "US-VI" : true, "US-VT" : true, "US-WA" : true, "US-WI" : true, - "US-WV" : true, "US-WY" : true, "UY-AR" : true, "UY-CA" : true, "UY-CL" : true, - "UY-CO" : true, "UY-DU" : true, "UY-FD" : true, "UY-FS" : true, "UY-LA" : true, - "UY-MA" : true, "UY-MO" : true, "UY-PA" : true, "UY-RN" : true, "UY-RO" : true, - "UY-RV" : true, "UY-SA" : true, "UY-SJ" : true, "UY-SO" : true, "UY-TA" : true, - "UY-TT" : true, "UZ-AN" : true, "UZ-BU" : true, "UZ-FA" : true, "UZ-JI" : true, - "UZ-NG" : true, "UZ-NW" : true, "UZ-QA" : true, "UZ-QR" : true, "UZ-SA" : true, - "UZ-SI" : true, "UZ-SU" : true, "UZ-TK" : true, "UZ-TO" : true, "UZ-XO" : true, - "VC-01" : true, "VC-02" : true, "VC-03" : true, "VC-04" : true, "VC-05" : true, - "VC-06" : true, "VE-A" : true, "VE-B" : true, "VE-C" : true, "VE-D" : true, - "VE-E" : true, "VE-F" : true, "VE-G" : true, "VE-H" : true, "VE-I" : true, - "VE-J" : true, "VE-K" : true, "VE-L" : true, "VE-M" : true, "VE-N" : true, - "VE-O" : true, "VE-P" : true, "VE-R" : true, "VE-S" : true, "VE-T" : true, - "VE-U" : true, "VE-V" : true, "VE-W" : true, "VE-X" : true, "VE-Y" : true, - "VE-Z" : true, "VN-01" : true, "VN-02" : true, "VN-03" : true, "VN-04" : true, - "VN-05" : true, "VN-06" : true, "VN-07" : true, "VN-09" : true, "VN-13" : true, - "VN-14" : true, "VN-15" : true, "VN-18" : true, "VN-20" : true, "VN-21" : true, - "VN-22" : true, "VN-23" : true, "VN-24" : true, "VN-25" : true, "VN-26" : true, - "VN-27" : true, "VN-28" : true, "VN-29" : true, "VN-30" : true, "VN-31" : true, - "VN-32" : true, "VN-33" : true, "VN-34" : true, "VN-35" : true, "VN-36" : true, - "VN-37" : true, "VN-39" : true, "VN-40" : true, "VN-41" : true, "VN-43" : true, - "VN-44" : true, "VN-45" : true, "VN-46" : true, "VN-47" : true, "VN-49" : true, - "VN-50" : true, "VN-51" : true, "VN-52" : true, "VN-53" : true, "VN-54" : true, - "VN-55" : true, "VN-56" : true, "VN-57" : true, "VN-58" : true, "VN-59" : true, - "VN-61" : true, "VN-63" : true, "VN-66" : true, "VN-67" : true, "VN-68" : true, - "VN-69" : true, "VN-70" : true, "VN-71" : true, "VN-72" : true, "VN-73" : true, - "VN-CT" : true, "VN-DN" : true, "VN-HN" : true, "VN-HP" : true, "VN-SG" : true, - "VU-MAP" : true, "VU-PAM" : true, "VU-SAM" : true, "VU-SEE" : true, "VU-TAE" : true, - "VU-TOB" : true, "WS-AA" : true, "WS-AL" : true, "WS-AT" : true, "WS-FA" : true, - "WS-GE" : true, "WS-GI" : true, "WS-PA" : true, "WS-SA" : true, "WS-TU" : true, - "WS-VF" : true, "WS-VS" : true, "YE-AB" : true, "YE-AD" : true, "YE-AM" : true, - "YE-BA" : true, "YE-DA" : true, "YE-DH" : true, "YE-HD" : true, "YE-HJ" : true, - "YE-IB" : true, "YE-JA" : true, "YE-LA" : true, "YE-MA" : true, "YE-MR" : true, - "YE-MU" : true, "YE-MW" : true, "YE-RA" : true, "YE-SD" : true, "YE-SH" : true, - "YE-SN" : true, "YE-TA" : true, "ZA-EC" : true, "ZA-FS" : true, "ZA-GP" : true, - "ZA-LP" : true, "ZA-MP" : true, "ZA-NC" : true, "ZA-NW" : true, "ZA-WC" : true, - "ZA-ZN" : true, "ZM-01" : true, "ZM-02" : true, "ZM-03" : true, "ZM-04" : true, - "ZM-05" : true, "ZM-06" : true, "ZM-07" : true, "ZM-08" : true, "ZM-09" : true, - "ZW-BU" : true, "ZW-HA" : true, "ZW-MA" : true, "ZW-MC" : true, "ZW-ME" : true, - "ZW-MI" : true, "ZW-MN" : true, "ZW-MS" : true, "ZW-MV" : true, "ZW-MW" : true, -} diff --git a/vendor/github.com/go-playground/validator/v10/currency_codes.go b/vendor/github.com/go-playground/validator/v10/currency_codes.go deleted file mode 100644 index a5cd9b1..0000000 --- a/vendor/github.com/go-playground/validator/v10/currency_codes.go +++ /dev/null @@ -1,79 +0,0 @@ -package validator - -var iso4217 = map[string]bool{ - "AFN": true, "EUR": true, "ALL": true, "DZD": true, "USD": true, - "AOA": true, "XCD": true, "ARS": true, "AMD": true, "AWG": true, - "AUD": true, "AZN": true, "BSD": true, "BHD": true, "BDT": true, - "BBD": true, "BYN": true, "BZD": true, "XOF": true, "BMD": true, - "INR": true, "BTN": true, "BOB": true, "BOV": true, "BAM": true, - "BWP": true, "NOK": true, "BRL": true, "BND": true, "BGN": true, - "BIF": true, "CVE": true, "KHR": true, "XAF": true, "CAD": true, - "KYD": true, "CLP": true, "CLF": true, "CNY": true, "COP": true, - "COU": true, "KMF": true, "CDF": true, "NZD": true, "CRC": true, - "HRK": true, "CUP": true, "CUC": true, "ANG": true, "CZK": true, - "DKK": true, "DJF": true, "DOP": true, "EGP": true, "SVC": true, - "ERN": true, "SZL": true, "ETB": true, "FKP": true, "FJD": true, - "XPF": true, "GMD": true, "GEL": true, "GHS": true, "GIP": true, - "GTQ": true, "GBP": true, "GNF": true, "GYD": true, "HTG": true, - "HNL": true, "HKD": true, "HUF": true, "ISK": true, "IDR": true, - "XDR": true, "IRR": true, "IQD": true, "ILS": true, "JMD": true, - "JPY": true, "JOD": true, "KZT": true, "KES": true, "KPW": true, - "KRW": true, "KWD": true, "KGS": true, "LAK": true, "LBP": true, - "LSL": true, "ZAR": true, "LRD": true, "LYD": true, "CHF": true, - "MOP": true, "MKD": true, "MGA": true, "MWK": true, "MYR": true, - "MVR": true, "MRU": true, "MUR": true, "XUA": true, "MXN": true, - "MXV": true, "MDL": true, "MNT": true, "MAD": true, "MZN": true, - "MMK": true, "NAD": true, "NPR": true, "NIO": true, "NGN": true, - "OMR": true, "PKR": true, "PAB": true, "PGK": true, "PYG": true, - "PEN": true, "PHP": true, "PLN": true, "QAR": true, "RON": true, - "RUB": true, "RWF": true, "SHP": true, "WST": true, "STN": true, - "SAR": true, "RSD": true, "SCR": true, "SLL": true, "SGD": true, - "XSU": true, "SBD": true, "SOS": true, "SSP": true, "LKR": true, - "SDG": true, "SRD": true, "SEK": true, "CHE": true, "CHW": true, - "SYP": true, "TWD": true, "TJS": true, "TZS": true, "THB": true, - "TOP": true, "TTD": true, "TND": true, "TRY": true, "TMT": true, - "UGX": true, "UAH": true, "AED": true, "USN": true, "UYU": true, - "UYI": true, "UYW": true, "UZS": true, "VUV": true, "VES": true, - "VND": true, "YER": true, "ZMW": true, "ZWL": true, "XBA": true, - "XBB": true, "XBC": true, "XBD": true, "XTS": true, "XXX": true, - "XAU": true, "XPD": true, "XPT": true, "XAG": true, -} - -var iso4217_numeric = map[int]bool{ - 8: true, 12: true, 32: true, 36: true, 44: true, - 48: true, 50: true, 51: true, 52: true, 60: true, - 64: true, 68: true, 72: true, 84: true, 90: true, - 96: true, 104: true, 108: true, 116: true, 124: true, - 132: true, 136: true, 144: true, 152: true, 156: true, - 170: true, 174: true, 188: true, 191: true, 192: true, - 203: true, 208: true, 214: true, 222: true, 230: true, - 232: true, 238: true, 242: true, 262: true, 270: true, - 292: true, 320: true, 324: true, 328: true, 332: true, - 340: true, 344: true, 348: true, 352: true, 356: true, - 360: true, 364: true, 368: true, 376: true, 388: true, - 392: true, 398: true, 400: true, 404: true, 408: true, - 410: true, 414: true, 417: true, 418: true, 422: true, - 426: true, 430: true, 434: true, 446: true, 454: true, - 458: true, 462: true, 480: true, 484: true, 496: true, - 498: true, 504: true, 512: true, 516: true, 524: true, - 532: true, 533: true, 548: true, 554: true, 558: true, - 566: true, 578: true, 586: true, 590: true, 598: true, - 600: true, 604: true, 608: true, 634: true, 643: true, - 646: true, 654: true, 682: true, 690: true, 694: true, - 702: true, 704: true, 706: true, 710: true, 728: true, - 748: true, 752: true, 756: true, 760: true, 764: true, - 776: true, 780: true, 784: true, 788: true, 800: true, - 807: true, 818: true, 826: true, 834: true, 840: true, - 858: true, 860: true, 882: true, 886: true, 901: true, - 927: true, 928: true, 929: true, 930: true, 931: true, - 932: true, 933: true, 934: true, 936: true, 938: true, - 940: true, 941: true, 943: true, 944: true, 946: true, - 947: true, 948: true, 949: true, 950: true, 951: true, - 952: true, 953: true, 955: true, 956: true, 957: true, - 958: true, 959: true, 960: true, 961: true, 962: true, - 963: true, 964: true, 965: true, 967: true, 968: true, - 969: true, 970: true, 971: true, 972: true, 973: true, - 975: true, 976: true, 977: true, 978: true, 979: true, - 980: true, 981: true, 984: true, 985: true, 986: true, - 990: true, 994: true, 997: true, 999: true, -} diff --git a/vendor/github.com/go-playground/validator/v10/doc.go b/vendor/github.com/go-playground/validator/v10/doc.go deleted file mode 100644 index 7341c67..0000000 --- a/vendor/github.com/go-playground/validator/v10/doc.go +++ /dev/null @@ -1,1401 +0,0 @@ -/* -Package validator implements value validations for structs and individual fields -based on tags. - -It can also handle Cross-Field and Cross-Struct validation for nested structs -and has the ability to dive into arrays and maps of any type. - -see more examples https://github.com/go-playground/validator/tree/master/_examples - -Singleton - -Validator is designed to be thread-safe and used as a singleton instance. -It caches information about your struct and validations, -in essence only parsing your validation tags once per struct type. -Using multiple instances neglects the benefit of caching. -The not thread-safe functions are explicitly marked as such in the documentation. - -Validation Functions Return Type error - -Doing things this way is actually the way the standard library does, see the -file.Open method here: - - https://golang.org/pkg/os/#Open. - -The authors return type "error" to avoid the issue discussed in the following, -where err is always != nil: - - http://stackoverflow.com/a/29138676/3158232 - https://github.com/go-playground/validator/issues/134 - -Validator only InvalidValidationError for bad validation input, nil or -ValidationErrors as type error; so, in your code all you need to do is check -if the error returned is not nil, and if it's not check if error is -InvalidValidationError ( if necessary, most of the time it isn't ) type cast -it to type ValidationErrors like so err.(validator.ValidationErrors). - -Custom Validation Functions - -Custom Validation functions can be added. Example: - - // Structure - func customFunc(fl validator.FieldLevel) bool { - - if fl.Field().String() == "invalid" { - return false - } - - return true - } - - validate.RegisterValidation("custom tag name", customFunc) - // NOTES: using the same tag name as an existing function - // will overwrite the existing one - -Cross-Field Validation - -Cross-Field Validation can be done via the following tags: - - eqfield - - nefield - - gtfield - - gtefield - - ltfield - - ltefield - - eqcsfield - - necsfield - - gtcsfield - - gtecsfield - - ltcsfield - - ltecsfield - -If, however, some custom cross-field validation is required, it can be done -using a custom validation. - -Why not just have cross-fields validation tags (i.e. only eqcsfield and not -eqfield)? - -The reason is efficiency. If you want to check a field within the same struct -"eqfield" only has to find the field on the same struct (1 level). But, if we -used "eqcsfield" it could be multiple levels down. Example: - - type Inner struct { - StartDate time.Time - } - - type Outer struct { - InnerStructField *Inner - CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"` - } - - now := time.Now() - - inner := &Inner{ - StartDate: now, - } - - outer := &Outer{ - InnerStructField: inner, - CreatedAt: now, - } - - errs := validate.Struct(outer) - - // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed - // into the function - // when calling validate.VarWithValue(val, field, tag) val will be - // whatever you pass, struct, field... - // when calling validate.Field(field, tag) val will be nil - -Multiple Validators - -Multiple validators on a field will process in the order defined. Example: - - type Test struct { - Field `validate:"max=10,min=1"` - } - - // max will be checked then min - -Bad Validator definitions are not handled by the library. Example: - - type Test struct { - Field `validate:"min=10,max=0"` - } - - // this definition of min max will never succeed - -Using Validator Tags - -Baked In Cross-Field validation only compares fields on the same struct. -If Cross-Field + Cross-Struct validation is needed you should implement your -own custom validator. - -Comma (",") is the default separator of validation tags. If you wish to -have a comma included within the parameter (i.e. excludesall=,) you will need to -use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma, -so the above will become excludesall=0x2C. - - type Test struct { - Field `validate:"excludesall=,"` // BAD! Do not include a comma. - Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation. - } - -Pipe ("|") is the 'or' validation tags deparator. If you wish to -have a pipe included within the parameter i.e. excludesall=| you will need to -use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe, -so the above will become excludesall=0x7C - - type Test struct { - Field `validate:"excludesall=|"` // BAD! Do not include a a pipe! - Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation. - } - - -Baked In Validators and Tags - -Here is a list of the current built in validators: - - -Skip Field - -Tells the validation to skip this struct field; this is particularly -handy in ignoring embedded structs from being validated. (Usage: -) - Usage: - - - -Or Operator - -This is the 'or' operator allowing multiple validators to be used and -accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba -colors to be accepted. This can also be combined with 'and' for example -( Usage: omitempty,rgb|rgba) - - Usage: | - -StructOnly - -When a field that is a nested struct is encountered, and contains this flag -any validation on the nested struct will be run, but none of the nested -struct fields will be validated. This is useful if inside of your program -you know the struct will be valid, but need to verify it has been assigned. -NOTE: only "required" and "omitempty" can be used on a struct itself. - - Usage: structonly - -NoStructLevel - -Same as structonly tag except that any struct level validations will not run. - - Usage: nostructlevel - -Omit Empty - -Allows conditional validation, for example if a field is not set with -a value (Determined by the "required" validator) then other validation -such as min or max won't run, but if a value is set validation will run. - - Usage: omitempty - -Dive - -This tells the validator to dive into a slice, array or map and validate that -level of the slice, array or map with the validation tags that follow. -Multidimensional nesting is also supported, each level you wish to dive will -require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see -the Keys & EndKeys section just below. - - Usage: dive - -Example #1 - - [][]string with validation tag "gt=0,dive,len=1,dive,required" - // gt=0 will be applied to [] - // len=1 will be applied to []string - // required will be applied to string - -Example #2 - - [][]string with validation tag "gt=0,dive,dive,required" - // gt=0 will be applied to [] - // []string will be spared validation - // required will be applied to string - -Keys & EndKeys - -These are to be used together directly after the dive tag and tells the validator -that anything between 'keys' and 'endkeys' applies to the keys of a map and not the -values; think of it like the 'dive' tag, but for map keys instead of values. -Multidimensional nesting is also supported, each level you wish to validate will -require another 'keys' and 'endkeys' tag. These tags are only valid for maps. - - Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags - -Example #1 - - map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required" - // gt=0 will be applied to the map itself - // eg=1|eq=2 will be applied to the map keys - // required will be applied to map values - -Example #2 - - map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required" - // gt=0 will be applied to the map itself - // eg=1|eq=2 will be applied to each array element in the the map keys - // required will be applied to map values - -Required - -This validates that the value is not the data types default zero value. -For numbers ensures value is not zero. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required - -Required If - -The field under validation must be present and not empty only if all -the other specified fields are equal to the value following the specified -field. For strings ensures value is not "". For slices, maps, pointers, -interfaces, channels and functions ensures the value is not nil. - - Usage: required_if - -Examples: - - // require the field if the Field1 is equal to the parameter given: - Usage: required_if=Field1 foobar - - // require the field if the Field1 and Field2 is equal to the value respectively: - Usage: required_if=Field1 foo Field2 bar - -Required Unless - -The field under validation must be present and not empty unless all -the other specified fields are equal to the value following the specified -field. For strings ensures value is not "". For slices, maps, pointers, -interfaces, channels and functions ensures the value is not nil. - - Usage: required_unless - -Examples: - - // require the field unless the Field1 is equal to the parameter given: - Usage: required_unless=Field1 foobar - - // require the field unless the Field1 and Field2 is equal to the value respectively: - Usage: required_unless=Field1 foo Field2 bar - -Required With - -The field under validation must be present and not empty only if any -of the other specified fields are present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_with - -Examples: - - // require the field if the Field1 is present: - Usage: required_with=Field1 - - // require the field if the Field1 or Field2 is present: - Usage: required_with=Field1 Field2 - -Required With All - -The field under validation must be present and not empty only if all -of the other specified fields are present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_with_all - -Example: - - // require the field if the Field1 and Field2 is present: - Usage: required_with_all=Field1 Field2 - -Required Without - -The field under validation must be present and not empty only when any -of the other specified fields are not present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_without - -Examples: - - // require the field if the Field1 is not present: - Usage: required_without=Field1 - - // require the field if the Field1 or Field2 is not present: - Usage: required_without=Field1 Field2 - -Required Without All - -The field under validation must be present and not empty only when all -of the other specified fields are not present. For strings ensures value is -not "". For slices, maps, pointers, interfaces, channels and functions -ensures the value is not nil. - - Usage: required_without_all - -Example: - - // require the field if the Field1 and Field2 is not present: - Usage: required_without_all=Field1 Field2 - -Excluded If - -The field under validation must not be present or not empty only if all -the other specified fields are equal to the value following the specified -field. For strings ensures value is not "". For slices, maps, pointers, -interfaces, channels and functions ensures the value is not nil. - - Usage: excluded_if - -Examples: - - // exclude the field if the Field1 is equal to the parameter given: - Usage: excluded_if=Field1 foobar - - // exclude the field if the Field1 and Field2 is equal to the value respectively: - Usage: excluded_if=Field1 foo Field2 bar - -Excluded Unless - -The field under validation must not be present or empty unless all -the other specified fields are equal to the value following the specified -field. For strings ensures value is not "". For slices, maps, pointers, -interfaces, channels and functions ensures the value is not nil. - - Usage: excluded_unless - -Examples: - - // exclude the field unless the Field1 is equal to the parameter given: - Usage: excluded_unless=Field1 foobar - - // exclude the field unless the Field1 and Field2 is equal to the value respectively: - Usage: excluded_unless=Field1 foo Field2 bar - -Is Default - -This validates that the value is the default value and is almost the -opposite of required. - - Usage: isdefault - -Length - -For numbers, length will ensure that the value is -equal to the parameter given. For strings, it checks that -the string length is exactly that number of characters. For slices, -arrays, and maps, validates the number of items. - -Example #1 - - Usage: len=10 - -Example #2 (time.Duration) - -For time.Duration, len will ensure that the value is equal to the duration given -in the parameter. - - Usage: len=1h30m - -Maximum - -For numbers, max will ensure that the value is -less than or equal to the parameter given. For strings, it checks -that the string length is at most that number of characters. For -slices, arrays, and maps, validates the number of items. - -Example #1 - - Usage: max=10 - -Example #2 (time.Duration) - -For time.Duration, max will ensure that the value is less than or equal to the -duration given in the parameter. - - Usage: max=1h30m - -Minimum - -For numbers, min will ensure that the value is -greater or equal to the parameter given. For strings, it checks that -the string length is at least that number of characters. For slices, -arrays, and maps, validates the number of items. - -Example #1 - - Usage: min=10 - -Example #2 (time.Duration) - -For time.Duration, min will ensure that the value is greater than or equal to -the duration given in the parameter. - - Usage: min=1h30m - -Equals - -For strings & numbers, eq will ensure that the value is -equal to the parameter given. For slices, arrays, and maps, -validates the number of items. - -Example #1 - - Usage: eq=10 - -Example #2 (time.Duration) - -For time.Duration, eq will ensure that the value is equal to the duration given -in the parameter. - - Usage: eq=1h30m - -Not Equal - -For strings & numbers, ne will ensure that the value is not -equal to the parameter given. For slices, arrays, and maps, -validates the number of items. - -Example #1 - - Usage: ne=10 - -Example #2 (time.Duration) - -For time.Duration, ne will ensure that the value is not equal to the duration -given in the parameter. - - Usage: ne=1h30m - -One Of - -For strings, ints, and uints, oneof will ensure that the value -is one of the values in the parameter. The parameter should be -a list of values separated by whitespace. Values may be -strings or numbers. To match strings with spaces in them, include -the target string between single quotes. - - Usage: oneof=red green - oneof='red green' 'blue yellow' - oneof=5 7 9 - -Greater Than - -For numbers, this will ensure that the value is greater than the -parameter given. For strings, it checks that the string length -is greater than that number of characters. For slices, arrays -and maps it validates the number of items. - -Example #1 - - Usage: gt=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is greater than time.Now.UTC(). - - Usage: gt - -Example #3 (time.Duration) - -For time.Duration, gt will ensure that the value is greater than the duration -given in the parameter. - - Usage: gt=1h30m - -Greater Than or Equal - -Same as 'min' above. Kept both to make terminology with 'len' easier. - -Example #1 - - Usage: gte=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is greater than or equal to time.Now.UTC(). - - Usage: gte - -Example #3 (time.Duration) - -For time.Duration, gte will ensure that the value is greater than or equal to -the duration given in the parameter. - - Usage: gte=1h30m - -Less Than - -For numbers, this will ensure that the value is less than the parameter given. -For strings, it checks that the string length is less than that number of -characters. For slices, arrays, and maps it validates the number of items. - -Example #1 - - Usage: lt=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is less than time.Now.UTC(). - - Usage: lt - -Example #3 (time.Duration) - -For time.Duration, lt will ensure that the value is less than the duration given -in the parameter. - - Usage: lt=1h30m - -Less Than or Equal - -Same as 'max' above. Kept both to make terminology with 'len' easier. - -Example #1 - - Usage: lte=10 - -Example #2 (time.Time) - -For time.Time ensures the time value is less than or equal to time.Now.UTC(). - - Usage: lte - -Example #3 (time.Duration) - -For time.Duration, lte will ensure that the value is less than or equal to the -duration given in the parameter. - - Usage: lte=1h30m - -Field Equals Another Field - -This will validate the field value against another fields value either within -a struct or passed in field. - -Example #1: - - // Validation on Password field using: - Usage: eqfield=ConfirmPassword - -Example #2: - - // Validating by field: - validate.VarWithValue(password, confirmpassword, "eqfield") - -Field Equals Another Field (relative) - -This does the same as eqfield except that it validates the field provided relative -to the top level struct. - - Usage: eqcsfield=InnerStructField.Field) - -Field Does Not Equal Another Field - -This will validate the field value against another fields value either within -a struct or passed in field. - -Examples: - - // Confirm two colors are not the same: - // - // Validation on Color field: - Usage: nefield=Color2 - - // Validating by field: - validate.VarWithValue(color1, color2, "nefield") - -Field Does Not Equal Another Field (relative) - -This does the same as nefield except that it validates the field provided -relative to the top level struct. - - Usage: necsfield=InnerStructField.Field - -Field Greater Than Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(gtfield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "gtfield") - -Field Greater Than Another Relative Field - -This does the same as gtfield except that it validates the field provided -relative to the top level struct. - - Usage: gtcsfield=InnerStructField.Field - -Field Greater Than or Equal To Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(gtefield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "gtefield") - -Field Greater Than or Equal To Another Relative Field - -This does the same as gtefield except that it validates the field provided relative -to the top level struct. - - Usage: gtecsfield=InnerStructField.Field - -Less Than Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(ltfield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "ltfield") - -Less Than Another Relative Field - -This does the same as ltfield except that it validates the field provided relative -to the top level struct. - - Usage: ltcsfield=InnerStructField.Field - -Less Than or Equal To Another Field - -Only valid for Numbers, time.Duration and time.Time types, this will validate -the field value against another fields value either within a struct or passed in -field. usage examples are for validation of a Start and End date: - -Example #1: - - // Validation on End field using: - validate.Struct Usage(ltefield=Start) - -Example #2: - - // Validating by field: - validate.VarWithValue(start, end, "ltefield") - -Less Than or Equal To Another Relative Field - -This does the same as ltefield except that it validates the field provided relative -to the top level struct. - - Usage: ltecsfield=InnerStructField.Field - -Field Contains Another Field - -This does the same as contains except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. - - Usage: containsfield=InnerStructField.Field - -Field Excludes Another Field - -This does the same as excludes except for struct fields. It should only be used -with string types. See the behavior of reflect.Value.String() for behavior on -other types. - - Usage: excludesfield=InnerStructField.Field - -Unique - -For arrays & slices, unique will ensure that there are no duplicates. -For maps, unique will ensure that there are no duplicate values. -For slices of struct, unique will ensure that there are no duplicate values -in a field of the struct specified via a parameter. - - // For arrays, slices, and maps: - Usage: unique - - // For slices of struct: - Usage: unique=field - -Alpha Only - -This validates that a string value contains ASCII alpha characters only - - Usage: alpha - -Alphanumeric - -This validates that a string value contains ASCII alphanumeric characters only - - Usage: alphanum - -Alpha Unicode - -This validates that a string value contains unicode alpha characters only - - Usage: alphaunicode - -Alphanumeric Unicode - -This validates that a string value contains unicode alphanumeric characters only - - Usage: alphanumunicode - -Boolean - -This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool - - Usage: boolean - -Number - -This validates that a string value contains number values only. -For integers or float it returns true. - - Usage: number - -Numeric - -This validates that a string value contains a basic numeric value. -basic excludes exponents etc... -for integers or float it returns true. - - Usage: numeric - -Hexadecimal String - -This validates that a string value contains a valid hexadecimal. - - Usage: hexadecimal - -Hexcolor String - -This validates that a string value contains a valid hex color including -hashtag (#) - - Usage: hexcolor - -Lowercase String - -This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string. - - Usage: lowercase - -Uppercase String - -This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string. - - Usage: uppercase - -RGB String - -This validates that a string value contains a valid rgb color - - Usage: rgb - -RGBA String - -This validates that a string value contains a valid rgba color - - Usage: rgba - -HSL String - -This validates that a string value contains a valid hsl color - - Usage: hsl - -HSLA String - -This validates that a string value contains a valid hsla color - - Usage: hsla - -E.164 Phone Number String - -This validates that a string value contains a valid E.164 Phone number -https://en.wikipedia.org/wiki/E.164 (ex. +1123456789) - - Usage: e164 - -E-mail String - -This validates that a string value contains a valid email -This may not conform to all possibilities of any rfc standard, but neither -does any email provider accept all possibilities. - - Usage: email - -JSON String - -This validates that a string value is valid JSON - - Usage: json - -JWT String - -This validates that a string value is a valid JWT - - Usage: jwt - -File path - -This validates that a string value contains a valid file path and that -the file exists on the machine. -This is done using os.Stat, which is a platform independent function. - - Usage: file - -URL String - -This validates that a string value contains a valid url -This will accept any url the golang request uri accepts but must contain -a schema for example http:// or rtmp:// - - Usage: url - -URI String - -This validates that a string value contains a valid uri -This will accept any uri the golang request uri accepts - - Usage: uri - -Urn RFC 2141 String - -This validataes that a string value contains a valid URN -according to the RFC 2141 spec. - - Usage: urn_rfc2141 - -Base64 String - -This validates that a string value contains a valid base64 value. -Although an empty string is valid base64 this will report an empty string -as an error, if you wish to accept an empty string as valid you can use -this with the omitempty tag. - - Usage: base64 - -Base64URL String - -This validates that a string value contains a valid base64 URL safe value -according the the RFC4648 spec. -Although an empty string is a valid base64 URL safe value, this will report -an empty string as an error, if you wish to accept an empty string as valid -you can use this with the omitempty tag. - - Usage: base64url - -Bitcoin Address - -This validates that a string value contains a valid bitcoin address. -The format of the string is checked to ensure it matches one of the three formats -P2PKH, P2SH and performs checksum validation. - - Usage: btc_addr - -Bitcoin Bech32 Address (segwit) - -This validates that a string value contains a valid bitcoin Bech32 address as defined -by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki) -Special thanks to Pieter Wuille for providng reference implementations. - - Usage: btc_addr_bech32 - -Ethereum Address - -This validates that a string value contains a valid ethereum address. -The format of the string is checked to ensure it matches the standard Ethereum address format. - - Usage: eth_addr - -Contains - -This validates that a string value contains the substring value. - - Usage: contains=@ - -Contains Any - -This validates that a string value contains any Unicode code points -in the substring value. - - Usage: containsany=!@#? - -Contains Rune - -This validates that a string value contains the supplied rune value. - - Usage: containsrune=@ - -Excludes - -This validates that a string value does not contain the substring value. - - Usage: excludes=@ - -Excludes All - -This validates that a string value does not contain any Unicode code -points in the substring value. - - Usage: excludesall=!@#? - -Excludes Rune - -This validates that a string value does not contain the supplied rune value. - - Usage: excludesrune=@ - -Starts With - -This validates that a string value starts with the supplied string value - - Usage: startswith=hello - -Ends With - -This validates that a string value ends with the supplied string value - - Usage: endswith=goodbye - -Does Not Start With - -This validates that a string value does not start with the supplied string value - - Usage: startsnotwith=hello - -Does Not End With - -This validates that a string value does not end with the supplied string value - - Usage: endsnotwith=goodbye - -International Standard Book Number - -This validates that a string value contains a valid isbn10 or isbn13 value. - - Usage: isbn - -International Standard Book Number 10 - -This validates that a string value contains a valid isbn10 value. - - Usage: isbn10 - -International Standard Book Number 13 - -This validates that a string value contains a valid isbn13 value. - - Usage: isbn13 - -Universally Unique Identifier UUID - -This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead. - - Usage: uuid - -Universally Unique Identifier UUID v3 - -This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead. - - Usage: uuid3 - -Universally Unique Identifier UUID v4 - -This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead. - - Usage: uuid4 - -Universally Unique Identifier UUID v5 - -This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead. - - Usage: uuid5 - -Universally Unique Lexicographically Sortable Identifier ULID - -This validates that a string value contains a valid ULID value. - - Usage: ulid - -ASCII - -This validates that a string value contains only ASCII characters. -NOTE: if the string is blank, this validates as true. - - Usage: ascii - -Printable ASCII - -This validates that a string value contains only printable ASCII characters. -NOTE: if the string is blank, this validates as true. - - Usage: printascii - -Multi-Byte Characters - -This validates that a string value contains one or more multibyte characters. -NOTE: if the string is blank, this validates as true. - - Usage: multibyte - -Data URL - -This validates that a string value contains a valid DataURI. -NOTE: this will also validate that the data portion is valid base64 - - Usage: datauri - -Latitude - -This validates that a string value contains a valid latitude. - - Usage: latitude - -Longitude - -This validates that a string value contains a valid longitude. - - Usage: longitude - -Social Security Number SSN - -This validates that a string value contains a valid U.S. Social Security Number. - - Usage: ssn - -Internet Protocol Address IP - -This validates that a string value contains a valid IP Address. - - Usage: ip - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid v4 IP Address. - - Usage: ipv4 - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid v6 IP Address. - - Usage: ipv6 - -Classless Inter-Domain Routing CIDR - -This validates that a string value contains a valid CIDR Address. - - Usage: cidr - -Classless Inter-Domain Routing CIDRv4 - -This validates that a string value contains a valid v4 CIDR Address. - - Usage: cidrv4 - -Classless Inter-Domain Routing CIDRv6 - -This validates that a string value contains a valid v6 CIDR Address. - - Usage: cidrv6 - -Transmission Control Protocol Address TCP - -This validates that a string value contains a valid resolvable TCP Address. - - Usage: tcp_addr - -Transmission Control Protocol Address TCPv4 - -This validates that a string value contains a valid resolvable v4 TCP Address. - - Usage: tcp4_addr - -Transmission Control Protocol Address TCPv6 - -This validates that a string value contains a valid resolvable v6 TCP Address. - - Usage: tcp6_addr - -User Datagram Protocol Address UDP - -This validates that a string value contains a valid resolvable UDP Address. - - Usage: udp_addr - -User Datagram Protocol Address UDPv4 - -This validates that a string value contains a valid resolvable v4 UDP Address. - - Usage: udp4_addr - -User Datagram Protocol Address UDPv6 - -This validates that a string value contains a valid resolvable v6 UDP Address. - - Usage: udp6_addr - -Internet Protocol Address IP - -This validates that a string value contains a valid resolvable IP Address. - - Usage: ip_addr - -Internet Protocol Address IPv4 - -This validates that a string value contains a valid resolvable v4 IP Address. - - Usage: ip4_addr - -Internet Protocol Address IPv6 - -This validates that a string value contains a valid resolvable v6 IP Address. - - Usage: ip6_addr - -Unix domain socket end point Address - -This validates that a string value contains a valid Unix Address. - - Usage: unix_addr - -Media Access Control Address MAC - -This validates that a string value contains a valid MAC Address. - - Usage: mac - -Note: See Go's ParseMAC for accepted formats and types: - - http://golang.org/src/net/mac.go?s=866:918#L29 - -Hostname RFC 952 - -This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952 - - Usage: hostname - -Hostname RFC 1123 - -This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123 - - Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias. - -Full Qualified Domain Name (FQDN) - -This validates that a string value contains a valid FQDN. - - Usage: fqdn - -HTML Tags - -This validates that a string value appears to be an HTML element tag -including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element - - Usage: html - -HTML Encoded - -This validates that a string value is a proper character reference in decimal -or hexadecimal format - - Usage: html_encoded - -URL Encoded - -This validates that a string value is percent-encoded (URL encoded) according -to https://tools.ietf.org/html/rfc3986#section-2.1 - - Usage: url_encoded - -Directory - -This validates that a string value contains a valid directory and that -it exists on the machine. -This is done using os.Stat, which is a platform independent function. - - Usage: dir - -HostPort - -This validates that a string value contains a valid DNS hostname and port that -can be used to valiate fields typically passed to sockets and connections. - - Usage: hostname_port - -Datetime - -This validates that a string value is a valid datetime based on the supplied datetime format. -Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/ - - Usage: datetime=2006-01-02 - -Iso3166-1 alpha-2 - -This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard. -see: https://www.iso.org/iso-3166-country-codes.html - - Usage: iso3166_1_alpha2 - -Iso3166-1 alpha-3 - -This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard. -see: https://www.iso.org/iso-3166-country-codes.html - - Usage: iso3166_1_alpha3 - -Iso3166-1 alpha-numeric - -This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard. -see: https://www.iso.org/iso-3166-country-codes.html - - Usage: iso3166_1_alpha3 - -BCP 47 Language Tag - -This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse. -More information on https://pkg.go.dev/golang.org/x/text/language - - Usage: bcp47_language_tag - -BIC (SWIFT code) - -This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362. -More information on https://www.iso.org/standard/60390.html - - Usage: bic - -RFC 1035 label - -This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035. -More information on https://datatracker.ietf.org/doc/html/rfc1035 - - Usage: dns_rfc1035_label - -TimeZone - -This validates that a string value is a valid time zone based on the time zone database present on the system. -Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator. -More information on https://golang.org/pkg/time/#LoadLocation - - Usage: timezone - -Semantic Version - -This validates that a string value is a valid semver version, defined in Semantic Versioning 2.0.0. -More information on https://semver.org/ - - Usage: semver - -Credit Card - -This validates that a string value contains a valid credit card number using Luhn algoritm. - - Usage: credit_card - -Alias Validators and Tags - -NOTE: When returning an error, the tag returned in "FieldError" will be -the alias tag unless the dive tag is part of the alias. Everything after the -dive tag is not reported as the alias tag. Also, the "ActualTag" in the before -case will be the actual tag within the alias that failed. - -Here is a list of the current built in alias tags: - - "iscolor" - alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor) - "country_code" - alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code) - -Validator notes: - - regex - a regex validator won't be added because commas and = signs can be part - of a regex which conflict with the validation definitions. Although - workarounds can be made, they take away from using pure regex's. - Furthermore it's quick and dirty but the regex's become harder to - maintain and are not reusable, so it's as much a programming philosophy - as anything. - - In place of this new validator functions should be created; a regex can - be used within the validator function and even be precompiled for better - efficiency within regexes.go. - - And the best reason, you can submit a pull request and we can keep on - adding to the validation library of this package! - -Non standard validators - -A collection of validation rules that are frequently needed but are more -complex than the ones found in the baked in validators. -A non standard validator must be registered manually like you would -with your own custom validation functions. - -Example of registration and use: - - type Test struct { - TestField string `validate:"yourtag"` - } - - t := &Test{ - TestField: "Test" - } - - validate := validator.New() - validate.RegisterValidation("yourtag", validators.NotBlank) - -Here is a list of the current non standard validators: - - NotBlank - This validates that the value is not blank or with length zero. - For strings ensures they do not contain only spaces. For channels, maps, slices and arrays - ensures they don't have zero length. For others, a non empty value is required. - - Usage: notblank - -Panics - -This package panics when bad input is provided, this is by design, bad code like -that should not make it to production. - - type Test struct { - TestField string `validate:"nonexistantfunction=1"` - } - - t := &Test{ - TestField: "Test" - } - - validate.Struct(t) // this will panic -*/ -package validator diff --git a/vendor/github.com/go-playground/validator/v10/errors.go b/vendor/github.com/go-playground/validator/v10/errors.go deleted file mode 100644 index 9a1b1ab..0000000 --- a/vendor/github.com/go-playground/validator/v10/errors.go +++ /dev/null @@ -1,275 +0,0 @@ -package validator - -import ( - "bytes" - "fmt" - "reflect" - "strings" - - ut "github.com/go-playground/universal-translator" -) - -const ( - fieldErrMsg = "Key: '%s' Error:Field validation for '%s' failed on the '%s' tag" -) - -// ValidationErrorsTranslations is the translation return type -type ValidationErrorsTranslations map[string]string - -// InvalidValidationError describes an invalid argument passed to -// `Struct`, `StructExcept`, StructPartial` or `Field` -type InvalidValidationError struct { - Type reflect.Type -} - -// Error returns InvalidValidationError message -func (e *InvalidValidationError) Error() string { - - if e.Type == nil { - return "validator: (nil)" - } - - return "validator: (nil " + e.Type.String() + ")" -} - -// ValidationErrors is an array of FieldError's -// for use in custom error messages post validation. -type ValidationErrors []FieldError - -// Error is intended for use in development + debugging and not intended to be a production error message. -// It allows ValidationErrors to subscribe to the Error interface. -// All information to create an error message specific to your application is contained within -// the FieldError found within the ValidationErrors array -func (ve ValidationErrors) Error() string { - - buff := bytes.NewBufferString("") - - var fe *fieldError - - for i := 0; i < len(ve); i++ { - - fe = ve[i].(*fieldError) - buff.WriteString(fe.Error()) - buff.WriteString("\n") - } - - return strings.TrimSpace(buff.String()) -} - -// Translate translates all of the ValidationErrors -func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { - - trans := make(ValidationErrorsTranslations) - - var fe *fieldError - - for i := 0; i < len(ve); i++ { - fe = ve[i].(*fieldError) - - // // in case an Anonymous struct was used, ensure that the key - // // would be 'Username' instead of ".Username" - // if len(fe.ns) > 0 && fe.ns[:1] == "." { - // trans[fe.ns[1:]] = fe.Translate(ut) - // continue - // } - - trans[fe.ns] = fe.Translate(ut) - } - - return trans -} - -// FieldError contains all functions to get error details -type FieldError interface { - - // Tag returns the validation tag that failed. if the - // validation was an alias, this will return the - // alias name and not the underlying tag that failed. - // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "iscolor" - Tag() string - - // ActualTag returns the validation tag that failed, even if an - // alias the actual tag within the alias will be returned. - // If an 'or' validation fails the entire or will be returned. - // - // eg. alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" - // will return "hexcolor|rgb|rgba|hsl|hsla" - ActualTag() string - - // Namespace returns the namespace for the field error, with the tag - // name taking precedence over the field's actual name. - // - // eg. JSON name "User.fname" - // - // See StructNamespace() for a version that returns actual names. - // - // NOTE: this field can be blank when validating a single primitive field - // using validate.Field(...) as there is no way to extract it's name - Namespace() string - - // StructNamespace returns the namespace for the field error, with the field's - // actual name. - // - // eq. "User.FirstName" see Namespace for comparison - // - // NOTE: this field can be blank when validating a single primitive field - // using validate.Field(...) as there is no way to extract its name - StructNamespace() string - - // Field returns the fields name with the tag name taking precedence over the - // field's actual name. - // - // eq. JSON name "fname" - // see StructField for comparison - Field() string - - // StructField returns the field's actual name from the struct, when able to determine. - // - // eq. "FirstName" - // see Field for comparison - StructField() string - - // Value returns the actual field's value in case needed for creating the error - // message - Value() interface{} - - // Param returns the param value, in string form for comparison; this will also - // help with generating an error message - Param() string - - // Kind returns the Field's reflect Kind - // - // eg. time.Time's kind is a struct - Kind() reflect.Kind - - // Type returns the Field's reflect Type - // - // eg. time.Time's type is time.Time - Type() reflect.Type - - // Translate returns the FieldError's translated error - // from the provided 'ut.Translator' and registered 'TranslationFunc' - // - // NOTE: if no registered translator can be found it returns the same as - // calling fe.Error() - Translate(ut ut.Translator) string - - // Error returns the FieldError's message - Error() string -} - -// compile time interface checks -var _ FieldError = new(fieldError) -var _ error = new(fieldError) - -// fieldError contains a single field's validation error along -// with other properties that may be needed for error message creation -// it complies with the FieldError interface -type fieldError struct { - v *Validate - tag string - actualTag string - ns string - structNs string - fieldLen uint8 - structfieldLen uint8 - value interface{} - param string - kind reflect.Kind - typ reflect.Type -} - -// Tag returns the validation tag that failed. -func (fe *fieldError) Tag() string { - return fe.tag -} - -// ActualTag returns the validation tag that failed, even if an -// alias the actual tag within the alias will be returned. -func (fe *fieldError) ActualTag() string { - return fe.actualTag -} - -// Namespace returns the namespace for the field error, with the tag -// name taking precedence over the field's actual name. -func (fe *fieldError) Namespace() string { - return fe.ns -} - -// StructNamespace returns the namespace for the field error, with the field's -// actual name. -func (fe *fieldError) StructNamespace() string { - return fe.structNs -} - -// Field returns the field's name with the tag name taking precedence over the -// field's actual name. -func (fe *fieldError) Field() string { - - return fe.ns[len(fe.ns)-int(fe.fieldLen):] - // // return fe.field - // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] - - // log.Println("FLD:", fld) - - // if len(fld) > 0 && fld[:1] == "." { - // return fld[1:] - // } - - // return fld -} - -// StructField returns the field's actual name from the struct, when able to determine. -func (fe *fieldError) StructField() string { - // return fe.structField - return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):] -} - -// Value returns the actual field's value in case needed for creating the error -// message -func (fe *fieldError) Value() interface{} { - return fe.value -} - -// Param returns the param value, in string form for comparison; this will -// also help with generating an error message -func (fe *fieldError) Param() string { - return fe.param -} - -// Kind returns the Field's reflect Kind -func (fe *fieldError) Kind() reflect.Kind { - return fe.kind -} - -// Type returns the Field's reflect Type -func (fe *fieldError) Type() reflect.Type { - return fe.typ -} - -// Error returns the fieldError's error message -func (fe *fieldError) Error() string { - return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag) -} - -// Translate returns the FieldError's translated error -// from the provided 'ut.Translator' and registered 'TranslationFunc' -// -// NOTE: if no registered translation can be found, it returns the original -// untranslated error message. -func (fe *fieldError) Translate(ut ut.Translator) string { - - m, ok := fe.v.transTagFunc[ut] - if !ok { - return fe.Error() - } - - fn, ok := m[fe.tag] - if !ok { - return fe.Error() - } - - return fn(ut, fe) -} diff --git a/vendor/github.com/go-playground/validator/v10/field_level.go b/vendor/github.com/go-playground/validator/v10/field_level.go deleted file mode 100644 index ef35826..0000000 --- a/vendor/github.com/go-playground/validator/v10/field_level.go +++ /dev/null @@ -1,120 +0,0 @@ -package validator - -import "reflect" - -// FieldLevel contains all the information and helper functions -// to validate a field -type FieldLevel interface { - - // Top returns the top level struct, if any - Top() reflect.Value - - // Parent returns the current fields parent struct, if any or - // the comparison value if called 'VarWithValue' - Parent() reflect.Value - - // Field returns current field for validation - Field() reflect.Value - - // FieldName returns the field's name with the tag - // name taking precedence over the fields actual name. - FieldName() string - - // StructFieldName returns the struct field's name - StructFieldName() string - - // Param returns param for validation against current field - Param() string - - // GetTag returns the current validations tag name - GetTag() string - - // ExtractType gets the actual underlying type of field value. - // It will dive into pointers, customTypes and return you the - // underlying value and it's kind. - ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) - - // GetStructFieldOK traverses the parent struct to retrieve a specific field denoted by the provided namespace - // in the param and returns the field, field kind and whether is was successful in retrieving - // the field at all. - // - // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field - // could not be retrieved because it didn't exist. - // - // Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. - GetStructFieldOK() (reflect.Value, reflect.Kind, bool) - - // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for - // the field and namespace allowing more extensibility for validators. - // - // Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. - GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) - - // GetStructFieldOK2 traverses the parent struct to retrieve a specific field denoted by the provided namespace - // in the param and returns the field, field kind, if it's a nullable type and whether is was successful in retrieving - // the field at all. - // - // NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field - // could not be retrieved because it didn't exist. - GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) - - // GetStructFieldOKAdvanced2 is the same as GetStructFieldOK except that it accepts the parent struct to start looking for - // the field and namespace allowing more extensibility for validators. - GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) -} - -var _ FieldLevel = new(validate) - -// Field returns current field for validation -func (v *validate) Field() reflect.Value { - return v.flField -} - -// FieldName returns the field's name with the tag -// name taking precedence over the fields actual name. -func (v *validate) FieldName() string { - return v.cf.altName -} - -// GetTag returns the current validations tag name -func (v *validate) GetTag() string { - return v.ct.tag -} - -// StructFieldName returns the struct field's name -func (v *validate) StructFieldName() string { - return v.cf.name -} - -// Param returns param for validation against current field -func (v *validate) Param() string { - return v.ct.param -} - -// GetStructFieldOK returns Param returns param for validation against current field -// -// Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable. -func (v *validate) GetStructFieldOK() (reflect.Value, reflect.Kind, bool) { - current, kind, _, found := v.getStructFieldOKInternal(v.slflParent, v.ct.param) - return current, kind, found -} - -// GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the parent struct to start looking for -// the field and namespace allowing more extensibility for validators. -// -// Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable. -func (v *validate) GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool) { - current, kind, _, found := v.GetStructFieldOKAdvanced2(val, namespace) - return current, kind, found -} - -// GetStructFieldOK2 returns Param returns param for validation against current field -func (v *validate) GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool) { - return v.getStructFieldOKInternal(v.slflParent, v.ct.param) -} - -// GetStructFieldOKAdvanced2 is the same as GetStructFieldOK except that it accepts the parent struct to start looking for -// the field and namespace allowing more extensibility for validators. -func (v *validate) GetStructFieldOKAdvanced2(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) { - return v.getStructFieldOKInternal(val, namespace) -} diff --git a/vendor/github.com/go-playground/validator/v10/logo.png b/vendor/github.com/go-playground/validator/v10/logo.png deleted file mode 100644 index 355000f..0000000 Binary files a/vendor/github.com/go-playground/validator/v10/logo.png and /dev/null differ diff --git a/vendor/github.com/go-playground/validator/v10/postcode_regexes.go b/vendor/github.com/go-playground/validator/v10/postcode_regexes.go deleted file mode 100644 index e7e7b68..0000000 --- a/vendor/github.com/go-playground/validator/v10/postcode_regexes.go +++ /dev/null @@ -1,173 +0,0 @@ -package validator - -import "regexp" - -var postCodePatternDict = map[string]string{ - "GB": `^GIR[ ]?0AA|((AB|AL|B|BA|BB|BD|BH|BL|BN|BR|BS|BT|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}))|BFPO[ ]?\d{1,4}$`, - "JE": `^JE\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`, - "GG": `^GY\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`, - "IM": `^IM\d[\dA-Z]?[ ]?\d[ABD-HJLN-UW-Z]{2}$`, - "US": `^\d{5}([ \-]\d{4})?$`, - "CA": `^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ ]?\d[ABCEGHJ-NPRSTV-Z]\d$`, - "DE": `^\d{5}$`, - "JP": `^\d{3}-\d{4}$`, - "FR": `^\d{2}[ ]?\d{3}$`, - "AU": `^\d{4}$`, - "IT": `^\d{5}$`, - "CH": `^\d{4}$`, - "AT": `^\d{4}$`, - "ES": `^\d{5}$`, - "NL": `^\d{4}[ ]?[A-Z]{2}$`, - "BE": `^\d{4}$`, - "DK": `^\d{4}$`, - "SE": `^\d{3}[ ]?\d{2}$`, - "NO": `^\d{4}$`, - "BR": `^\d{5}[\-]?\d{3}$`, - "PT": `^\d{4}([\-]\d{3})?$`, - "FI": `^\d{5}$`, - "AX": `^22\d{3}$`, - "KR": `^\d{3}[\-]\d{3}$`, - "CN": `^\d{6}$`, - "TW": `^\d{3}(\d{2})?$`, - "SG": `^\d{6}$`, - "DZ": `^\d{5}$`, - "AD": `^AD\d{3}$`, - "AR": `^([A-HJ-NP-Z])?\d{4}([A-Z]{3})?$`, - "AM": `^(37)?\d{4}$`, - "AZ": `^\d{4}$`, - "BH": `^((1[0-2]|[2-9])\d{2})?$`, - "BD": `^\d{4}$`, - "BB": `^(BB\d{5})?$`, - "BY": `^\d{6}$`, - "BM": `^[A-Z]{2}[ ]?[A-Z0-9]{2}$`, - "BA": `^\d{5}$`, - "IO": `^BBND 1ZZ$`, - "BN": `^[A-Z]{2}[ ]?\d{4}$`, - "BG": `^\d{4}$`, - "KH": `^\d{5}$`, - "CV": `^\d{4}$`, - "CL": `^\d{7}$`, - "CR": `^\d{4,5}|\d{3}-\d{4}$`, - "HR": `^\d{5}$`, - "CY": `^\d{4}$`, - "CZ": `^\d{3}[ ]?\d{2}$`, - "DO": `^\d{5}$`, - "EC": `^([A-Z]\d{4}[A-Z]|(?:[A-Z]{2})?\d{6})?$`, - "EG": `^\d{5}$`, - "EE": `^\d{5}$`, - "FO": `^\d{3}$`, - "GE": `^\d{4}$`, - "GR": `^\d{3}[ ]?\d{2}$`, - "GL": `^39\d{2}$`, - "GT": `^\d{5}$`, - "HT": `^\d{4}$`, - "HN": `^(?:\d{5})?$`, - "HU": `^\d{4}$`, - "IS": `^\d{3}$`, - "IN": `^\d{6}$`, - "ID": `^\d{5}$`, - "IL": `^\d{5}$`, - "JO": `^\d{5}$`, - "KZ": `^\d{6}$`, - "KE": `^\d{5}$`, - "KW": `^\d{5}$`, - "LA": `^\d{5}$`, - "LV": `^\d{4}$`, - "LB": `^(\d{4}([ ]?\d{4})?)?$`, - "LI": `^(948[5-9])|(949[0-7])$`, - "LT": `^\d{5}$`, - "LU": `^\d{4}$`, - "MK": `^\d{4}$`, - "MY": `^\d{5}$`, - "MV": `^\d{5}$`, - "MT": `^[A-Z]{3}[ ]?\d{2,4}$`, - "MU": `^(\d{3}[A-Z]{2}\d{3})?$`, - "MX": `^\d{5}$`, - "MD": `^\d{4}$`, - "MC": `^980\d{2}$`, - "MA": `^\d{5}$`, - "NP": `^\d{5}$`, - "NZ": `^\d{4}$`, - "NI": `^((\d{4}-)?\d{3}-\d{3}(-\d{1})?)?$`, - "NG": `^(\d{6})?$`, - "OM": `^(PC )?\d{3}$`, - "PK": `^\d{5}$`, - "PY": `^\d{4}$`, - "PH": `^\d{4}$`, - "PL": `^\d{2}-\d{3}$`, - "PR": `^00[679]\d{2}([ \-]\d{4})?$`, - "RO": `^\d{6}$`, - "RU": `^\d{6}$`, - "SM": `^4789\d$`, - "SA": `^\d{5}$`, - "SN": `^\d{5}$`, - "SK": `^\d{3}[ ]?\d{2}$`, - "SI": `^\d{4}$`, - "ZA": `^\d{4}$`, - "LK": `^\d{5}$`, - "TJ": `^\d{6}$`, - "TH": `^\d{5}$`, - "TN": `^\d{4}$`, - "TR": `^\d{5}$`, - "TM": `^\d{6}$`, - "UA": `^\d{5}$`, - "UY": `^\d{5}$`, - "UZ": `^\d{6}$`, - "VA": `^00120$`, - "VE": `^\d{4}$`, - "ZM": `^\d{5}$`, - "AS": `^96799$`, - "CC": `^6799$`, - "CK": `^\d{4}$`, - "RS": `^\d{6}$`, - "ME": `^8\d{4}$`, - "CS": `^\d{5}$`, - "YU": `^\d{5}$`, - "CX": `^6798$`, - "ET": `^\d{4}$`, - "FK": `^FIQQ 1ZZ$`, - "NF": `^2899$`, - "FM": `^(9694[1-4])([ \-]\d{4})?$`, - "GF": `^9[78]3\d{2}$`, - "GN": `^\d{3}$`, - "GP": `^9[78][01]\d{2}$`, - "GS": `^SIQQ 1ZZ$`, - "GU": `^969[123]\d([ \-]\d{4})?$`, - "GW": `^\d{4}$`, - "HM": `^\d{4}$`, - "IQ": `^\d{5}$`, - "KG": `^\d{6}$`, - "LR": `^\d{4}$`, - "LS": `^\d{3}$`, - "MG": `^\d{3}$`, - "MH": `^969[67]\d([ \-]\d{4})?$`, - "MN": `^\d{6}$`, - "MP": `^9695[012]([ \-]\d{4})?$`, - "MQ": `^9[78]2\d{2}$`, - "NC": `^988\d{2}$`, - "NE": `^\d{4}$`, - "VI": `^008(([0-4]\d)|(5[01]))([ \-]\d{4})?$`, - "VN": `^[0-9]{1,6}$`, - "PF": `^987\d{2}$`, - "PG": `^\d{3}$`, - "PM": `^9[78]5\d{2}$`, - "PN": `^PCRN 1ZZ$`, - "PW": `^96940$`, - "RE": `^9[78]4\d{2}$`, - "SH": `^(ASCN|STHL) 1ZZ$`, - "SJ": `^\d{4}$`, - "SO": `^\d{5}$`, - "SZ": `^[HLMS]\d{3}$`, - "TC": `^TKCA 1ZZ$`, - "WF": `^986\d{2}$`, - "XK": `^\d{5}$`, - "YT": `^976\d{2}$`, -} - -var postCodeRegexDict = map[string]*regexp.Regexp{} - -func init() { - for countryCode, pattern := range postCodePatternDict { - postCodeRegexDict[countryCode] = regexp.MustCompile(pattern) - } -} diff --git a/vendor/github.com/go-playground/validator/v10/regexes.go b/vendor/github.com/go-playground/validator/v10/regexes.go deleted file mode 100644 index 9c1c634..0000000 --- a/vendor/github.com/go-playground/validator/v10/regexes.go +++ /dev/null @@ -1,131 +0,0 @@ -package validator - -import "regexp" - -const ( - alphaRegexString = "^[a-zA-Z]+$" - alphaNumericRegexString = "^[a-zA-Z0-9]+$" - alphaUnicodeRegexString = "^[\\p{L}]+$" - alphaUnicodeNumericRegexString = "^[\\p{L}\\p{N}]+$" - numericRegexString = "^[-+]?[0-9]+(?:\\.[0-9]+)?$" - numberRegexString = "^[0-9]+$" - hexadecimalRegexString = "^(0[xX])?[0-9a-fA-F]+$" - hexColorRegexString = "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$" - rgbRegexString = "^rgb\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%)\\s*\\)$" - rgbaRegexString = "^rgba\\(\\s*(?:(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])|(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%\\s*,\\s*(?:0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$" - hslRegexString = "^hsl\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*\\)$" - hslaRegexString = "^hsla\\(\\s*(?:0|[1-9]\\d?|[12]\\d\\d|3[0-5]\\d|360)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0|[1-9]\\d?|100)%)\\s*,\\s*(?:(?:0.[1-9]*)|[01])\\s*\\)$" - emailRegexString = "^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$" - e164RegexString = "^\\+[1-9]?[0-9]{7,14}$" - base64RegexString = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" - base64URLRegexString = "^(?:[A-Za-z0-9-_]{4})*(?:[A-Za-z0-9-_]{2}==|[A-Za-z0-9-_]{3}=|[A-Za-z0-9-_]{4})$" - iSBN10RegexString = "^(?:[0-9]{9}X|[0-9]{10})$" - iSBN13RegexString = "^(?:(?:97(?:8|9))[0-9]{10})$" - uUID3RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" - uUID4RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - uUID5RegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" - uUIDRegexString = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" - uUID3RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-3[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - uUID4RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" - uUID5RFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-5[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$" - uUIDRFC4122RegexString = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" - uLIDRegexString = "^[A-HJKMNP-TV-Z0-9]{26}$" - md4RegexString = "^[0-9a-f]{32}$" - md5RegexString = "^[0-9a-f]{32}$" - sha256RegexString = "^[0-9a-f]{64}$" - sha384RegexString = "^[0-9a-f]{96}$" - sha512RegexString = "^[0-9a-f]{128}$" - ripemd128RegexString = "^[0-9a-f]{32}$" - ripemd160RegexString = "^[0-9a-f]{40}$" - tiger128RegexString = "^[0-9a-f]{32}$" - tiger160RegexString = "^[0-9a-f]{40}$" - tiger192RegexString = "^[0-9a-f]{48}$" - aSCIIRegexString = "^[\x00-\x7F]*$" - printableASCIIRegexString = "^[\x20-\x7E]*$" - multibyteRegexString = "[^\x00-\x7F]" - dataURIRegexString = `^data:((?:\w+\/(?:([^;]|;[^;]).)+)?)` - latitudeRegexString = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" - longitudeRegexString = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" - sSNRegexString = `^[0-9]{3}[ -]?(0[1-9]|[1-9][0-9])[ -]?([1-9][0-9]{3}|[0-9][1-9][0-9]{2}|[0-9]{2}[1-9][0-9]|[0-9]{3}[1-9])$` - hostnameRegexStringRFC952 = `^[a-zA-Z]([a-zA-Z0-9\-]+[\.]?)*[a-zA-Z0-9]$` // https://tools.ietf.org/html/rfc952 - hostnameRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62}){1}(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?$` // accepts hostname starting with a digit https://tools.ietf.org/html/rfc1123 - fqdnRegexStringRFC1123 = `^([a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]{1}[a-zA-Z0-9-]{0,62})*?(\.[a-zA-Z]{1}[a-zA-Z0-9]{0,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.') - btcAddressRegexString = `^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$` // bitcoin address - btcAddressUpperRegexStringBech32 = `^BC1[02-9AC-HJ-NP-Z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 - btcAddressLowerRegexStringBech32 = `^bc1[02-9ac-hj-np-z]{7,76}$` // bitcoin bech32 address https://en.bitcoin.it/wiki/Bech32 - ethAddressRegexString = `^0x[0-9a-fA-F]{40}$` - ethAddressUpperRegexString = `^0x[0-9A-F]{40}$` - ethAddressLowerRegexString = `^0x[0-9a-f]{40}$` - uRLEncodedRegexString = `^(?:[^%]|%[0-9A-Fa-f]{2})*$` - hTMLEncodedRegexString = `&#[x]?([0-9a-fA-F]{2})|(>)|(<)|(")|(&)+[;]?` - hTMLRegexString = `<[/]?([a-zA-Z]+).*?>` - jWTRegexString = "^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$" - splitParamsRegexString = `'[^']*'|\S+` - bicRegexString = `^[A-Za-z]{6}[A-Za-z0-9]{2}([A-Za-z0-9]{3})?$` - semverRegexString = `^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$` // numbered capture groups https://semver.org/ - dnsRegexStringRFC1035Label = "^[a-z]([-a-z0-9]*[a-z0-9]){0,62}$" -) - -var ( - alphaRegex = regexp.MustCompile(alphaRegexString) - alphaNumericRegex = regexp.MustCompile(alphaNumericRegexString) - alphaUnicodeRegex = regexp.MustCompile(alphaUnicodeRegexString) - alphaUnicodeNumericRegex = regexp.MustCompile(alphaUnicodeNumericRegexString) - numericRegex = regexp.MustCompile(numericRegexString) - numberRegex = regexp.MustCompile(numberRegexString) - hexadecimalRegex = regexp.MustCompile(hexadecimalRegexString) - hexColorRegex = regexp.MustCompile(hexColorRegexString) - rgbRegex = regexp.MustCompile(rgbRegexString) - rgbaRegex = regexp.MustCompile(rgbaRegexString) - hslRegex = regexp.MustCompile(hslRegexString) - hslaRegex = regexp.MustCompile(hslaRegexString) - e164Regex = regexp.MustCompile(e164RegexString) - emailRegex = regexp.MustCompile(emailRegexString) - base64Regex = regexp.MustCompile(base64RegexString) - base64URLRegex = regexp.MustCompile(base64URLRegexString) - iSBN10Regex = regexp.MustCompile(iSBN10RegexString) - iSBN13Regex = regexp.MustCompile(iSBN13RegexString) - uUID3Regex = regexp.MustCompile(uUID3RegexString) - uUID4Regex = regexp.MustCompile(uUID4RegexString) - uUID5Regex = regexp.MustCompile(uUID5RegexString) - uUIDRegex = regexp.MustCompile(uUIDRegexString) - uUID3RFC4122Regex = regexp.MustCompile(uUID3RFC4122RegexString) - uUID4RFC4122Regex = regexp.MustCompile(uUID4RFC4122RegexString) - uUID5RFC4122Regex = regexp.MustCompile(uUID5RFC4122RegexString) - uUIDRFC4122Regex = regexp.MustCompile(uUIDRFC4122RegexString) - uLIDRegex = regexp.MustCompile(uLIDRegexString) - md4Regex = regexp.MustCompile(md4RegexString) - md5Regex = regexp.MustCompile(md5RegexString) - sha256Regex = regexp.MustCompile(sha256RegexString) - sha384Regex = regexp.MustCompile(sha384RegexString) - sha512Regex = regexp.MustCompile(sha512RegexString) - ripemd128Regex = regexp.MustCompile(ripemd128RegexString) - ripemd160Regex = regexp.MustCompile(ripemd160RegexString) - tiger128Regex = regexp.MustCompile(tiger128RegexString) - tiger160Regex = regexp.MustCompile(tiger160RegexString) - tiger192Regex = regexp.MustCompile(tiger192RegexString) - aSCIIRegex = regexp.MustCompile(aSCIIRegexString) - printableASCIIRegex = regexp.MustCompile(printableASCIIRegexString) - multibyteRegex = regexp.MustCompile(multibyteRegexString) - dataURIRegex = regexp.MustCompile(dataURIRegexString) - latitudeRegex = regexp.MustCompile(latitudeRegexString) - longitudeRegex = regexp.MustCompile(longitudeRegexString) - sSNRegex = regexp.MustCompile(sSNRegexString) - hostnameRegexRFC952 = regexp.MustCompile(hostnameRegexStringRFC952) - hostnameRegexRFC1123 = regexp.MustCompile(hostnameRegexStringRFC1123) - fqdnRegexRFC1123 = regexp.MustCompile(fqdnRegexStringRFC1123) - btcAddressRegex = regexp.MustCompile(btcAddressRegexString) - btcUpperAddressRegexBech32 = regexp.MustCompile(btcAddressUpperRegexStringBech32) - btcLowerAddressRegexBech32 = regexp.MustCompile(btcAddressLowerRegexStringBech32) - ethAddressRegex = regexp.MustCompile(ethAddressRegexString) - ethAddressRegexUpper = regexp.MustCompile(ethAddressUpperRegexString) - ethAddressRegexLower = regexp.MustCompile(ethAddressLowerRegexString) - uRLEncodedRegex = regexp.MustCompile(uRLEncodedRegexString) - hTMLEncodedRegex = regexp.MustCompile(hTMLEncodedRegexString) - hTMLRegex = regexp.MustCompile(hTMLRegexString) - jWTRegex = regexp.MustCompile(jWTRegexString) - splitParamsRegex = regexp.MustCompile(splitParamsRegexString) - bicRegex = regexp.MustCompile(bicRegexString) - semverRegex = regexp.MustCompile(semverRegexString) - dnsRegexRFC1035Label = regexp.MustCompile(dnsRegexStringRFC1035Label) -) diff --git a/vendor/github.com/go-playground/validator/v10/struct_level.go b/vendor/github.com/go-playground/validator/v10/struct_level.go deleted file mode 100644 index c0d89cf..0000000 --- a/vendor/github.com/go-playground/validator/v10/struct_level.go +++ /dev/null @@ -1,175 +0,0 @@ -package validator - -import ( - "context" - "reflect" -) - -// StructLevelFunc accepts all values needed for struct level validation -type StructLevelFunc func(sl StructLevel) - -// StructLevelFuncCtx accepts all values needed for struct level validation -// but also allows passing of contextual validation information via context.Context. -type StructLevelFuncCtx func(ctx context.Context, sl StructLevel) - -// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx -func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx { - return func(ctx context.Context, sl StructLevel) { - fn(sl) - } -} - -// StructLevel contains all the information and helper functions -// to validate a struct -type StructLevel interface { - - // Validator returns the main validation object, in case one wants to call validations internally. - // this is so you don't have to use anonymous functions to get access to the validate - // instance. - Validator() *Validate - - // Top returns the top level struct, if any - Top() reflect.Value - - // Parent returns the current fields parent struct, if any - Parent() reflect.Value - - // Current returns the current struct. - Current() reflect.Value - - // ExtractType gets the actual underlying type of field value. - // It will dive into pointers, customTypes and return you the - // underlying value and its kind. - ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) - - // ReportError reports an error just by passing the field and tag information - // - // NOTES: - // - // fieldName and altName get appended to the existing namespace that - // validator is on. e.g. pass 'FirstName' or 'Names[0]' depending - // on the nesting - // - // tag can be an existing validation tag or just something you make up - // and process on the flip side it's up to you. - ReportError(field interface{}, fieldName, structFieldName string, tag, param string) - - // ReportValidationErrors reports an error just by passing ValidationErrors - // - // NOTES: - // - // relativeNamespace and relativeActualNamespace get appended to the - // existing namespace that validator is on. - // e.g. pass 'User.FirstName' or 'Users[0].FirstName' depending - // on the nesting. most of the time they will be blank, unless you validate - // at a level lower the the current field depth - ReportValidationErrors(relativeNamespace, relativeActualNamespace string, errs ValidationErrors) -} - -var _ StructLevel = new(validate) - -// Top returns the top level struct -// -// NOTE: this can be the same as the current struct being validated -// if not is a nested struct. -// -// this is only called when within Struct and Field Level validation and -// should not be relied upon for an acurate value otherwise. -func (v *validate) Top() reflect.Value { - return v.top -} - -// Parent returns the current structs parent -// -// NOTE: this can be the same as the current struct being validated -// if not is a nested struct. -// -// this is only called when within Struct and Field Level validation and -// should not be relied upon for an acurate value otherwise. -func (v *validate) Parent() reflect.Value { - return v.slflParent -} - -// Current returns the current struct. -func (v *validate) Current() reflect.Value { - return v.slCurrent -} - -// Validator returns the main validation object, in case one want to call validations internally. -func (v *validate) Validator() *Validate { - return v.v -} - -// ExtractType gets the actual underlying type of field value. -func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) { - return v.extractTypeInternal(field, false) -} - -// ReportError reports an error just by passing the field and tag information -func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { - - fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) - - if len(structFieldName) == 0 { - structFieldName = fieldName - } - - v.str1 = string(append(v.ns, fieldName...)) - - if v.v.hasTagNameFunc || fieldName != structFieldName { - v.str2 = string(append(v.actualNs, structFieldName...)) - } else { - v.str2 = v.str1 - } - - if kind == reflect.Invalid { - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tag, - actualTag: tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(fieldName)), - structfieldLen: uint8(len(structFieldName)), - param: param, - kind: kind, - }, - ) - return - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tag, - actualTag: tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(fieldName)), - structfieldLen: uint8(len(structFieldName)), - value: fv.Interface(), - param: param, - kind: kind, - typ: fv.Type(), - }, - ) -} - -// ReportValidationErrors reports ValidationErrors obtained from running validations within the Struct Level validation. -// -// NOTE: this function prepends the current namespace to the relative ones. -func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors) { - - var err *fieldError - - for i := 0; i < len(errs); i++ { - - err = errs[i].(*fieldError) - err.ns = string(append(append(v.ns, relativeNamespace...), err.ns...)) - err.structNs = string(append(append(v.actualNs, relativeStructNamespace...), err.structNs...)) - - v.errs = append(v.errs, err) - } -} diff --git a/vendor/github.com/go-playground/validator/v10/translations.go b/vendor/github.com/go-playground/validator/v10/translations.go deleted file mode 100644 index 4d9d75c..0000000 --- a/vendor/github.com/go-playground/validator/v10/translations.go +++ /dev/null @@ -1,11 +0,0 @@ -package validator - -import ut "github.com/go-playground/universal-translator" - -// TranslationFunc is the function type used to register or override -// custom translations -type TranslationFunc func(ut ut.Translator, fe FieldError) string - -// RegisterTranslationsFunc allows for registering of translations -// for a 'ut.Translator' for use within the 'TranslationFunc' -type RegisterTranslationsFunc func(ut ut.Translator) error diff --git a/vendor/github.com/go-playground/validator/v10/util.go b/vendor/github.com/go-playground/validator/v10/util.go deleted file mode 100644 index 36da855..0000000 --- a/vendor/github.com/go-playground/validator/v10/util.go +++ /dev/null @@ -1,288 +0,0 @@ -package validator - -import ( - "reflect" - "strconv" - "strings" - "time" -) - -// extractTypeInternal gets the actual underlying type of field value. -// It will dive into pointers, customTypes and return you the -// underlying value and it's kind. -func (v *validate) extractTypeInternal(current reflect.Value, nullable bool) (reflect.Value, reflect.Kind, bool) { - -BEGIN: - switch current.Kind() { - case reflect.Ptr: - - nullable = true - - if current.IsNil() { - return current, reflect.Ptr, nullable - } - - current = current.Elem() - goto BEGIN - - case reflect.Interface: - - nullable = true - - if current.IsNil() { - return current, reflect.Interface, nullable - } - - current = current.Elem() - goto BEGIN - - case reflect.Invalid: - return current, reflect.Invalid, nullable - - default: - - if v.v.hasCustomFuncs { - - if fn, ok := v.v.customFuncs[current.Type()]; ok { - current = reflect.ValueOf(fn(current)) - goto BEGIN - } - } - - return current, current.Kind(), nullable - } -} - -// getStructFieldOKInternal traverses a struct to retrieve a specific field denoted by the provided namespace and -// returns the field, field kind and whether is was successful in retrieving the field at all. -// -// NOTE: when not successful ok will be false, this can happen when a nested struct is nil and so the field -// could not be retrieved because it didn't exist. -func (v *validate) getStructFieldOKInternal(val reflect.Value, namespace string) (current reflect.Value, kind reflect.Kind, nullable bool, found bool) { - -BEGIN: - current, kind, nullable = v.ExtractType(val) - if kind == reflect.Invalid { - return - } - - if namespace == "" { - found = true - return - } - - switch kind { - - case reflect.Ptr, reflect.Interface: - return - - case reflect.Struct: - - typ := current.Type() - fld := namespace - var ns string - - if !typ.ConvertibleTo(timeType) { - - idx := strings.Index(namespace, namespaceSeparator) - - if idx != -1 { - fld = namespace[:idx] - ns = namespace[idx+1:] - } else { - ns = "" - } - - bracketIdx := strings.Index(fld, leftBracket) - if bracketIdx != -1 { - fld = fld[:bracketIdx] - - ns = namespace[bracketIdx:] - } - - val = current.FieldByName(fld) - namespace = ns - goto BEGIN - } - - case reflect.Array, reflect.Slice: - idx := strings.Index(namespace, leftBracket) - idx2 := strings.Index(namespace, rightBracket) - - arrIdx, _ := strconv.Atoi(namespace[idx+1 : idx2]) - - if arrIdx >= current.Len() { - return - } - - startIdx := idx2 + 1 - - if startIdx < len(namespace) { - if namespace[startIdx:startIdx+1] == namespaceSeparator { - startIdx++ - } - } - - val = current.Index(arrIdx) - namespace = namespace[startIdx:] - goto BEGIN - - case reflect.Map: - idx := strings.Index(namespace, leftBracket) + 1 - idx2 := strings.Index(namespace, rightBracket) - - endIdx := idx2 - - if endIdx+1 < len(namespace) { - if namespace[endIdx+1:endIdx+2] == namespaceSeparator { - endIdx++ - } - } - - key := namespace[idx:idx2] - - switch current.Type().Key().Kind() { - case reflect.Int: - i, _ := strconv.Atoi(key) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Int8: - i, _ := strconv.ParseInt(key, 10, 8) - val = current.MapIndex(reflect.ValueOf(int8(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int16: - i, _ := strconv.ParseInt(key, 10, 16) - val = current.MapIndex(reflect.ValueOf(int16(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int32: - i, _ := strconv.ParseInt(key, 10, 32) - val = current.MapIndex(reflect.ValueOf(int32(i))) - namespace = namespace[endIdx+1:] - - case reflect.Int64: - i, _ := strconv.ParseInt(key, 10, 64) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Uint: - i, _ := strconv.ParseUint(key, 10, 0) - val = current.MapIndex(reflect.ValueOf(uint(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint8: - i, _ := strconv.ParseUint(key, 10, 8) - val = current.MapIndex(reflect.ValueOf(uint8(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint16: - i, _ := strconv.ParseUint(key, 10, 16) - val = current.MapIndex(reflect.ValueOf(uint16(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint32: - i, _ := strconv.ParseUint(key, 10, 32) - val = current.MapIndex(reflect.ValueOf(uint32(i))) - namespace = namespace[endIdx+1:] - - case reflect.Uint64: - i, _ := strconv.ParseUint(key, 10, 64) - val = current.MapIndex(reflect.ValueOf(i)) - namespace = namespace[endIdx+1:] - - case reflect.Float32: - f, _ := strconv.ParseFloat(key, 32) - val = current.MapIndex(reflect.ValueOf(float32(f))) - namespace = namespace[endIdx+1:] - - case reflect.Float64: - f, _ := strconv.ParseFloat(key, 64) - val = current.MapIndex(reflect.ValueOf(f)) - namespace = namespace[endIdx+1:] - - case reflect.Bool: - b, _ := strconv.ParseBool(key) - val = current.MapIndex(reflect.ValueOf(b)) - namespace = namespace[endIdx+1:] - - // reflect.Type = string - default: - val = current.MapIndex(reflect.ValueOf(key)) - namespace = namespace[endIdx+1:] - } - - goto BEGIN - } - - // if got here there was more namespace, cannot go any deeper - panic("Invalid field namespace") -} - -// asInt returns the parameter as a int64 -// or panics if it can't convert -func asInt(param string) int64 { - i, err := strconv.ParseInt(param, 0, 64) - panicIf(err) - - return i -} - -// asIntFromTimeDuration parses param as time.Duration and returns it as int64 -// or panics on error. -func asIntFromTimeDuration(param string) int64 { - d, err := time.ParseDuration(param) - if err != nil { - // attempt parsing as an an integer assuming nanosecond precision - return asInt(param) - } - return int64(d) -} - -// asIntFromType calls the proper function to parse param as int64, -// given a field's Type t. -func asIntFromType(t reflect.Type, param string) int64 { - switch t { - case timeDurationType: - return asIntFromTimeDuration(param) - default: - return asInt(param) - } -} - -// asUint returns the parameter as a uint64 -// or panics if it can't convert -func asUint(param string) uint64 { - - i, err := strconv.ParseUint(param, 0, 64) - panicIf(err) - - return i -} - -// asFloat returns the parameter as a float64 -// or panics if it can't convert -func asFloat(param string) float64 { - - i, err := strconv.ParseFloat(param, 64) - panicIf(err) - - return i -} - -// asBool returns the parameter as a bool -// or panics if it can't convert -func asBool(param string) bool { - - i, err := strconv.ParseBool(param) - panicIf(err) - - return i -} - -func panicIf(err error) { - if err != nil { - panic(err.Error()) - } -} diff --git a/vendor/github.com/go-playground/validator/v10/validator.go b/vendor/github.com/go-playground/validator/v10/validator.go deleted file mode 100644 index 80da095..0000000 --- a/vendor/github.com/go-playground/validator/v10/validator.go +++ /dev/null @@ -1,486 +0,0 @@ -package validator - -import ( - "context" - "fmt" - "reflect" - "strconv" -) - -// per validate construct -type validate struct { - v *Validate - top reflect.Value - ns []byte - actualNs []byte - errs ValidationErrors - includeExclude map[string]struct{} // reset only if StructPartial or StructExcept are called, no need otherwise - ffn FilterFunc - slflParent reflect.Value // StructLevel & FieldLevel - slCurrent reflect.Value // StructLevel & FieldLevel - flField reflect.Value // StructLevel & FieldLevel - cf *cField // StructLevel & FieldLevel - ct *cTag // StructLevel & FieldLevel - misc []byte // misc reusable - str1 string // misc reusable - str2 string // misc reusable - fldIsPointer bool // StructLevel & FieldLevel - isPartial bool - hasExcludes bool -} - -// parent and current will be the same the first run of validateStruct -func (v *validate) validateStruct(ctx context.Context, parent reflect.Value, current reflect.Value, typ reflect.Type, ns []byte, structNs []byte, ct *cTag) { - - cs, ok := v.v.structCache.Get(typ) - if !ok { - cs = v.v.extractStructCache(current, typ.Name()) - } - - if len(ns) == 0 && len(cs.name) != 0 { - - ns = append(ns, cs.name...) - ns = append(ns, '.') - - structNs = append(structNs, cs.name...) - structNs = append(structNs, '.') - } - - // ct is nil on top level struct, and structs as fields that have no tag info - // so if nil or if not nil and the structonly tag isn't present - if ct == nil || ct.typeof != typeStructOnly { - - var f *cField - - for i := 0; i < len(cs.fields); i++ { - - f = cs.fields[i] - - if v.isPartial { - - if v.ffn != nil { - // used with StructFiltered - if v.ffn(append(structNs, f.name...)) { - continue - } - - } else { - // used with StructPartial & StructExcept - _, ok = v.includeExclude[string(append(structNs, f.name...))] - - if (ok && v.hasExcludes) || (!ok && !v.hasExcludes) { - continue - } - } - } - - v.traverseField(ctx, current, current.Field(f.idx), ns, structNs, f, f.cTags) - } - } - - // check if any struct level validations, after all field validations already checked. - // first iteration will have no info about nostructlevel tag, and is checked prior to - // calling the next iteration of validateStruct called from traverseField. - if cs.fn != nil { - - v.slflParent = parent - v.slCurrent = current - v.ns = ns - v.actualNs = structNs - - cs.fn(ctx, v) - } -} - -// traverseField validates any field, be it a struct or single field, ensures it's validity and passes it along to be validated via it's tag options -func (v *validate) traverseField(ctx context.Context, parent reflect.Value, current reflect.Value, ns []byte, structNs []byte, cf *cField, ct *cTag) { - var typ reflect.Type - var kind reflect.Kind - - current, kind, v.fldIsPointer = v.extractTypeInternal(current, false) - - switch kind { - case reflect.Ptr, reflect.Interface, reflect.Invalid: - - if ct == nil { - return - } - - if ct.typeof == typeOmitEmpty || ct.typeof == typeIsDefault { - return - } - - if ct.hasTag { - if kind == reflect.Invalid { - v.str1 = string(append(ns, cf.altName...)) - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - param: ct.param, - kind: kind, - }, - ) - return - } - - v.str1 = string(append(ns, cf.altName...)) - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - if !ct.runValidationWhenNil { - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: current.Type(), - }, - ) - return - } - } - - case reflect.Struct: - - typ = current.Type() - - if !typ.ConvertibleTo(timeType) { - - if ct != nil { - - if ct.typeof == typeStructOnly { - goto CONTINUE - } else if ct.typeof == typeIsDefault { - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !ct.fn(ctx, v) { - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - return - } - } - - ct = ct.next - } - - if ct != nil && ct.typeof == typeNoStructLevel { - return - } - - CONTINUE: - // if len == 0 then validating using 'Var' or 'VarWithValue' - // Var - doesn't make much sense to do it that way, should call 'Struct', but no harm... - // VarWithField - this allows for validating against each field within the struct against a specific value - // pretty handy in certain situations - if len(cf.name) > 0 { - ns = append(append(ns, cf.altName...), '.') - structNs = append(append(structNs, cf.name...), '.') - } - - v.validateStruct(ctx, parent, current, typ, ns, structNs, ct) - return - } - } - - if ct == nil || !ct.hasTag { - return - } - - typ = current.Type() - -OUTER: - for { - if ct == nil { - return - } - - switch ct.typeof { - - case typeOmitEmpty: - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !hasValue(v) { - return - } - - ct = ct.next - continue - - case typeEndKeys: - return - - case typeDive: - - ct = ct.next - - // traverse slice or map here - // or panic ;) - switch kind { - case reflect.Slice, reflect.Array: - - var i64 int64 - reusableCF := &cField{} - - for i := 0; i < current.Len(); i++ { - - i64 = int64(i) - - v.misc = append(v.misc[0:0], cf.name...) - v.misc = append(v.misc, '[') - v.misc = strconv.AppendInt(v.misc, i64, 10) - v.misc = append(v.misc, ']') - - reusableCF.name = string(v.misc) - - if cf.namesEqual { - reusableCF.altName = reusableCF.name - } else { - - v.misc = append(v.misc[0:0], cf.altName...) - v.misc = append(v.misc, '[') - v.misc = strconv.AppendInt(v.misc, i64, 10) - v.misc = append(v.misc, ']') - - reusableCF.altName = string(v.misc) - } - v.traverseField(ctx, parent, current.Index(i), ns, structNs, reusableCF, ct) - } - - case reflect.Map: - - var pv string - reusableCF := &cField{} - - for _, key := range current.MapKeys() { - - pv = fmt.Sprintf("%v", key.Interface()) - - v.misc = append(v.misc[0:0], cf.name...) - v.misc = append(v.misc, '[') - v.misc = append(v.misc, pv...) - v.misc = append(v.misc, ']') - - reusableCF.name = string(v.misc) - - if cf.namesEqual { - reusableCF.altName = reusableCF.name - } else { - v.misc = append(v.misc[0:0], cf.altName...) - v.misc = append(v.misc, '[') - v.misc = append(v.misc, pv...) - v.misc = append(v.misc, ']') - - reusableCF.altName = string(v.misc) - } - - if ct != nil && ct.typeof == typeKeys && ct.keys != nil { - v.traverseField(ctx, parent, key, ns, structNs, reusableCF, ct.keys) - // can be nil when just keys being validated - if ct.next != nil { - v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct.next) - } - } else { - v.traverseField(ctx, parent, current.MapIndex(key), ns, structNs, reusableCF, ct) - } - } - - default: - // throw error, if not a slice or map then should not have gotten here - // bad dive tag - panic("dive error! can't dive on a non slice or map") - } - - return - - case typeOr: - - v.misc = v.misc[0:0] - - for { - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if ct.fn(ctx, v) { - if ct.isBlockEnd { - ct = ct.next - continue OUTER - } - - // drain rest of the 'or' values, then continue or leave - for { - - ct = ct.next - - if ct == nil { - return - } - - if ct.typeof != typeOr { - continue OUTER - } - - if ct.isBlockEnd { - ct = ct.next - continue OUTER - } - } - } - - v.misc = append(v.misc, '|') - v.misc = append(v.misc, ct.tag...) - - if ct.hasParam { - v.misc = append(v.misc, '=') - v.misc = append(v.misc, ct.param...) - } - - if ct.isBlockEnd || ct.next == nil { - // if we get here, no valid 'or' value and no more tags - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - if ct.hasAlias { - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.actualAliasTag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - - } else { - - tVal := string(v.misc)[1:] - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: tVal, - actualTag: tVal, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - } - - return - } - - ct = ct.next - } - - default: - - // set Field Level fields - v.slflParent = parent - v.flField = current - v.cf = cf - v.ct = ct - - if !ct.fn(ctx, v) { - - v.str1 = string(append(ns, cf.altName...)) - - if v.v.hasTagNameFunc { - v.str2 = string(append(structNs, cf.name...)) - } else { - v.str2 = v.str1 - } - - v.errs = append(v.errs, - &fieldError{ - v: v.v, - tag: ct.aliasTag, - actualTag: ct.tag, - ns: v.str1, - structNs: v.str2, - fieldLen: uint8(len(cf.altName)), - structfieldLen: uint8(len(cf.name)), - value: current.Interface(), - param: ct.param, - kind: kind, - typ: typ, - }, - ) - - return - } - ct = ct.next - } - } - -} diff --git a/vendor/github.com/go-playground/validator/v10/validator_instance.go b/vendor/github.com/go-playground/validator/v10/validator_instance.go deleted file mode 100644 index 9493da4..0000000 --- a/vendor/github.com/go-playground/validator/v10/validator_instance.go +++ /dev/null @@ -1,699 +0,0 @@ -package validator - -import ( - "context" - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" - - ut "github.com/go-playground/universal-translator" -) - -const ( - defaultTagName = "validate" - utf8HexComma = "0x2C" - utf8Pipe = "0x7C" - tagSeparator = "," - orSeparator = "|" - tagKeySeparator = "=" - structOnlyTag = "structonly" - noStructLevelTag = "nostructlevel" - omitempty = "omitempty" - isdefault = "isdefault" - requiredWithoutAllTag = "required_without_all" - requiredWithoutTag = "required_without" - requiredWithTag = "required_with" - requiredWithAllTag = "required_with_all" - requiredIfTag = "required_if" - requiredUnlessTag = "required_unless" - excludedWithoutAllTag = "excluded_without_all" - excludedWithoutTag = "excluded_without" - excludedWithTag = "excluded_with" - excludedWithAllTag = "excluded_with_all" - excludedIfTag = "excluded_if" - excludedUnlessTag = "excluded_unless" - skipValidationTag = "-" - diveTag = "dive" - keysTag = "keys" - endKeysTag = "endkeys" - requiredTag = "required" - namespaceSeparator = "." - leftBracket = "[" - rightBracket = "]" - restrictedTagChars = ".[],|=+()`~!@#$%^&*\\\"/?<>{}" - restrictedAliasErr = "Alias '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" - restrictedTagErr = "Tag '%s' either contains restricted characters or is the same as a restricted tag needed for normal operation" -) - -var ( - timeDurationType = reflect.TypeOf(time.Duration(0)) - timeType = reflect.TypeOf(time.Time{}) - - defaultCField = &cField{namesEqual: true} -) - -// FilterFunc is the type used to filter fields using -// StructFiltered(...) function. -// returning true results in the field being filtered/skiped from -// validation -type FilterFunc func(ns []byte) bool - -// CustomTypeFunc allows for overriding or adding custom field type handler functions -// field = field value of the type to return a value to be validated -// example Valuer from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29 -type CustomTypeFunc func(field reflect.Value) interface{} - -// TagNameFunc allows for adding of a custom tag name parser -type TagNameFunc func(field reflect.StructField) string - -type internalValidationFuncWrapper struct { - fn FuncCtx - runValidatinOnNil bool -} - -// Validate contains the validator settings and cache -type Validate struct { - tagName string - pool *sync.Pool - hasCustomFuncs bool - hasTagNameFunc bool - tagNameFunc TagNameFunc - structLevelFuncs map[reflect.Type]StructLevelFuncCtx - customFuncs map[reflect.Type]CustomTypeFunc - aliases map[string]string - validations map[string]internalValidationFuncWrapper - transTagFunc map[ut.Translator]map[string]TranslationFunc // map[]map[]TranslationFunc - rules map[reflect.Type]map[string]string - tagCache *tagCache - structCache *structCache -} - -// New returns a new instance of 'validate' with sane defaults. -// Validate is designed to be thread-safe and used as a singleton instance. -// It caches information about your struct and validations, -// in essence only parsing your validation tags once per struct type. -// Using multiple instances neglects the benefit of caching. -func New() *Validate { - - tc := new(tagCache) - tc.m.Store(make(map[string]*cTag)) - - sc := new(structCache) - sc.m.Store(make(map[reflect.Type]*cStruct)) - - v := &Validate{ - tagName: defaultTagName, - aliases: make(map[string]string, len(bakedInAliases)), - validations: make(map[string]internalValidationFuncWrapper, len(bakedInValidators)), - tagCache: tc, - structCache: sc, - } - - // must copy alias validators for separate validations to be used in each validator instance - for k, val := range bakedInAliases { - v.RegisterAlias(k, val) - } - - // must copy validators for separate validations to be used in each instance - for k, val := range bakedInValidators { - - switch k { - // these require that even if the value is nil that the validation should run, omitempty still overrides this behaviour - case requiredIfTag, requiredUnlessTag, requiredWithTag, requiredWithAllTag, requiredWithoutTag, requiredWithoutAllTag, - excludedIfTag, excludedUnlessTag, excludedWithTag, excludedWithAllTag, excludedWithoutTag, excludedWithoutAllTag: - _ = v.registerValidation(k, wrapFunc(val), true, true) - default: - // no need to error check here, baked in will always be valid - _ = v.registerValidation(k, wrapFunc(val), true, false) - } - } - - v.pool = &sync.Pool{ - New: func() interface{} { - return &validate{ - v: v, - ns: make([]byte, 0, 64), - actualNs: make([]byte, 0, 64), - misc: make([]byte, 32), - } - }, - } - - return v -} - -// SetTagName allows for changing of the default tag name of 'validate' -func (v *Validate) SetTagName(name string) { - v.tagName = name -} - -// ValidateMapCtx validates a map using a map of validation rules and allows passing of contextual -// validation validation information via context.Context. -func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{}, rules map[string]interface{}) map[string]interface{} { - errs := make(map[string]interface{}) - for field, rule := range rules { - if ruleObj, ok := rule.(map[string]interface{}); ok { - if dataObj, ok := data[field].(map[string]interface{}); ok { - err := v.ValidateMapCtx(ctx, dataObj, ruleObj) - if len(err) > 0 { - errs[field] = err - } - } else if dataObjs, ok := data[field].([]map[string]interface{}); ok { - for _, obj := range dataObjs { - err := v.ValidateMapCtx(ctx, obj, ruleObj) - if len(err) > 0 { - errs[field] = err - } - } - } else { - errs[field] = errors.New("The field: '" + field + "' is not a map to dive") - } - } else if ruleStr, ok := rule.(string); ok { - err := v.VarCtx(ctx, data[field], ruleStr) - if err != nil { - errs[field] = err - } - } - } - return errs -} - -// ValidateMap validates map data from a map of tags -func (v *Validate) ValidateMap(data map[string]interface{}, rules map[string]interface{}) map[string]interface{} { - return v.ValidateMapCtx(context.Background(), data, rules) -} - -// RegisterTagNameFunc registers a function to get alternate names for StructFields. -// -// eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names: -// -// validate.RegisterTagNameFunc(func(fld reflect.StructField) string { -// name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] -// // skip if tag key says it should be ignored -// if name == "-" { -// return "" -// } -// return name -// }) -func (v *Validate) RegisterTagNameFunc(fn TagNameFunc) { - v.tagNameFunc = fn - v.hasTagNameFunc = true -} - -// RegisterValidation adds a validation with the given tag -// -// NOTES: -// - if the key already exists, the previous validation function will be replaced. -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool) error { - return v.RegisterValidationCtx(tag, wrapFunc(fn), callValidationEvenIfNull...) -} - -// RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation -// allowing context.Context validation support. -func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull ...bool) error { - var nilCheckable bool - if len(callValidationEvenIfNull) > 0 { - nilCheckable = callValidationEvenIfNull[0] - } - return v.registerValidation(tag, fn, false, nilCheckable) -} - -func (v *Validate) registerValidation(tag string, fn FuncCtx, bakedIn bool, nilCheckable bool) error { - if len(tag) == 0 { - return errors.New("function Key cannot be empty") - } - - if fn == nil { - return errors.New("function cannot be empty") - } - - _, ok := restrictedTags[tag] - if !bakedIn && (ok || strings.ContainsAny(tag, restrictedTagChars)) { - panic(fmt.Sprintf(restrictedTagErr, tag)) - } - v.validations[tag] = internalValidationFuncWrapper{fn: fn, runValidatinOnNil: nilCheckable} - return nil -} - -// RegisterAlias registers a mapping of a single validation tag that -// defines a common or complex set of validation(s) to simplify adding validation -// to structs. -// -// NOTE: this function is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterAlias(alias, tags string) { - - _, ok := restrictedTags[alias] - - if ok || strings.ContainsAny(alias, restrictedTagChars) { - panic(fmt.Sprintf(restrictedAliasErr, alias)) - } - - v.aliases[alias] = tags -} - -// RegisterStructValidation registers a StructLevelFunc against a number of types. -// -// NOTE: -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{}) { - v.RegisterStructValidationCtx(wrapStructLevelFunc(fn), types...) -} - -// RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing -// of contextual validation information via context.Context. -// -// NOTE: -// - this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{}) { - - if v.structLevelFuncs == nil { - v.structLevelFuncs = make(map[reflect.Type]StructLevelFuncCtx) - } - - for _, t := range types { - tv := reflect.ValueOf(t) - if tv.Kind() == reflect.Ptr { - t = reflect.Indirect(tv).Interface() - } - - v.structLevelFuncs[reflect.TypeOf(t)] = fn - } -} - -// RegisterStructValidationMapRules registers validate map rules. -// Be aware that map validation rules supersede those defined on a/the struct if present. -// -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterStructValidationMapRules(rules map[string]string, types ...interface{}) { - if v.rules == nil { - v.rules = make(map[reflect.Type]map[string]string) - } - - deepCopyRules := make(map[string]string) - for i, rule := range rules { - deepCopyRules[i] = rule - } - - for _, t := range types { - typ := reflect.TypeOf(t) - - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - } - - if typ.Kind() != reflect.Struct { - continue - } - v.rules[typ] = deepCopyRules - } -} - -// RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types -// -// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation -func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{}) { - - if v.customFuncs == nil { - v.customFuncs = make(map[reflect.Type]CustomTypeFunc) - } - - for _, t := range types { - v.customFuncs[reflect.TypeOf(t)] = fn - } - - v.hasCustomFuncs = true -} - -// RegisterTranslation registers translations against the provided tag. -func (v *Validate) RegisterTranslation(tag string, trans ut.Translator, registerFn RegisterTranslationsFunc, translationFn TranslationFunc) (err error) { - - if v.transTagFunc == nil { - v.transTagFunc = make(map[ut.Translator]map[string]TranslationFunc) - } - - if err = registerFn(trans); err != nil { - return - } - - m, ok := v.transTagFunc[trans] - if !ok { - m = make(map[string]TranslationFunc) - v.transTagFunc[trans] = m - } - - m[tag] = translationFn - - return -} - -// Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) Struct(s interface{}) error { - return v.StructCtx(context.Background(), s) -} - -// StructCtx validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified -// and also allows passing of context.Context for contextual validation information. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error) { - - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type().ConvertibleTo(timeType) { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = false - // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept - - vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates -// nested structs, unless otherwise specified. -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error { - return v.StructFilteredCtx(context.Background(), s, fn) -} - -// StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates -// nested structs, unless otherwise specified and also allows passing of contextual validation information via -// context.Context -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type().ConvertibleTo(timeType) { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = fn - // vd.hasExcludes = false // only need to reset in StructPartial and StructExcept - - vd.validateStruct(ctx, top, val, val.Type(), vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructPartial validates the fields passed in only, ignoring all others. -// Fields may be provided in a namespaced fashion relative to the struct provided -// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructPartial(s interface{}, fields ...string) error { - return v.StructPartialCtx(context.Background(), s, fields...) -} - -// StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual -// validation validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided -// eg. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type().ConvertibleTo(timeType) { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = nil - vd.hasExcludes = false - vd.includeExclude = make(map[string]struct{}) - - typ := val.Type() - name := typ.Name() - - for _, k := range fields { - - flds := strings.Split(k, namespaceSeparator) - if len(flds) > 0 { - - vd.misc = append(vd.misc[0:0], name...) - // Don't append empty name for unnamed structs - if len(vd.misc) != 0 { - vd.misc = append(vd.misc, '.') - } - - for _, s := range flds { - - idx := strings.Index(s, leftBracket) - - if idx != -1 { - for idx != -1 { - vd.misc = append(vd.misc, s[:idx]...) - vd.includeExclude[string(vd.misc)] = struct{}{} - - idx2 := strings.Index(s, rightBracket) - idx2++ - vd.misc = append(vd.misc, s[idx:idx2]...) - vd.includeExclude[string(vd.misc)] = struct{}{} - s = s[idx2:] - idx = strings.Index(s, leftBracket) - } - } else { - - vd.misc = append(vd.misc, s...) - vd.includeExclude[string(vd.misc)] = struct{}{} - } - - vd.misc = append(vd.misc, '.') - } - } - } - - vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// StructExcept validates all fields except the ones passed in. -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructExcept(s interface{}, fields ...string) error { - return v.StructExceptCtx(context.Background(), s, fields...) -} - -// StructExceptCtx validates all fields except the ones passed in and allows passing of contextual -// validation validation information via context.Context -// Fields may be provided in a namespaced fashion relative to the struct provided -// i.e. NestedStruct.Field or NestedArrayField[0].Struct.Name -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error) { - val := reflect.ValueOf(s) - top := val - - if val.Kind() == reflect.Ptr && !val.IsNil() { - val = val.Elem() - } - - if val.Kind() != reflect.Struct || val.Type().ConvertibleTo(timeType) { - return &InvalidValidationError{Type: reflect.TypeOf(s)} - } - - // good to validate - vd := v.pool.Get().(*validate) - vd.top = top - vd.isPartial = true - vd.ffn = nil - vd.hasExcludes = true - vd.includeExclude = make(map[string]struct{}) - - typ := val.Type() - name := typ.Name() - - for _, key := range fields { - - vd.misc = vd.misc[0:0] - - if len(name) > 0 { - vd.misc = append(vd.misc, name...) - vd.misc = append(vd.misc, '.') - } - - vd.misc = append(vd.misc, key...) - vd.includeExclude[string(vd.misc)] = struct{}{} - } - - vd.validateStruct(ctx, top, val, typ, vd.ns[0:0], vd.actualNs[0:0], nil) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - - v.pool.Put(vd) - - return -} - -// Var validates a single variable using tag style validation. -// eg. -// var i int -// validate.Var(i, "gt=1,lt=10") -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) Var(field interface{}, tag string) error { - return v.VarCtx(context.Background(), field, tag) -} - -// VarCtx validates a single variable using tag style validation and allows passing of contextual -// validation validation information via context.Context. -// eg. -// var i int -// validate.Var(i, "gt=1,lt=10") -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (err error) { - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - - ctag := v.fetchCacheTag(tag) - val := reflect.ValueOf(field) - vd := v.pool.Get().(*validate) - vd.top = val - vd.isPartial = false - vd.traverseField(ctx, val, val, vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - v.pool.Put(vd) - return -} - -// VarWithValue validates a single variable, against another variable/field's value using tag style validation -// eg. -// s1 := "abcd" -// s2 := "abcd" -// validate.VarWithValue(s1, s2, "eqcsfield") // returns true -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error { - return v.VarWithValueCtx(context.Background(), field, other, tag) -} - -// VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and -// allows passing of contextual validation validation information via context.Context. -// eg. -// s1 := "abcd" -// s2 := "abcd" -// validate.VarWithValue(s1, s2, "eqcsfield") // returns true -// -// WARNING: a struct can be passed for validation eg. time.Time is a struct or -// if you have a custom type and have registered a custom type handler, so must -// allow it; however unforeseen validations will occur if trying to validate a -// struct that is meant to be passed to 'validate.Struct' -// -// It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. -// You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. -// validate Array, Slice and maps fields which may contain more than one error -func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error) { - if len(tag) == 0 || tag == skipValidationTag { - return nil - } - ctag := v.fetchCacheTag(tag) - otherVal := reflect.ValueOf(other) - vd := v.pool.Get().(*validate) - vd.top = otherVal - vd.isPartial = false - vd.traverseField(ctx, otherVal, reflect.ValueOf(field), vd.ns[0:0], vd.actualNs[0:0], defaultCField, ctag) - - if len(vd.errs) > 0 { - err = vd.errs - vd.errs = nil - } - v.pool.Put(vd) - return -} diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE deleted file mode 100644 index 5f920e9..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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 deleted file mode 100644 index 7a950d1..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# 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 deleted file mode 100644 index 06a91f0..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ /dev/null @@ -1,16 +0,0 @@ -//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 deleted file mode 100644 index 0c56880..0000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ /dev/null @@ -1,42 +0,0 @@ -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/leodido/go-urn/.gitignore b/vendor/github.com/leodido/go-urn/.gitignore deleted file mode 100644 index 5bcf4ba..0000000 --- a/vendor/github.com/leodido/go-urn/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -*.exe -*.dll -*.so -*.dylib - -*.test - -*.out -*.txt - -vendor/ \ No newline at end of file diff --git a/vendor/github.com/leodido/go-urn/.travis.yml b/vendor/github.com/leodido/go-urn/.travis.yml deleted file mode 100644 index 21f348d..0000000 --- a/vendor/github.com/leodido/go-urn/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: go - -go: - - 1.13.x - - 1.14.x - - 1.15.x - - tip - -before_install: - - go get -t -v ./... - -script: - - go test -race -coverprofile=coverage.txt -covermode=atomic - -after_success: - - bash <(curl -s https://codecov.io/bash) \ No newline at end of file diff --git a/vendor/github.com/leodido/go-urn/LICENSE b/vendor/github.com/leodido/go-urn/LICENSE deleted file mode 100644 index 8c3504a..0000000 --- a/vendor/github.com/leodido/go-urn/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Leonardo Di Donato - -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/leodido/go-urn/README.md b/vendor/github.com/leodido/go-urn/README.md deleted file mode 100644 index cc902ec..0000000 --- a/vendor/github.com/leodido/go-urn/README.md +++ /dev/null @@ -1,55 +0,0 @@ -[![Build](https://img.shields.io/travis/leodido/go-urn/master.svg?style=for-the-badge)](https://travis-ci.org/leodido/go-urn) [![Coverage](https://img.shields.io/codecov/c/github/leodido/go-urn.svg?style=for-the-badge)](https://codecov.io/gh/leodido/go-urn) [![Documentation](https://img.shields.io/badge/godoc-reference-blue.svg?style=for-the-badge)](https://godoc.org/github.com/leodido/go-urn) - -**A parser for URNs**. - -> As seen on [RFC 2141](https://tools.ietf.org/html/rfc2141#ref-1). - -[API documentation](https://godoc.org/github.com/leodido/go-urn). - -## Installation - -``` -go get github.com/leodido/go-urn -``` - -## Performances - -This implementation results to be really fast. - -Usually below ½ microsecond on my machine[1](#mymachine). - -Notice it also performs, while parsing: - -1. fine-grained and informative erroring -2. specific-string normalization - -``` -ok/00/urn:a:b______________________________________/-4 20000000 265 ns/op 182 B/op 6 allocs/op -ok/01/URN:foo:a123,456_____________________________/-4 30000000 296 ns/op 200 B/op 6 allocs/op -ok/02/urn:foo:a123%2c456___________________________/-4 20000000 331 ns/op 208 B/op 6 allocs/op -ok/03/urn:ietf:params:scim:schemas:core:2.0:User___/-4 20000000 430 ns/op 280 B/op 6 allocs/op -ok/04/urn:ietf:params:scim:schemas:extension:enterp/-4 20000000 411 ns/op 312 B/op 6 allocs/op -ok/05/urn:ietf:params:scim:schemas:extension:enterp/-4 20000000 472 ns/op 344 B/op 6 allocs/op -ok/06/urn:burnout:nss______________________________/-4 30000000 257 ns/op 192 B/op 6 allocs/op -ok/07/urn:abcdefghilmnopqrstuvzabcdefghilm:x_______/-4 20000000 375 ns/op 213 B/op 6 allocs/op -ok/08/urn:urnurnurn:urn____________________________/-4 30000000 265 ns/op 197 B/op 6 allocs/op -ok/09/urn:ciao:@!=%2c(xyz)+a,b.*@g=$_'_____________/-4 20000000 307 ns/op 248 B/op 6 allocs/op -ok/10/URN:x:abc%1dz%2f%3az_________________________/-4 30000000 259 ns/op 212 B/op 6 allocs/op -no/11/URN:-xxx:x___________________________________/-4 20000000 445 ns/op 320 B/op 6 allocs/op -no/12/urn::colon:nss_______________________________/-4 20000000 461 ns/op 320 B/op 6 allocs/op -no/13/urn:abcdefghilmnopqrstuvzabcdefghilmn:specifi/-4 10000000 660 ns/op 320 B/op 6 allocs/op -no/14/URN:a!?:x____________________________________/-4 20000000 507 ns/op 320 B/op 6 allocs/op -no/15/urn:urn:NSS__________________________________/-4 20000000 429 ns/op 288 B/op 6 allocs/op -no/16/urn:white_space:NSS__________________________/-4 20000000 482 ns/op 320 B/op 6 allocs/op -no/17/urn:concat:no_spaces_________________________/-4 20000000 539 ns/op 328 B/op 7 allocs/op -no/18/urn:a:/______________________________________/-4 20000000 470 ns/op 320 B/op 7 allocs/op -no/19/urn:UrN:NSS__________________________________/-4 20000000 399 ns/op 288 B/op 6 allocs/op -``` - ---- - -* [1]: Intel Core i7-7600U CPU @ 2.80GHz - ---- - -[![Analytics](https://ga-beacon.appspot.com/UA-49657176-1/go-urn?flat)](https://github.com/igrigorik/ga-beacon) \ No newline at end of file diff --git a/vendor/github.com/leodido/go-urn/machine.go b/vendor/github.com/leodido/go-urn/machine.go deleted file mode 100644 index fe5a0cc..0000000 --- a/vendor/github.com/leodido/go-urn/machine.go +++ /dev/null @@ -1,1691 +0,0 @@ -package urn - -import ( - "fmt" -) - -var ( - errPrefix = "expecting the prefix to be the \"urn\" string (whatever case) [col %d]" - errIdentifier = "expecting the identifier to be string (1..31 alnum chars, also containing dashes but not at its start) [col %d]" - errSpecificString = "expecting the specific string to be a string containing alnum, hex, or others ([()+,-.:=@;$_!*']) chars [col %d]" - errNoUrnWithinID = "expecting the identifier to not contain the \"urn\" reserved string [col %d]" - errHex = "expecting the specific string hex chars to be well-formed (%%alnum{2}) [col %d]" - errParse = "parsing error [col %d]" -) - -const start int = 1 -const firstFinal int = 44 - -const enFail int = 46 -const enMain int = 1 - -// Machine is the interface representing the FSM -type Machine interface { - Error() error - Parse(input []byte) (*URN, error) -} - -type machine struct { - data []byte - cs int - p, pe, eof, pb int - err error - tolower []int -} - -// NewMachine creates a new FSM able to parse RFC 2141 strings. -func NewMachine() Machine { - m := &machine{} - - return m -} - -// Err returns the error that occurred on the last call to Parse. -// -// If the result is nil, then the line was parsed successfully. -func (m *machine) Error() error { - return m.err -} - -func (m *machine) text() []byte { - return m.data[m.pb:m.p] -} - -// Parse parses the input byte array as a RFC 2141 string. -func (m *machine) Parse(input []byte) (*URN, error) { - m.data = input - m.p = 0 - m.pb = 0 - m.pe = len(input) - m.eof = len(input) - m.err = nil - m.tolower = []int{} - output := &URN{} - - { - m.cs = start - } - - { - if (m.p) == (m.pe) { - goto _testEof - } - switch m.cs { - case 1: - goto stCase1 - case 0: - goto stCase0 - case 2: - goto stCase2 - case 3: - goto stCase3 - case 4: - goto stCase4 - case 5: - goto stCase5 - case 6: - goto stCase6 - case 7: - goto stCase7 - case 8: - goto stCase8 - case 9: - goto stCase9 - case 10: - goto stCase10 - case 11: - goto stCase11 - case 12: - goto stCase12 - case 13: - goto stCase13 - case 14: - goto stCase14 - case 15: - goto stCase15 - case 16: - goto stCase16 - case 17: - goto stCase17 - case 18: - goto stCase18 - case 19: - goto stCase19 - case 20: - goto stCase20 - case 21: - goto stCase21 - case 22: - goto stCase22 - case 23: - goto stCase23 - case 24: - goto stCase24 - case 25: - goto stCase25 - case 26: - goto stCase26 - case 27: - goto stCase27 - case 28: - goto stCase28 - case 29: - goto stCase29 - case 30: - goto stCase30 - case 31: - goto stCase31 - case 32: - goto stCase32 - case 33: - goto stCase33 - case 34: - goto stCase34 - case 35: - goto stCase35 - case 36: - goto stCase36 - case 37: - goto stCase37 - case 38: - goto stCase38 - case 44: - goto stCase44 - case 39: - goto stCase39 - case 40: - goto stCase40 - case 45: - goto stCase45 - case 41: - goto stCase41 - case 42: - goto stCase42 - case 43: - goto stCase43 - case 46: - goto stCase46 - } - goto stOut - stCase1: - switch (m.data)[(m.p)] { - case 85: - goto tr1 - case 117: - goto tr1 - } - goto tr0 - tr0: - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - tr3: - - m.err = fmt.Errorf(errPrefix, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - tr6: - - m.err = fmt.Errorf(errIdentifier, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - tr41: - - m.err = fmt.Errorf(errSpecificString, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - tr44: - - m.err = fmt.Errorf(errHex, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errSpecificString, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - tr50: - - m.err = fmt.Errorf(errPrefix, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errIdentifier, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - tr52: - - m.err = fmt.Errorf(errNoUrnWithinID, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errIdentifier, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - goto st0 - stCase0: - st0: - m.cs = 0 - goto _out - tr1: - - m.pb = m.p - - goto st2 - st2: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof2 - } - stCase2: - switch (m.data)[(m.p)] { - case 82: - goto st3 - case 114: - goto st3 - } - goto tr0 - st3: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof3 - } - stCase3: - switch (m.data)[(m.p)] { - case 78: - goto st4 - case 110: - goto st4 - } - goto tr3 - st4: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof4 - } - stCase4: - if (m.data)[(m.p)] == 58 { - goto tr5 - } - goto tr0 - tr5: - - output.prefix = string(m.text()) - - goto st5 - st5: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof5 - } - stCase5: - switch (m.data)[(m.p)] { - case 85: - goto tr8 - case 117: - goto tr8 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto tr7 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto tr7 - } - default: - goto tr7 - } - goto tr6 - tr7: - - m.pb = m.p - - goto st6 - st6: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof6 - } - stCase6: - switch (m.data)[(m.p)] { - case 45: - goto st7 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st7 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st7 - } - default: - goto st7 - } - goto tr6 - st7: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof7 - } - stCase7: - switch (m.data)[(m.p)] { - case 45: - goto st8 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st8 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st8 - } - default: - goto st8 - } - goto tr6 - st8: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof8 - } - stCase8: - switch (m.data)[(m.p)] { - case 45: - goto st9 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st9 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st9 - } - default: - goto st9 - } - goto tr6 - st9: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof9 - } - stCase9: - switch (m.data)[(m.p)] { - case 45: - goto st10 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st10 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st10 - } - default: - goto st10 - } - goto tr6 - st10: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof10 - } - stCase10: - switch (m.data)[(m.p)] { - case 45: - goto st11 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st11 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st11 - } - default: - goto st11 - } - goto tr6 - st11: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof11 - } - stCase11: - switch (m.data)[(m.p)] { - case 45: - goto st12 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st12 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st12 - } - default: - goto st12 - } - goto tr6 - st12: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof12 - } - stCase12: - switch (m.data)[(m.p)] { - case 45: - goto st13 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st13 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st13 - } - default: - goto st13 - } - goto tr6 - st13: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof13 - } - stCase13: - switch (m.data)[(m.p)] { - case 45: - goto st14 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st14 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st14 - } - default: - goto st14 - } - goto tr6 - st14: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof14 - } - stCase14: - switch (m.data)[(m.p)] { - case 45: - goto st15 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st15 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st15 - } - default: - goto st15 - } - goto tr6 - st15: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof15 - } - stCase15: - switch (m.data)[(m.p)] { - case 45: - goto st16 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st16 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st16 - } - default: - goto st16 - } - goto tr6 - st16: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof16 - } - stCase16: - switch (m.data)[(m.p)] { - case 45: - goto st17 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st17 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st17 - } - default: - goto st17 - } - goto tr6 - st17: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof17 - } - stCase17: - switch (m.data)[(m.p)] { - case 45: - goto st18 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st18 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st18 - } - default: - goto st18 - } - goto tr6 - st18: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof18 - } - stCase18: - switch (m.data)[(m.p)] { - case 45: - goto st19 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st19 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st19 - } - default: - goto st19 - } - goto tr6 - st19: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof19 - } - stCase19: - switch (m.data)[(m.p)] { - case 45: - goto st20 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st20 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st20 - } - default: - goto st20 - } - goto tr6 - st20: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof20 - } - stCase20: - switch (m.data)[(m.p)] { - case 45: - goto st21 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st21 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st21 - } - default: - goto st21 - } - goto tr6 - st21: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof21 - } - stCase21: - switch (m.data)[(m.p)] { - case 45: - goto st22 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st22 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st22 - } - default: - goto st22 - } - goto tr6 - st22: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof22 - } - stCase22: - switch (m.data)[(m.p)] { - case 45: - goto st23 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st23 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st23 - } - default: - goto st23 - } - goto tr6 - st23: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof23 - } - stCase23: - switch (m.data)[(m.p)] { - case 45: - goto st24 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st24 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st24 - } - default: - goto st24 - } - goto tr6 - st24: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof24 - } - stCase24: - switch (m.data)[(m.p)] { - case 45: - goto st25 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st25 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st25 - } - default: - goto st25 - } - goto tr6 - st25: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof25 - } - stCase25: - switch (m.data)[(m.p)] { - case 45: - goto st26 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st26 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st26 - } - default: - goto st26 - } - goto tr6 - st26: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof26 - } - stCase26: - switch (m.data)[(m.p)] { - case 45: - goto st27 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st27 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st27 - } - default: - goto st27 - } - goto tr6 - st27: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof27 - } - stCase27: - switch (m.data)[(m.p)] { - case 45: - goto st28 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st28 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st28 - } - default: - goto st28 - } - goto tr6 - st28: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof28 - } - stCase28: - switch (m.data)[(m.p)] { - case 45: - goto st29 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st29 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st29 - } - default: - goto st29 - } - goto tr6 - st29: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof29 - } - stCase29: - switch (m.data)[(m.p)] { - case 45: - goto st30 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st30 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st30 - } - default: - goto st30 - } - goto tr6 - st30: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof30 - } - stCase30: - switch (m.data)[(m.p)] { - case 45: - goto st31 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st31 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st31 - } - default: - goto st31 - } - goto tr6 - st31: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof31 - } - stCase31: - switch (m.data)[(m.p)] { - case 45: - goto st32 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st32 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st32 - } - default: - goto st32 - } - goto tr6 - st32: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof32 - } - stCase32: - switch (m.data)[(m.p)] { - case 45: - goto st33 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st33 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st33 - } - default: - goto st33 - } - goto tr6 - st33: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof33 - } - stCase33: - switch (m.data)[(m.p)] { - case 45: - goto st34 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st34 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st34 - } - default: - goto st34 - } - goto tr6 - st34: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof34 - } - stCase34: - switch (m.data)[(m.p)] { - case 45: - goto st35 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st35 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st35 - } - default: - goto st35 - } - goto tr6 - st35: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof35 - } - stCase35: - switch (m.data)[(m.p)] { - case 45: - goto st36 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st36 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st36 - } - default: - goto st36 - } - goto tr6 - st36: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof36 - } - stCase36: - switch (m.data)[(m.p)] { - case 45: - goto st37 - case 58: - goto tr10 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st37 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st37 - } - default: - goto st37 - } - goto tr6 - st37: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof37 - } - stCase37: - if (m.data)[(m.p)] == 58 { - goto tr10 - } - goto tr6 - tr10: - - output.ID = string(m.text()) - - goto st38 - st38: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof38 - } - stCase38: - switch (m.data)[(m.p)] { - case 33: - goto tr42 - case 36: - goto tr42 - case 37: - goto tr43 - case 61: - goto tr42 - case 95: - goto tr42 - } - switch { - case (m.data)[(m.p)] < 48: - if 39 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 46 { - goto tr42 - } - case (m.data)[(m.p)] > 59: - switch { - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto tr42 - } - case (m.data)[(m.p)] >= 64: - goto tr42 - } - default: - goto tr42 - } - goto tr41 - tr42: - - m.pb = m.p - - goto st44 - st44: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof44 - } - stCase44: - switch (m.data)[(m.p)] { - case 33: - goto st44 - case 36: - goto st44 - case 37: - goto st39 - case 61: - goto st44 - case 95: - goto st44 - } - switch { - case (m.data)[(m.p)] < 48: - if 39 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 46 { - goto st44 - } - case (m.data)[(m.p)] > 59: - switch { - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st44 - } - case (m.data)[(m.p)] >= 64: - goto st44 - } - default: - goto st44 - } - goto tr41 - tr43: - - m.pb = m.p - - goto st39 - st39: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof39 - } - stCase39: - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st40 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st40 - } - default: - goto tr46 - } - goto tr44 - tr46: - - m.tolower = append(m.tolower, m.p-m.pb) - - goto st40 - st40: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof40 - } - stCase40: - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st45 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st45 - } - default: - goto tr48 - } - goto tr44 - tr48: - - m.tolower = append(m.tolower, m.p-m.pb) - - goto st45 - st45: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof45 - } - stCase45: - switch (m.data)[(m.p)] { - case 33: - goto st44 - case 36: - goto st44 - case 37: - goto st39 - case 61: - goto st44 - case 95: - goto st44 - } - switch { - case (m.data)[(m.p)] < 48: - if 39 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 46 { - goto st44 - } - case (m.data)[(m.p)] > 59: - switch { - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st44 - } - case (m.data)[(m.p)] >= 64: - goto st44 - } - default: - goto st44 - } - goto tr44 - tr8: - - m.pb = m.p - - goto st41 - st41: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof41 - } - stCase41: - switch (m.data)[(m.p)] { - case 45: - goto st7 - case 58: - goto tr10 - case 82: - goto st42 - case 114: - goto st42 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st7 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st7 - } - default: - goto st7 - } - goto tr6 - st42: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof42 - } - stCase42: - switch (m.data)[(m.p)] { - case 45: - goto st8 - case 58: - goto tr10 - case 78: - goto st43 - case 110: - goto st43 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st8 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st8 - } - default: - goto st8 - } - goto tr50 - st43: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof43 - } - stCase43: - if (m.data)[(m.p)] == 45 { - goto st9 - } - switch { - case (m.data)[(m.p)] < 65: - if 48 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 57 { - goto st9 - } - case (m.data)[(m.p)] > 90: - if 97 <= (m.data)[(m.p)] && (m.data)[(m.p)] <= 122 { - goto st9 - } - default: - goto st9 - } - goto tr52 - st46: - if (m.p)++; (m.p) == (m.pe) { - goto _testEof46 - } - stCase46: - switch (m.data)[(m.p)] { - case 10: - goto st0 - case 13: - goto st0 - } - goto st46 - stOut: - _testEof2: - m.cs = 2 - goto _testEof - _testEof3: - m.cs = 3 - goto _testEof - _testEof4: - m.cs = 4 - goto _testEof - _testEof5: - m.cs = 5 - goto _testEof - _testEof6: - m.cs = 6 - goto _testEof - _testEof7: - m.cs = 7 - goto _testEof - _testEof8: - m.cs = 8 - goto _testEof - _testEof9: - m.cs = 9 - goto _testEof - _testEof10: - m.cs = 10 - goto _testEof - _testEof11: - m.cs = 11 - goto _testEof - _testEof12: - m.cs = 12 - goto _testEof - _testEof13: - m.cs = 13 - goto _testEof - _testEof14: - m.cs = 14 - goto _testEof - _testEof15: - m.cs = 15 - goto _testEof - _testEof16: - m.cs = 16 - goto _testEof - _testEof17: - m.cs = 17 - goto _testEof - _testEof18: - m.cs = 18 - goto _testEof - _testEof19: - m.cs = 19 - goto _testEof - _testEof20: - m.cs = 20 - goto _testEof - _testEof21: - m.cs = 21 - goto _testEof - _testEof22: - m.cs = 22 - goto _testEof - _testEof23: - m.cs = 23 - goto _testEof - _testEof24: - m.cs = 24 - goto _testEof - _testEof25: - m.cs = 25 - goto _testEof - _testEof26: - m.cs = 26 - goto _testEof - _testEof27: - m.cs = 27 - goto _testEof - _testEof28: - m.cs = 28 - goto _testEof - _testEof29: - m.cs = 29 - goto _testEof - _testEof30: - m.cs = 30 - goto _testEof - _testEof31: - m.cs = 31 - goto _testEof - _testEof32: - m.cs = 32 - goto _testEof - _testEof33: - m.cs = 33 - goto _testEof - _testEof34: - m.cs = 34 - goto _testEof - _testEof35: - m.cs = 35 - goto _testEof - _testEof36: - m.cs = 36 - goto _testEof - _testEof37: - m.cs = 37 - goto _testEof - _testEof38: - m.cs = 38 - goto _testEof - _testEof44: - m.cs = 44 - goto _testEof - _testEof39: - m.cs = 39 - goto _testEof - _testEof40: - m.cs = 40 - goto _testEof - _testEof45: - m.cs = 45 - goto _testEof - _testEof41: - m.cs = 41 - goto _testEof - _testEof42: - m.cs = 42 - goto _testEof - _testEof43: - m.cs = 43 - goto _testEof - _testEof46: - m.cs = 46 - goto _testEof - - _testEof: - { - } - if (m.p) == (m.eof) { - switch m.cs { - case 44, 45: - - raw := m.text() - output.SS = string(raw) - // Iterate upper letters lowering them - for _, i := range m.tolower { - raw[i] = raw[i] + 32 - } - output.norm = string(raw) - - case 1, 2, 4: - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - case 3: - - m.err = fmt.Errorf(errPrefix, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - case 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 41: - - m.err = fmt.Errorf(errIdentifier, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - case 38: - - m.err = fmt.Errorf(errSpecificString, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - case 42: - - m.err = fmt.Errorf(errPrefix, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errIdentifier, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - case 43: - - m.err = fmt.Errorf(errNoUrnWithinID, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errIdentifier, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - case 39, 40: - - m.err = fmt.Errorf(errHex, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errSpecificString, m.p) - (m.p)-- - - { - goto st46 - } - - m.err = fmt.Errorf(errParse, m.p) - (m.p)-- - - { - goto st46 - } - - } - } - - _out: - { - } - } - - if m.cs < firstFinal || m.cs == enFail { - return nil, m.err - } - - return output, nil -} diff --git a/vendor/github.com/leodido/go-urn/machine.go.rl b/vendor/github.com/leodido/go-urn/machine.go.rl deleted file mode 100644 index 3bc05a6..0000000 --- a/vendor/github.com/leodido/go-urn/machine.go.rl +++ /dev/null @@ -1,159 +0,0 @@ -package urn - -import ( - "fmt" -) - -var ( - errPrefix = "expecting the prefix to be the \"urn\" string (whatever case) [col %d]" - errIdentifier = "expecting the identifier to be string (1..31 alnum chars, also containing dashes but not at its start) [col %d]" - errSpecificString = "expecting the specific string to be a string containing alnum, hex, or others ([()+,-.:=@;$_!*']) chars [col %d]" - errNoUrnWithinID = "expecting the identifier to not contain the \"urn\" reserved string [col %d]" - errHex = "expecting the specific string hex chars to be well-formed (%%alnum{2}) [col %d]" - errParse = "parsing error [col %d]" -) - -%%{ -machine urn; - -# unsigned alphabet -alphtype uint8; - -action mark { - m.pb = m.p -} - -action tolower { - m.tolower = append(m.tolower, m.p - m.pb) -} - -action set_pre { - output.prefix = string(m.text()) -} - -action set_nid { - output.ID = string(m.text()) -} - -action set_nss { - raw := m.text() - output.SS = string(raw) - // Iterate upper letters lowering them - for _, i := range m.tolower { - raw[i] = raw[i] + 32 - } - output.norm = string(raw) -} - -action err_pre { - m.err = fmt.Errorf(errPrefix, m.p) - fhold; - fgoto fail; -} - -action err_nid { - m.err = fmt.Errorf(errIdentifier, m.p) - fhold; - fgoto fail; -} - -action err_nss { - m.err = fmt.Errorf(errSpecificString, m.p) - fhold; - fgoto fail; -} - -action err_urn { - m.err = fmt.Errorf(errNoUrnWithinID, m.p) - fhold; - fgoto fail; -} - -action err_hex { - m.err = fmt.Errorf(errHex, m.p) - fhold; - fgoto fail; -} - -action err_parse { - m.err = fmt.Errorf(errParse, m.p) - fhold; - fgoto fail; -} - -pre = ([uU][rR][nN] @err(err_pre)) >mark %set_pre; - -nid = (alnum >mark (alnum | '-'){0,31}) %set_nid; - -hex = '%' (digit | lower | upper >tolower){2} $err(err_hex); - -sss = (alnum | [()+,\-.:=@;$_!*']); - -nss = (sss | hex)+ $err(err_nss); - -fail := (any - [\n\r])* @err{ fgoto main; }; - -main := (pre ':' (nid - pre %err(err_urn)) $err(err_nid) ':' nss >mark %set_nss) $err(err_parse); - -}%% - -%% write data noerror noprefix; - -// Machine is the interface representing the FSM -type Machine interface { - Error() error - Parse(input []byte) (*URN, error) -} - -type machine struct { - data []byte - cs int - p, pe, eof, pb int - err error - tolower []int -} - -// NewMachine creates a new FSM able to parse RFC 2141 strings. -func NewMachine() Machine { - m := &machine{} - - %% access m.; - %% variable p m.p; - %% variable pe m.pe; - %% variable eof m.eof; - %% variable data m.data; - - return m -} - -// Err returns the error that occurred on the last call to Parse. -// -// If the result is nil, then the line was parsed successfully. -func (m *machine) Error() error { - return m.err -} - -func (m *machine) text() []byte { - return m.data[m.pb:m.p] -} - -// Parse parses the input byte array as a RFC 2141 string. -func (m *machine) Parse(input []byte) (*URN, error) { - m.data = input - m.p = 0 - m.pb = 0 - m.pe = len(input) - m.eof = len(input) - m.err = nil - m.tolower = []int{} - output := &URN{} - - %% write init; - %% write exec; - - if m.cs < first_final || m.cs == en_fail { - return nil, m.err - } - - return output, nil -} diff --git a/vendor/github.com/leodido/go-urn/makefile b/vendor/github.com/leodido/go-urn/makefile deleted file mode 100644 index 47026d5..0000000 --- a/vendor/github.com/leodido/go-urn/makefile +++ /dev/null @@ -1,39 +0,0 @@ -SHELL := /bin/bash - -build: machine.go - -images: docs/urn.png - -machine.go: machine.go.rl - ragel -Z -G2 -e -o $@ $< - @sed -i '/^\/\/line/d' $@ - @$(MAKE) -s file=$@ snake2camel - @gofmt -w -s $@ - -docs/urn.dot: machine.go.rl - @mkdir -p docs - ragel -Z -e -Vp $< -o $@ - -docs/urn.png: docs/urn.dot - dot $< -Tpng -o $@ - -.PHONY: bench -bench: *_test.go machine.go - go test -bench=. -benchmem -benchtime=5s ./... - -.PHONY: tests -tests: *_test.go machine.go - go test -race -timeout 10s -coverprofile=coverage.out -covermode=atomic -v ./... - -.PHONY: clean -clean: - @rm -rf docs - @rm -f machine.go - -.PHONY: snake2camel -snake2camel: - @awk -i inplace '{ \ - while ( match($$0, /(.*)([a-z]+[0-9]*)_([a-zA-Z0-9])(.*)/, cap) ) \ - $$0 = cap[1] cap[2] toupper(cap[3]) cap[4]; \ - print \ - }' $(file) \ No newline at end of file diff --git a/vendor/github.com/leodido/go-urn/urn.go b/vendor/github.com/leodido/go-urn/urn.go deleted file mode 100644 index d51a6c9..0000000 --- a/vendor/github.com/leodido/go-urn/urn.go +++ /dev/null @@ -1,86 +0,0 @@ -package urn - -import ( - "encoding/json" - "fmt" - "strings" -) - -const errInvalidURN = "invalid URN: %s" - -// URN represents an Uniform Resource Name. -// -// The general form represented is: -// -// urn:: -// -// Details at https://tools.ietf.org/html/rfc2141. -type URN struct { - prefix string // Static prefix. Equal to "urn" when empty. - ID string // Namespace identifier - SS string // Namespace specific string - norm string // Normalized namespace specific string -} - -// Normalize turns the receiving URN into its norm version. -// -// Which means: lowercase prefix, lowercase namespace identifier, and immutate namespace specific string chars (except tokens which are lowercased). -func (u *URN) Normalize() *URN { - return &URN{ - prefix: "urn", - ID: strings.ToLower(u.ID), - SS: u.norm, - } -} - -// Equal checks the lexical equivalence of the current URN with another one. -func (u *URN) Equal(x *URN) bool { - return *u.Normalize() == *x.Normalize() -} - -// String reassembles the URN into a valid URN string. -// -// This requires both ID and SS fields to be non-empty. -// Otherwise it returns an empty string. -// -// Default URN prefix is "urn". -func (u *URN) String() string { - var res string - if u.ID != "" && u.SS != "" { - if u.prefix == "" { - res += "urn" - } - res += u.prefix + ":" + u.ID + ":" + u.SS - } - - return res -} - -// Parse is responsible to create an URN instance from a byte array matching the correct URN syntax. -func Parse(u []byte) (*URN, bool) { - urn, err := NewMachine().Parse(u) - if err != nil { - return nil, false - } - - return urn, true -} - -// MarshalJSON marshals the URN to JSON string form (e.g. `"urn:oid:1.2.3.4"`). -func (u URN) MarshalJSON() ([]byte, error) { - return json.Marshal(u.String()) -} - -// MarshalJSON unmarshals a URN from JSON string form (e.g. `"urn:oid:1.2.3.4"`). -func (u *URN) UnmarshalJSON(bytes []byte) error { - var str string - if err := json.Unmarshal(bytes, &str); err != nil { - return err - } - if value, ok := Parse([]byte(str)); !ok { - return fmt.Errorf(errInvalidURN, str) - } else { - *u = *value - } - return nil -} \ No newline at end of file diff --git a/vendor/github.com/pmezard/go-difflib/LICENSE b/vendor/github.com/pmezard/go-difflib/LICENSE deleted file mode 100644 index c67dad6..0000000 --- a/vendor/github.com/pmezard/go-difflib/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013, Patrick Mezard -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. - The names of its contributors may not 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 -HOLDER 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/pmezard/go-difflib/difflib/difflib.go b/vendor/github.com/pmezard/go-difflib/difflib/difflib.go deleted file mode 100644 index 003e99f..0000000 --- a/vendor/github.com/pmezard/go-difflib/difflib/difflib.go +++ /dev/null @@ -1,772 +0,0 @@ -// Package difflib is a partial port of Python difflib module. -// -// It provides tools to compare sequences of strings and generate textual diffs. -// -// The following class and functions have been ported: -// -// - SequenceMatcher -// -// - unified_diff -// -// - context_diff -// -// Getting unified diffs was the main goal of the port. Keep in mind this code -// is mostly suitable to output text differences in a human friendly way, there -// are no guarantees generated diffs are consumable by patch(1). -package difflib - -import ( - "bufio" - "bytes" - "fmt" - "io" - "strings" -) - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func calculateRatio(matches, length int) float64 { - if length > 0 { - return 2.0 * float64(matches) / float64(length) - } - return 1.0 -} - -type Match struct { - A int - B int - Size int -} - -type OpCode struct { - Tag byte - I1 int - I2 int - J1 int - J2 int -} - -// SequenceMatcher compares sequence of strings. The basic -// algorithm predates, and is a little fancier than, an algorithm -// published in the late 1980's by Ratcliff and Obershelp under the -// hyperbolic name "gestalt pattern matching". The basic idea is to find -// the longest contiguous matching subsequence that contains no "junk" -// elements (R-O doesn't address junk). The same idea is then applied -// recursively to the pieces of the sequences to the left and to the right -// of the matching subsequence. This does not yield minimal edit -// sequences, but does tend to yield matches that "look right" to people. -// -// SequenceMatcher tries to compute a "human-friendly diff" between two -// sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the -// longest *contiguous* & junk-free matching subsequence. That's what -// catches peoples' eyes. The Windows(tm) windiff has another interesting -// notion, pairing up elements that appear uniquely in each sequence. -// That, and the method here, appear to yield more intuitive difference -// reports than does diff. This method appears to be the least vulnerable -// to synching up on blocks of "junk lines", though (like blank lines in -// ordinary text files, or maybe "

" lines in HTML files). That may be -// because this is the only method of the 3 that has a *concept* of -// "junk" . -// -// Timing: Basic R-O is cubic time worst case and quadratic time expected -// case. SequenceMatcher is quadratic time for the worst case and has -// expected-case behavior dependent in a complicated way on how many -// elements the sequences have in common; best case time is linear. -type SequenceMatcher struct { - a []string - b []string - b2j map[string][]int - IsJunk func(string) bool - autoJunk bool - bJunk map[string]struct{} - matchingBlocks []Match - fullBCount map[string]int - bPopular map[string]struct{} - opCodes []OpCode -} - -func NewMatcher(a, b []string) *SequenceMatcher { - m := SequenceMatcher{autoJunk: true} - m.SetSeqs(a, b) - return &m -} - -func NewMatcherWithJunk(a, b []string, autoJunk bool, - isJunk func(string) bool) *SequenceMatcher { - - m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk} - m.SetSeqs(a, b) - return &m -} - -// Set two sequences to be compared. -func (m *SequenceMatcher) SetSeqs(a, b []string) { - m.SetSeq1(a) - m.SetSeq2(b) -} - -// Set the first sequence to be compared. The second sequence to be compared is -// not changed. -// -// SequenceMatcher computes and caches detailed information about the second -// sequence, so if you want to compare one sequence S against many sequences, -// use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other -// sequences. -// -// See also SetSeqs() and SetSeq2(). -func (m *SequenceMatcher) SetSeq1(a []string) { - if &a == &m.a { - return - } - m.a = a - m.matchingBlocks = nil - m.opCodes = nil -} - -// Set the second sequence to be compared. The first sequence to be compared is -// not changed. -func (m *SequenceMatcher) SetSeq2(b []string) { - if &b == &m.b { - return - } - m.b = b - m.matchingBlocks = nil - m.opCodes = nil - m.fullBCount = nil - m.chainB() -} - -func (m *SequenceMatcher) chainB() { - // Populate line -> index mapping - b2j := map[string][]int{} - for i, s := range m.b { - indices := b2j[s] - indices = append(indices, i) - b2j[s] = indices - } - - // Purge junk elements - m.bJunk = map[string]struct{}{} - if m.IsJunk != nil { - junk := m.bJunk - for s, _ := range b2j { - if m.IsJunk(s) { - junk[s] = struct{}{} - } - } - for s, _ := range junk { - delete(b2j, s) - } - } - - // Purge remaining popular elements - popular := map[string]struct{}{} - n := len(m.b) - if m.autoJunk && n >= 200 { - ntest := n/100 + 1 - for s, indices := range b2j { - if len(indices) > ntest { - popular[s] = struct{}{} - } - } - for s, _ := range popular { - delete(b2j, s) - } - } - m.bPopular = popular - m.b2j = b2j -} - -func (m *SequenceMatcher) isBJunk(s string) bool { - _, ok := m.bJunk[s] - return ok -} - -// Find longest matching block in a[alo:ahi] and b[blo:bhi]. -// -// If IsJunk is not defined: -// -// Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where -// alo <= i <= i+k <= ahi -// blo <= j <= j+k <= bhi -// and for all (i',j',k') meeting those conditions, -// k >= k' -// i <= i' -// and if i == i', j <= j' -// -// In other words, of all maximal matching blocks, return one that -// starts earliest in a, and of all those maximal matching blocks that -// start earliest in a, return the one that starts earliest in b. -// -// If IsJunk is defined, first the longest matching block is -// determined as above, but with the additional restriction that no -// junk element appears in the block. Then that block is extended as -// far as possible by matching (only) junk elements on both sides. So -// the resulting block never matches on junk except as identical junk -// happens to be adjacent to an "interesting" match. -// -// If no blocks match, return (alo, blo, 0). -func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match { - // CAUTION: stripping common prefix or suffix would be incorrect. - // E.g., - // ab - // acab - // Longest matching block is "ab", but if common prefix is - // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so - // strip, so ends up claiming that ab is changed to acab by - // inserting "ca" in the middle. That's minimal but unintuitive: - // "it's obvious" that someone inserted "ac" at the front. - // Windiff ends up at the same place as diff, but by pairing up - // the unique 'b's and then matching the first two 'a's. - besti, bestj, bestsize := alo, blo, 0 - - // find longest junk-free match - // during an iteration of the loop, j2len[j] = length of longest - // junk-free match ending with a[i-1] and b[j] - j2len := map[int]int{} - for i := alo; i != ahi; i++ { - // look at all instances of a[i] in b; note that because - // b2j has no junk keys, the loop is skipped if a[i] is junk - newj2len := map[int]int{} - for _, j := range m.b2j[m.a[i]] { - // a[i] matches b[j] - if j < blo { - continue - } - if j >= bhi { - break - } - k := j2len[j-1] + 1 - newj2len[j] = k - if k > bestsize { - besti, bestj, bestsize = i-k+1, j-k+1, k - } - } - j2len = newj2len - } - - // Extend the best by non-junk elements on each end. In particular, - // "popular" non-junk elements aren't in b2j, which greatly speeds - // the inner loop above, but also means "the best" match so far - // doesn't contain any junk *or* popular non-junk elements. - for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - !m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - // Now that we have a wholly interesting match (albeit possibly - // empty!), we may as well suck up the matching junk on each - // side of it too. Can't think of a good reason not to, and it - // saves post-processing the (possibly considerable) expense of - // figuring out what to do with it. In the case of an empty - // interesting match, this is clearly the right thing to do, - // because no other kind of match is possible in the regions. - for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) && - m.a[besti-1] == m.b[bestj-1] { - besti, bestj, bestsize = besti-1, bestj-1, bestsize+1 - } - for besti+bestsize < ahi && bestj+bestsize < bhi && - m.isBJunk(m.b[bestj+bestsize]) && - m.a[besti+bestsize] == m.b[bestj+bestsize] { - bestsize += 1 - } - - return Match{A: besti, B: bestj, Size: bestsize} -} - -// Return list of triples describing matching subsequences. -// -// Each triple is of the form (i, j, n), and means that -// a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in -// i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are -// adjacent triples in the list, and the second is not the last triple in the -// list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe -// adjacent equal blocks. -// -// The last triple is a dummy, (len(a), len(b), 0), and is the only -// triple with n==0. -func (m *SequenceMatcher) GetMatchingBlocks() []Match { - if m.matchingBlocks != nil { - return m.matchingBlocks - } - - var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match - matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match { - match := m.findLongestMatch(alo, ahi, blo, bhi) - i, j, k := match.A, match.B, match.Size - if match.Size > 0 { - if alo < i && blo < j { - matched = matchBlocks(alo, i, blo, j, matched) - } - matched = append(matched, match) - if i+k < ahi && j+k < bhi { - matched = matchBlocks(i+k, ahi, j+k, bhi, matched) - } - } - return matched - } - matched := matchBlocks(0, len(m.a), 0, len(m.b), nil) - - // It's possible that we have adjacent equal blocks in the - // matching_blocks list now. - nonAdjacent := []Match{} - i1, j1, k1 := 0, 0, 0 - for _, b := range matched { - // Is this block adjacent to i1, j1, k1? - i2, j2, k2 := b.A, b.B, b.Size - if i1+k1 == i2 && j1+k1 == j2 { - // Yes, so collapse them -- this just increases the length of - // the first block by the length of the second, and the first - // block so lengthened remains the block to compare against. - k1 += k2 - } else { - // Not adjacent. Remember the first block (k1==0 means it's - // the dummy we started with), and make the second block the - // new block to compare against. - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - i1, j1, k1 = i2, j2, k2 - } - } - if k1 > 0 { - nonAdjacent = append(nonAdjacent, Match{i1, j1, k1}) - } - - nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0}) - m.matchingBlocks = nonAdjacent - return m.matchingBlocks -} - -// Return list of 5-tuples describing how to turn a into b. -// -// Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple -// has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the -// tuple preceding it, and likewise for j1 == the previous j2. -// -// The tags are characters, with these meanings: -// -// 'r' (replace): a[i1:i2] should be replaced by b[j1:j2] -// -// 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case. -// -// 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case. -// -// 'e' (equal): a[i1:i2] == b[j1:j2] -func (m *SequenceMatcher) GetOpCodes() []OpCode { - if m.opCodes != nil { - return m.opCodes - } - i, j := 0, 0 - matching := m.GetMatchingBlocks() - opCodes := make([]OpCode, 0, len(matching)) - for _, m := range matching { - // invariant: we've pumped out correct diffs to change - // a[:i] into b[:j], and the next matching block is - // a[ai:ai+size] == b[bj:bj+size]. So we need to pump - // out a diff to change a[i:ai] into b[j:bj], pump out - // the matching block, and move (i,j) beyond the match - ai, bj, size := m.A, m.B, m.Size - tag := byte(0) - if i < ai && j < bj { - tag = 'r' - } else if i < ai { - tag = 'd' - } else if j < bj { - tag = 'i' - } - if tag > 0 { - opCodes = append(opCodes, OpCode{tag, i, ai, j, bj}) - } - i, j = ai+size, bj+size - // the list of matching blocks is terminated by a - // sentinel with size 0 - if size > 0 { - opCodes = append(opCodes, OpCode{'e', ai, i, bj, j}) - } - } - m.opCodes = opCodes - return m.opCodes -} - -// Isolate change clusters by eliminating ranges with no changes. -// -// Return a generator of groups with up to n lines of context. -// Each group is in the same format as returned by GetOpCodes(). -func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode { - if n < 0 { - n = 3 - } - codes := m.GetOpCodes() - if len(codes) == 0 { - codes = []OpCode{OpCode{'e', 0, 1, 0, 1}} - } - // Fixup leading and trailing groups if they show no changes. - if codes[0].Tag == 'e' { - c := codes[0] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2} - } - if codes[len(codes)-1].Tag == 'e' { - c := codes[len(codes)-1] - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)} - } - nn := n + n - groups := [][]OpCode{} - group := []OpCode{} - for _, c := range codes { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - // End the current group and start a new one whenever - // there is a large range with no changes. - if c.Tag == 'e' && i2-i1 > nn { - group = append(group, OpCode{c.Tag, i1, min(i2, i1+n), - j1, min(j2, j1+n)}) - groups = append(groups, group) - group = []OpCode{} - i1, j1 = max(i1, i2-n), max(j1, j2-n) - } - group = append(group, OpCode{c.Tag, i1, i2, j1, j2}) - } - if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') { - groups = append(groups, group) - } - return groups -} - -// Return a measure of the sequences' similarity (float in [0,1]). -// -// Where T is the total number of elements in both sequences, and -// M is the number of matches, this is 2.0*M / T. -// Note that this is 1 if the sequences are identical, and 0 if -// they have nothing in common. -// -// .Ratio() is expensive to compute if you haven't already computed -// .GetMatchingBlocks() or .GetOpCodes(), in which case you may -// want to try .QuickRatio() or .RealQuickRation() first to get an -// upper bound. -func (m *SequenceMatcher) Ratio() float64 { - matches := 0 - for _, m := range m.GetMatchingBlocks() { - matches += m.Size - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() relatively quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute. -func (m *SequenceMatcher) QuickRatio() float64 { - // viewing a and b as multisets, set matches to the cardinality - // of their intersection; this counts the number of matches - // without regard to order, so is clearly an upper bound - if m.fullBCount == nil { - m.fullBCount = map[string]int{} - for _, s := range m.b { - m.fullBCount[s] = m.fullBCount[s] + 1 - } - } - - // avail[x] is the number of times x appears in 'b' less the - // number of times we've seen it in 'a' so far ... kinda - avail := map[string]int{} - matches := 0 - for _, s := range m.a { - n, ok := avail[s] - if !ok { - n = m.fullBCount[s] - } - avail[s] = n - 1 - if n > 0 { - matches += 1 - } - } - return calculateRatio(matches, len(m.a)+len(m.b)) -} - -// Return an upper bound on ratio() very quickly. -// -// This isn't defined beyond that it is an upper bound on .Ratio(), and -// is faster to compute than either .Ratio() or .QuickRatio(). -func (m *SequenceMatcher) RealQuickRatio() float64 { - la, lb := len(m.a), len(m.b) - return calculateRatio(min(la, lb), la+lb) -} - -// Convert range to the "ed" format -func formatRangeUnified(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 1 { - return fmt.Sprintf("%d", beginning) - } - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - return fmt.Sprintf("%d,%d", beginning, length) -} - -// Unified diff parameters -type UnifiedDiff struct { - A []string // First sequence lines - FromFile string // First file name - FromDate string // First file time - B []string // Second sequence lines - ToFile string // Second file name - ToDate string // Second file time - Eol string // Headers end of line, defaults to LF - Context int // Number of context lines -} - -// Compare two sequences of lines; generate the delta as a unified diff. -// -// Unified diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by 'n' which -// defaults to three. -// -// By default, the diff control lines (those with ---, +++, or @@) are -// created with a trailing newline. This is helpful so that inputs -// created from file.readlines() result in diffs that are suitable for -// file.writelines() since both the inputs and outputs have trailing -// newlines. -// -// For inputs that do not have trailing newlines, set the lineterm -// argument to "" so that the output will be uniformly newline free. -// -// The unidiff format normally has a header for filenames and modification -// times. Any or all of these may be specified using strings for -// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. -// The modification times are normally expressed in the ISO 8601 format. -func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - wf := func(format string, args ...interface{}) error { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - return err - } - ws := func(s string) error { - _, err := buf.WriteString(s) - return err - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - if diff.FromFile != "" || diff.ToFile != "" { - err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol) - if err != nil { - return err - } - err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol) - if err != nil { - return err - } - } - } - first, last := g[0], g[len(g)-1] - range1 := formatRangeUnified(first.I1, last.I2) - range2 := formatRangeUnified(first.J1, last.J2) - if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil { - return err - } - for _, c := range g { - i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2 - if c.Tag == 'e' { - for _, line := range diff.A[i1:i2] { - if err := ws(" " + line); err != nil { - return err - } - } - continue - } - if c.Tag == 'r' || c.Tag == 'd' { - for _, line := range diff.A[i1:i2] { - if err := ws("-" + line); err != nil { - return err - } - } - } - if c.Tag == 'r' || c.Tag == 'i' { - for _, line := range diff.B[j1:j2] { - if err := ws("+" + line); err != nil { - return err - } - } - } - } - } - return nil -} - -// Like WriteUnifiedDiff but returns the diff a string. -func GetUnifiedDiffString(diff UnifiedDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteUnifiedDiff(w, diff) - return string(w.Bytes()), err -} - -// Convert range to the "ed" format. -func formatRangeContext(start, stop int) string { - // Per the diff spec at http://www.unix.org/single_unix_specification/ - beginning := start + 1 // lines start numbering with one - length := stop - start - if length == 0 { - beginning -= 1 // empty ranges begin at line just before the range - } - if length <= 1 { - return fmt.Sprintf("%d", beginning) - } - return fmt.Sprintf("%d,%d", beginning, beginning+length-1) -} - -type ContextDiff UnifiedDiff - -// Compare two sequences of lines; generate the delta as a context diff. -// -// Context diffs are a compact way of showing line changes and a few -// lines of context. The number of context lines is set by diff.Context -// which defaults to three. -// -// By default, the diff control lines (those with *** or ---) are -// created with a trailing newline. -// -// For inputs that do not have trailing newlines, set the diff.Eol -// argument to "" so that the output will be uniformly newline free. -// -// The context diff format normally has a header for filenames and -// modification times. Any or all of these may be specified using -// strings for diff.FromFile, diff.ToFile, diff.FromDate, diff.ToDate. -// The modification times are normally expressed in the ISO 8601 format. -// If not specified, the strings default to blanks. -func WriteContextDiff(writer io.Writer, diff ContextDiff) error { - buf := bufio.NewWriter(writer) - defer buf.Flush() - var diffErr error - wf := func(format string, args ...interface{}) { - _, err := buf.WriteString(fmt.Sprintf(format, args...)) - if diffErr == nil && err != nil { - diffErr = err - } - } - ws := func(s string) { - _, err := buf.WriteString(s) - if diffErr == nil && err != nil { - diffErr = err - } - } - - if len(diff.Eol) == 0 { - diff.Eol = "\n" - } - - prefix := map[byte]string{ - 'i': "+ ", - 'd': "- ", - 'r': "! ", - 'e': " ", - } - - started := false - m := NewMatcher(diff.A, diff.B) - for _, g := range m.GetGroupedOpCodes(diff.Context) { - if !started { - started = true - fromDate := "" - if len(diff.FromDate) > 0 { - fromDate = "\t" + diff.FromDate - } - toDate := "" - if len(diff.ToDate) > 0 { - toDate = "\t" + diff.ToDate - } - if diff.FromFile != "" || diff.ToFile != "" { - wf("*** %s%s%s", diff.FromFile, fromDate, diff.Eol) - wf("--- %s%s%s", diff.ToFile, toDate, diff.Eol) - } - } - - first, last := g[0], g[len(g)-1] - ws("***************" + diff.Eol) - - range1 := formatRangeContext(first.I1, last.I2) - wf("*** %s ****%s", range1, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'd' { - for _, cc := range g { - if cc.Tag == 'i' { - continue - } - for _, line := range diff.A[cc.I1:cc.I2] { - ws(prefix[cc.Tag] + line) - } - } - break - } - } - - range2 := formatRangeContext(first.J1, last.J2) - wf("--- %s ----%s", range2, diff.Eol) - for _, c := range g { - if c.Tag == 'r' || c.Tag == 'i' { - for _, cc := range g { - if cc.Tag == 'd' { - continue - } - for _, line := range diff.B[cc.J1:cc.J2] { - ws(prefix[cc.Tag] + line) - } - } - break - } - } - } - return diffErr -} - -// Like WriteContextDiff but returns the diff a string. -func GetContextDiffString(diff ContextDiff) (string, error) { - w := &bytes.Buffer{} - err := WriteContextDiff(w, diff) - return string(w.Bytes()), err -} - -// Split a string on "\n" while preserving them. The output can be used -// as input for UnifiedDiff and ContextDiff structures. -func SplitLines(s string) []string { - lines := strings.SplitAfter(s, "\n") - lines[len(lines)-1] += "\n" - return lines -} diff --git a/vendor/github.com/rsteube/carapace-bin/LICENSE b/vendor/github.com/rsteube/carapace-bin/LICENSE deleted file mode 100644 index 073d68d..0000000 --- a/vendor/github.com/rsteube/carapace-bin/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 rsteube - -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/rsteube/carapace-bin/pkg/actions/net/ip.go b/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/ip.go deleted file mode 100644 index 9e4fc25..0000000 --- a/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/ip.go +++ /dev/null @@ -1,60 +0,0 @@ -package net - -import ( - "github.com/rsteube/carapace" - "github.com/rsteube/carapace-bin/pkg/actions/number" -) - -// ActionIpv4Addresses completes ipv4 addresses -// -// 192.168.1.100 -// 192.168.100.100/16 -func ActionIpv4Addresses() carapace.Action { - return carapace.ActionMultiParts("/", func(c carapace.Context) carapace.Action { - switch len(c.Parts) { - case 0: - return carapace.ActionMultiParts(".", func(c carapace.Context) carapace.Action { - switch len(c.Parts) { - case 0: - return number.ActionRange(number.RangeOpts{Format: "%v", Start: 0, End: 255}).Invoke(c).Suffix(".").ToA() - case 1: - return number.ActionRange(number.RangeOpts{Format: "%v", Start: 0, End: 255}).Invoke(c).Suffix(".").ToA() - case 2: - return number.ActionRange(number.RangeOpts{Format: "%v", Start: 0, End: 255}).Invoke(c).Suffix(".").ToA() - case 3: - return number.ActionRange(number.RangeOpts{Format: "%v", Start: 0, End: 255}) - default: - return carapace.ActionValues() - } - }) - case 1: - return ActionSubnets() - default: - return carapace.ActionValues() - } - }) -} - -// ActionSubnets completes subnets -// -// 24 (255.255.255.0 - 256)# -// 16 (255.255.0.0 - 65536) -func ActionSubnets() carapace.Action { - return carapace.ActionValuesDescribed( - "30", "255.255.255.252 - 4", - "29", "255.255.255.248 - 8", - "28", "255.255.255.240 - 16", - "27", "255.255.255.224 - 32", - "26", "255.255.255.192 - 64", - "25", "255.255.255.128 - 128", - "24", "255.255.255.0 - 256", - "23", "255.255.254.0 - 512", - "22", "255.255.252.0 - 1024", - "21", "255.255.248.0 - 2048", - "20", "255.255.240.0 - 4096", - "19", "255.255.224.0 - 8192", - "18", "255.255.192.0 - 16384", - "17", "255.255.128.0 - 32768", - "16", "255.255.0.0 - 65536", - ) -} diff --git a/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/net.go b/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/net.go deleted file mode 100644 index c0c3b22..0000000 --- a/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/net.go +++ /dev/null @@ -1,226 +0,0 @@ -// package net contains network related actions -package net - -import ( - "os" - "regexp" - "strings" - - "github.com/rsteube/carapace" - "github.com/rsteube/carapace/pkg/style" - "github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs" -) - -// ActionHosts completes known hosts -// -// 192.168.1.1 -// pihole -func ActionHosts() carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - vals := []string{} - if file, err := c.Abs("~/.ssh/known_hosts"); err == nil { - if content, err := os.ReadFile(file); err == nil { - r := regexp.MustCompile(`^(?P[^ ,#]+)`) - rIPv4 := regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`) - rIPv6 := regexp.MustCompile(`^([A-Fa-f0-9]{0,4}:){5,7}[A-Fa-f0-9]{0,4}$`) // TODO likely wrong - for _, entry := range strings.Split(string(content), "\n") { - if r.MatchString(entry) { - if host := r.FindStringSubmatch(entry)[0]; rIPv4.MatchString(host) { - vals = append(vals, host, style.Default) - } else if rIPv6.MatchString(host) { - vals = append(vals, host, style.Bold) - } else { - vals = append(vals, host, style.Blue) - } - } - } - } else { - return carapace.ActionMessage(err.Error()) - } - } - return carapace.ActionStyledValues(vals...) - }) -} - -type IncludedDevices struct { - Bluetooth bool - Bond bool - BondSlave bool - Bridge bool - BridgeSlave bool - Cdma bool - Ethernet bool - Gsm bool - Infiniband bool - Loopback bool - OlpcMesh bool - Pppoe bool - Team bool - TeamSlave bool - Vlan bool - Vpn bool - Wifi bool - Wimax bool -} - -func (i IncludedDevices) Includes(deviceType string) bool { - include := map[string]bool{ - "ethernet": i.Ethernet, - "wifi": i.Wifi, - "wimax": i.Wimax, - "pppoe": i.Pppoe, - "gsm": i.Gsm, - "cdma": i.Cdma, - "infiniband": i.Infiniband, - "bluetooth": i.Bluetooth, - "vlan": i.Vlan, - "bond": i.Bond, - "bond-slave": i.BondSlave, - "team": i.Team, - "team-slave": i.TeamSlave, - "bridge": i.Bridge, - "bridge-slave": i.BridgeSlave, - "vpn": i.Vpn, - "olpc-mesh": i.OlpcMesh, - "loopback": i.Loopback, - } - if value, exists := include[deviceType]; exists { - return value - } else { - return false - } -} - -var AllDevices = IncludedDevices{ - Bluetooth: true, - Bond: true, - BondSlave: true, - Bridge: true, - BridgeSlave: true, - Cdma: true, - Ethernet: true, - Gsm: true, - Infiniband: true, - Loopback: true, - OlpcMesh: true, - Pppoe: true, - Team: true, - TeamSlave: true, - Vlan: true, - Vpn: true, - Wifi: true, - Wimax: true, -} - -// ActionDevices completes network devices -// -// lo (loopback) -// wlp3s0 (wifi) -func ActionDevices(includedDevices IncludedDevices) carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - if _, err := execabs.LookPath("nmcli"); err == nil { - return carapace.ActionExecCommand("nmcli", "--terse", "--fields", "device,type", "device", "status")(func(output []byte) carapace.Action { - lines := strings.Split(string(output), "\n") - vals := make([]string, 0) - for _, line := range lines[:len(lines)-1] { - parts := strings.Split(line, ":") - if includedDevices.Includes(parts[1]) { - vals = append(vals, parts[0], parts[1]) - } - } - return carapace.ActionValuesDescribed(vals...) - }) - } else if _, err := execabs.LookPath("ifconfig"); err == nil { - // fallback to basic ifconfig if nmcli is not available - return carapace.ActionExecCommand("ifconfig")(func(output []byte) carapace.Action { - interfaces := []string{} - r := regexp.MustCompile("^[0-9a-zA-Z]") - for _, line := range strings.Split(string(output), "\n") { - if matches := r.MatchString(line); matches { - interfaces = append(interfaces, strings.Split(line, ":")[0]) - } - } - return carapace.ActionValues(interfaces...) - }) - } - return carapace.ActionMessage("neither nmcli nor ifconfig available") - }) -} - -// ActionConnections completes stored network connections -// -// somewifi (802-11-wireless abcdefgh-hijk-lmnop-qert-012345678902) -// private (vpn abcdefgh-hijk-lmnop-qert-012345678901) -func ActionConnections() carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - return carapace.ActionExecCommand("nmcli", "--terse", "connection", "show")(func(output []byte) carapace.Action { - lines := strings.Split(string(output), "\n") - vals := make([]string, (len(lines)-1)*2) - for index, line := range lines[:len(lines)-1] { - parts := strings.Split(line, ":") - vals[index*2] = parts[0] - vals[index*2+1] = parts[2] + " " + parts[1] - } - return carapace.ActionValuesDescribed(vals...) - }) - }) -} - -// ActionBssids completes BSSID's of local wifi networks -// -// AA:BB:CC:DD:EE:FF (somewifi) -// AA:BB:CC:DD:EE:11 (anotherwifi) -func ActionBssids() carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - return carapace.ActionExecCommand("nmcli", "--terse", "--fields", "bssid,ssid,bars", "device", "wifi", "list")(func(output []byte) carapace.Action { - lines := strings.Split(string(output), "\n") - - vals := make([]string, 0) - for _, line := range lines[:len(lines)-1] { - mac := strings.Replace(line[:22], `\:`, `:`, -1) - splitted := strings.Split(line[23:], ":") - if name := splitted[0]; name != "" { - vals = append(vals, mac, splitted[0], styleForBars(splitted[1])) - } - } - return carapace.ActionStyledValuesDescribed(vals...) - }) - }) -} - -// ActionSsids completes SSID's of local wifi networks -// -// somewifi (AA:BB:CC:DD:EE:FF) -// anotherwifi (AA:BB:CC:DD:EE:11) -func ActionSsids() carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - return carapace.ActionExecCommand("nmcli", "--terse", "--fields", "bssid,ssid,bars", "device", "wifi", "list")(func(output []byte) carapace.Action { - lines := strings.Split(string(output), "\n") - - vals := make([]string, 0) - for _, line := range lines[:len(lines)-1] { - mac := strings.Replace(line[:22], `\:`, `:`, -1) - splitted := strings.Split(line[23:], ":") - if name := splitted[0]; name != "" { - vals = append(vals, splitted[0], mac, styleForBars(splitted[1])) - } - } - return carapace.ActionStyledValuesDescribed(vals...) - }) - }) -} - -func styleForBars(s string) string { - switch s { - case "▂___": - return style.Blue - case "▂▄__": - return style.Magenta - case "▂▄▆_": - return style.Yellow - case "▂▄▆█": - return style.Green - default: - return style.Default - } -} diff --git a/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/port.go b/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/port.go deleted file mode 100644 index a7a2ee4..0000000 --- a/vendor/github.com/rsteube/carapace-bin/pkg/actions/net/port.go +++ /dev/null @@ -1,35 +0,0 @@ -package net - -import ( - "github.com/rsteube/carapace" -) - -// ActionPorts completes commonly used ports (opiniated) -// -// 80 (http) -// 443 (https) -func ActionPorts() carapace.Action { - return carapace.ActionValuesDescribed( - "21", "ftp", - "22", "ssh", - "25", "smtp", - "80", "http", - "110", "pop3", - "143", "imap", - "443", "https", - "587", "smtp ssl", - "993", "imap ssl", - "995", "pop3 ssl", - "2077", "webdav", - "2078", "webdav ssl", - "2082", "cpanel", - "2083", "cpanel ssl", - "2086", "webhost manager", - "2087", "webhost manager ssl", - "2095", "webmail", - "2096", "webmail ssl", - "3306", "mysql", - "8080", "http alternative", - "8443", "https alternative", - ) -} diff --git a/vendor/github.com/rsteube/carapace-bin/pkg/actions/number/number.go b/vendor/github.com/rsteube/carapace-bin/pkg/actions/number/number.go deleted file mode 100644 index 9d38e86..0000000 --- a/vendor/github.com/rsteube/carapace-bin/pkg/actions/number/number.go +++ /dev/null @@ -1,31 +0,0 @@ -// package os contains number related actions -package number - -import ( - "fmt" - - "github.com/rsteube/carapace" -) - -type RangeOpts struct { - Format string - Start int - End int -} - -// ActionRange completes a number range formatted with given (optional) format specifier -// -// ActionRange(RangeOpts{Format: "%02d", Start: 0, End: 59}) -func ActionRange(opts RangeOpts) carapace.Action { - return carapace.ActionCallback(func(c carapace.Context) carapace.Action { - if opts.Format == "" { - opts.Format = "%d" - } - - vals := make([]string, 0) - for i := opts.Start; i <= opts.End; i = i + 1 { - vals = append(vals, fmt.Sprintf(opts.Format, i)) - } - return carapace.ActionValues(vals...) - }) -} diff --git a/vendor/github.com/rsteube/carapace/.dockerignore b/vendor/github.com/rsteube/carapace/.dockerignore deleted file mode 100644 index fb89b31..0000000 --- a/vendor/github.com/rsteube/carapace/.dockerignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.dockerfile diff --git a/vendor/github.com/rsteube/carapace/.gitignore b/vendor/github.com/rsteube/carapace/.gitignore deleted file mode 100644 index 39959f6..0000000 --- a/vendor/github.com/rsteube/carapace/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.vscode -example/example -caraparse/caraparse -docs/book diff --git a/vendor/github.com/rsteube/carapace/.goreleaser.yml b/vendor/github.com/rsteube/carapace/.goreleaser.yml deleted file mode 100644 index 1a57ff3..0000000 --- a/vendor/github.com/rsteube/carapace/.goreleaser.yml +++ /dev/null @@ -1,40 +0,0 @@ -before: - hooks: - - go mod download -builds: - - id: example - env: - - CGO_ENABLED=0 - goos: - - linux - - windows - - darwin - main: ./example - binary: example - - id: example-nonposix - env: - - CGO_ENABLED=0 - goos: - - linux - - windows - - darwin - main: ./example-nonposix - binary: example-nonposix -archives: - - replacements: - darwin: Darwin - linux: Linux - windows: Windows - 386: i386 - amd64: x86_64 - name_template: "example_{{ .Version }}_{{ .Os }}_{{ .Arch }}" -checksum: - name_template: 'checksums.txt' -snapshot: - name_template: "{{ .Tag }}-next" -changelog: - sort: asc - filters: - exclude: - - '^docs:' - - '^test:' diff --git a/vendor/github.com/rsteube/carapace/Dockerfile b/vendor/github.com/rsteube/carapace/Dockerfile deleted file mode 100644 index 91698fa..0000000 --- a/vendor/github.com/rsteube/carapace/Dockerfile +++ /dev/null @@ -1,103 +0,0 @@ -FROM golang:1.20-bullseye as base -LABEL org.opencontainers.image.source https://github.com/rsteube/carapace -USER root - -FROM base as bat -ARG version=0.22.1 -RUN curl -L https://github.com/sharkdp/bat/releases/download/v${version}/bat-v${version}-x86_64-unknown-linux-gnu.tar.gz \ - | tar -C /usr/local/bin/ --strip-components=1 -xvz bat-v${version}-x86_64-unknown-linux-gnu/bat \ - && chmod +x /usr/local/bin/bat - -FROM base as ble -RUN git clone --recursive https://github.com/akinomyoga/ble.sh.git \ - && apt-get update && apt-get install -y gawk \ - && make -C ble.sh - -FROM base as elvish -ARG version=0.18.0 -RUN curl https://dl.elv.sh/linux-amd64/elvish-v${version}.tar.gz | tar -xvz \ - && mv elvish-* /usr/local/bin/elvish - -FROM base as goreleaser -ARG version=1.15.1 -RUN curl -L https://github.com/goreleaser/goreleaser/releases/download/v${version}/goreleaser_Linux_x86_64.tar.gz | tar -xvz goreleaser \ - && mv goreleaser /usr/local/bin/goreleaser - -FROM rsteube/ion-poc as ion-poc -#FROM rust as ion -#ARG version=master -#RUN git clone --single-branch --branch "${version}" --depth 1 https://gitlab.redox-os.org/redox-os/ion/ \ -# && cd ion \ -# && RUSTUP=0 make # By default RUSTUP equals 1, which is for developmental purposes \ -# && sudo make install prefix=/usr \ -# && sudo make update-shells prefix=/usr - -FROM base as nushell -ARG version=0.75.0 -RUN curl -L https://github.com/nushell/nushell/releases/download/${version}/nu-${version}-x86_64-unknown-linux-gnu.tar.gz | tar -xvz \ - && mv nu-${version}-x86_64-unknown-linux-gnu/nu* /usr/local/bin - -FROM base as oil -ARG version=0.14.0 -RUN apt-get update && apt-get install -y libreadline-dev -RUN curl https://www.oilshell.org/download/oil-${version}.tar.gz | tar -xvz \ - && cd oil-*/ \ - && ./configure \ - && make \ - && ./install - -FROM base as starship -ARG version=1.12.0 -RUN wget -qO- "https://github.com/starship/starship/releases/download/v${version}/starship-x86_64-unknown-linux-gnu.tar.gz" | tar -xvz starship \ - && mv starship /usr/local/bin/ - -FROM base as vivid -ARG version=0.8.0 -RUN wget -qO- "https://github.com/sharkdp/vivid/releases/download/v${version}/vivid-v${version}-x86_64-unknown-linux-gnu.tar.gz" | tar -xvz vivid-v${version}-x86_64-unknown-linux-gnu/vivid \ - && mv vivid-v${version}-x86_64-unknown-linux-gnu/vivid /usr/local/bin/ - -FROM base as mdbook -ARG version=0.4.25 -RUN curl -L "https://github.com/rust-lang/mdBook/releases/download/v${version}/mdbook-v${version}-x86_64-unknown-linux-gnu.tar.gz" | tar -xvz mdbook \ - && curl -L "https://github.com/Michael-F-Bryan/mdbook-linkcheck/releases/download/v0.7.0/mdbook-linkcheck-v0.7.0-x86_64-unknown-linux-gnu.tar.gz" | tar -xvz mdbook-linkcheck \ - && mv mdbook* /usr/local/bin/ - -FROM base -RUN apt-get update && apt-get install -y libicu67 -RUN wget -q https://github.com/PowerShell/PowerShell/releases/download/v7.3.0/powershell_7.3.0-1.deb_amd64.deb\ - && dpkg -i powershell_7.3.0-1.deb_amd64.deb \ - && rm powershell_7.3.0-1.deb_amd64.deb - -RUN apt-get update \ - && apt-get install -y fish \ - elvish \ - python3-pip \ - shellcheck \ - tcsh \ - zsh \ - expect - -RUN pip3 install --no-cache-dir --disable-pip-version-check xonsh prompt_toolkit \ - && ln -s $(which xonsh) /usr/bin/xonsh - -RUN pwsh -Command "Install-Module PSScriptAnalyzer -Scope AllUsers -Force" - -RUN git config --system safe.directory '*' - -COPY --from=bat /usr/local/bin/* /usr/local/bin/ -COPY --from=ble /go/ble.sh /opt/ble.sh -COPY --from=elvish /usr/local/bin/* /usr/local/bin/ -COPY --from=goreleaser /usr/local/bin/* /usr/local/bin/ -#COPY --from=ion /ion/target/release/ion /usr/local/bin/ -COPY --from=ion-poc /usr/local/bin/ion /usr/local/bin/ -COPY --from=nushell /usr/local/bin/* /usr/local/bin/ -COPY --from=mdbook /usr/local/bin/* /usr/local/bin/ -COPY --from=oil /usr/local/bin/* /usr/local/bin/ -COPY --from=starship /usr/local/bin/* /usr/local/bin/ -COPY --from=vivid /usr/local/bin/* /usr/local/bin/ - -ADD .dockerfile/root /root -ADD .dockerfile/usr/local/bin/* /usr/local/bin/ - -ENV TERM xterm -ENTRYPOINT [ "entrypoint.sh" ] diff --git a/vendor/github.com/rsteube/carapace/LICENSE.txt b/vendor/github.com/rsteube/carapace/LICENSE.txt deleted file mode 100644 index 298f0e2..0000000 --- a/vendor/github.com/rsteube/carapace/LICENSE.txt +++ /dev/null @@ -1,174 +0,0 @@ - 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/rsteube/carapace/README.md b/vendor/github.com/rsteube/carapace/README.md deleted file mode 100644 index 8344123..0000000 --- a/vendor/github.com/rsteube/carapace/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# carapace - -[![PkgGoDev](https://pkg.go.dev/badge/github.com/rsteube/carapace)](https://pkg.go.dev/github.com/rsteube/carapace) -[![documentation](https://img.shields.io/badge/‌-documentation-blue?logo=gitbook)](https://rsteube.github.io/carapace/) -[![GoReportCard](https://goreportcard.com/badge/github.com/rsteube/carapace)](https://goreportcard.com/report/github.com/rsteube/carapace) -[![Coverage Status](https://coveralls.io/repos/github/rsteube/carapace/badge.svg?branch=master)](https://coveralls.io/github/rsteube/carapace?branch=master) - -Command argument completion generator for [cobra]. You can read more about it here: _[A pragmatic approach to shell completion](https://dev.to/rsteube/a-pragmatic-approach-to-shell-completion-4gp0)_. - - -Supported shells: -- [Bash](https://www.gnu.org/software/bash/) -- [Elvish](https://elv.sh/) -- [Fish](https://fishshell.com/) -- [Ion](https://doc.redox-os.org/ion-manual/) ([experimental](https://github.com/rsteube/carapace/issues/88)) -- [Nushell](https://www.nushell.sh/) -- [Oil](http://www.oilshell.org/) -- [Powershell](https://microsoft.com/powershell) -- [Tcsh](https://www.tcsh.org/) ([experimental](https://github.com/rsteube/carapace/issues/331)) -- [Xonsh](https://xon.sh/) -- [Zsh](https://www.zsh.org/) - -## Usage - -Calling `carapace.Gen` on the root command is sufficient to enable completion using the [hidden command](https://rsteube.github.io/carapace/carapace/gen/hiddenSubcommand.html). - -```go -import ( - "github.com/rsteube/carapace" -) - -carapace.Gen(rootCmd) -``` - -## Example - -An example implementation can be found in the [example](./example/) folder. - - -## Standalone Mode - -Carapace can also be used to provide completion for arbitrary commands. -See [carapace-bin](https://github.com/rsteube/carapace-bin) for examples. - -## Related Projects - -- [carapace-bin](https://github.com/rsteube/carapace-bin) multi-shell multi-command argument completer -- [carapace-bridge](https://github.com/rsteube/carapace-bridge) completion bridge -- [carapace-pflag](https://github.com/rsteube/carapace-pflag) Drop-in replacement for spf13/pflag with support for non-posix variants -- [carapace-spec](https://github.com/rsteube/carapace-spec) define simple completions using a spec file -- [carapace-spec-clap](https://github.com/rsteube/carapace-spec-clap) spec generation for clap-rs/clap -- [carapace-spec-kong](https://github.com/rsteube/carapace-spec-kong) spec generation for alecthomas/kong -- [carapace-spec-urfavecli](https://github.com/rsteube/carapace-spec-urfavecli) spec generation for urfave/cli - -[cobra]:https://github.com/spf13/cobra diff --git a/vendor/github.com/rsteube/carapace/action.go b/vendor/github.com/rsteube/carapace/action.go deleted file mode 100644 index 4ad418d..0000000 --- a/vendor/github.com/rsteube/carapace/action.go +++ /dev/null @@ -1,259 +0,0 @@ -package carapace - -import ( - "fmt" - "os" - "runtime" - "time" - - "github.com/rsteube/carapace/internal/cache" - "github.com/rsteube/carapace/internal/common" - pkgcache "github.com/rsteube/carapace/pkg/cache" - "github.com/rsteube/carapace/pkg/style" -) - -// Action indicates how to complete a flag or positional argument. -type Action struct { - meta common.Meta - rawValues common.RawValues - callback CompletionCallback -} - -// ActionMap maps Actions to an identifier. -type ActionMap map[string]Action - -// CompletionCallback is executed during completion of associated flag or positional argument. -type CompletionCallback func(c Context) Action - -// Cache cashes values of a CompletionCallback for given duration and keys. -func (a Action) Cache(timeout time.Duration, keys ...pkgcache.Key) Action { - if a.callback != nil { // only relevant for callback actions - cachedCallback := a.callback - _, file, line, _ := runtime.Caller(1) // generate uid from wherever Cache() was called - a.callback = func(c Context) Action { - cacheFile, err := cache.File(file, line, keys...) - if err != nil { - return cachedCallback(c) - } - - if cached, err := cache.Load(cacheFile, timeout); err == nil { - return Action{meta: cached.Meta, rawValues: cached.Values} - } - - invokedAction := (Action{callback: cachedCallback}).Invoke(c) - if invokedAction.meta.Messages.IsEmpty() { - if cacheFile, err := cache.File(file, line, keys...); err == nil { // regenerate as cache keys might have changed due to invocation - _ = cache.Write(cacheFile, invokedAction.export()) - } - } - return invokedAction.ToA() - } - } - return a -} - -// Invoke executes the callback of an action if it exists (supports nesting). -func (a Action) Invoke(c Context) InvokedAction { - if c.Args == nil { - c.Args = []string{} - } - if c.Env == nil { - c.Env = []string{} - } - if c.Parts == nil { - c.Parts = []string{} - } - - if a.rawValues == nil && a.callback != nil { - result := a.callback(c).Invoke(c) - result.meta.Merge(a.meta) - return result - } - return InvokedAction{a} -} - -// NoSpace disables space suffix for given characters (or all if none are given). -func (a Action) NoSpace(suffixes ...rune) Action { - return ActionCallback(func(c Context) Action { - if len(suffixes) == 0 { - a.meta.Nospace.Add('*') - } - a.meta.Nospace.Add(suffixes...) - return a - }) -} - -// Usage sets the usage. -func (a Action) Usage(usage string, args ...interface{}) Action { - return a.UsageF(func() string { - return fmt.Sprintf(usage, args...) - }) -} - -// Usage sets the usage using a function. -func (a Action) UsageF(f func() string) Action { - return ActionCallback(func(c Context) Action { - if usage := f(); usage != "" { - a.meta.Usage = usage - } - return a - }) -} - -// Style sets the style. -// -// ActionValues("yes").Style(style.Green) -// ActionValues("no").Style(style.Red) -func (a Action) Style(s string) Action { - return a.StyleF(func(_ string, _ style.Context) string { - return s - }) -} - -// Style sets the style using a reference. -// -// ActionValues("value").StyleR(&style.Carapace.Value) -// ActionValues("description").StyleR(&style.Carapace.Value) -func (a Action) StyleR(s *string) Action { - return ActionCallback(func(c Context) Action { - if s != nil { - return a.Style(*s) - } - return a - }) -} - -// Style sets the style using a function. -// -// ActionValues("dir/", "test.txt").StyleF(style.ForPathExt) -// ActionValues("true", "false").StyleF(style.ForKeyword) -func (a Action) StyleF(f func(s string, sc style.Context) string) Action { - return ActionCallback(func(c Context) Action { - invoked := a.Invoke(c) - for index, v := range invoked.rawValues { - invoked.rawValues[index].Style = f(v.Value, c) - } - return invoked.ToA() - }) -} - -// Tag sets the tag. -// -// ActionValues("192.168.1.1", "127.0.0.1").Tag("interfaces"). -func (a Action) Tag(tag string) Action { - return a.TagF(func(value string) string { - return tag - }) -} - -// Tag sets the tag using a function. -// -// ActionValues("192.168.1.1", "127.0.0.1").TagF(func(value string) string { -// return "interfaces" -// }) -func (a Action) TagF(f func(value string) string) Action { - return ActionCallback(func(c Context) Action { - invoked := a.Invoke(c) - for index, v := range invoked.rawValues { - invoked.rawValues[index].Tag = f(v.Value) - } - return invoked.ToA() - }) -} - -// Chdir changes the current working directory to the named directory for the duration of invocation. -func (a Action) Chdir(dir string) Action { - return ActionCallback(func(c Context) Action { - abs, err := c.Abs(dir) - if err != nil { - return ActionMessage(err.Error()) - } - if info, err := os.Stat(abs); err != nil { - return ActionMessage(err.Error()) - } else if !info.IsDir() { - return ActionMessage("not a directory: %v", abs) - } - c.Dir = abs - return a.Invoke(c).ToA() - }) -} - -// Suppress suppresses specific error messages using regular expressions. -func (a Action) Suppress(expr ...string) Action { - return ActionCallback(func(c Context) Action { - invoked := a.Invoke(c) - if err := invoked.meta.Messages.Suppress(expr...); err != nil { - return ActionMessage(err.Error()) - } - return invoked.ToA() - }) -} - -// MultiParts splits values of an Action by given dividers and completes each segment separately. -func (a Action) MultiParts(dividers ...string) Action { - return ActionCallback(func(c Context) Action { - return a.Invoke(c).ToMultiPartsA(dividers...) - }) -} - -// List wraps the Action in an ActionMultiParts with given divider. -func (a Action) List(divider string) Action { - return ActionMultiParts(divider, func(c Context) Action { - return a.Invoke(c).ToA().NoSpace() - }) -} - -// UniqueList wraps the Action in an ActionMultiParts with given divider. -func (a Action) UniqueList(divider string) Action { - return ActionMultiParts(divider, func(c Context) Action { - noSpace := make([]rune, 0) - if runes := []rune(divider); len(runes) > 0 { - noSpace = append(noSpace, runes[len(runes)-1]) - } - noSpace = append(noSpace, []rune(a.meta.Nospace.String())...) - return a.Invoke(c).Filter(c.Parts).ToA().NoSpace([]rune(noSpace)...) - }) -} - -// Prefix adds a prefix to values (only the ones inserted, not the display values). -// -// carapace.ActionValues("melon", "drop", "fall").Prefix("water") -func (a Action) Prefix(prefix string) Action { - return ActionCallback(func(c Context) Action { - return a.Invoke(c).Prefix(prefix).ToA() - }) -} - -// Suffix adds a suffx to values (only the ones inserted, not the display values). -// -// carapace.ActionValues("apple", "melon", "orange").Suffix("juice") -func (a Action) Suffix(suffix string) Action { - return ActionCallback(func(c Context) Action { - return a.Invoke(c).Suffix(suffix).ToA() - }) -} - -// Timeout sets the maximum duration an Action may take to invoke. -// -// carapace.ActionCallback(func(c carapace.Context) carapace.Action { -// time.Sleep(2*time.Second) -// return carapace.ActionValues("done") -// }).Timeout(1*time.Second, carapace.ActionMessage("timeout exceeded")) -func (a Action) Timeout(d time.Duration, alternative Action) Action { - return ActionCallback(func(c Context) Action { - currentChannel := make(chan string, 1) - - var result InvokedAction - go func() { - result = a.Invoke(c) - currentChannel <- "" - }() - - select { - case <-currentChannel: - case <-time.After(d): - return alternative - } - return result.ToA() - }) -} diff --git a/vendor/github.com/rsteube/carapace/batch.go b/vendor/github.com/rsteube/carapace/batch.go deleted file mode 100644 index 91868af..0000000 --- a/vendor/github.com/rsteube/carapace/batch.go +++ /dev/null @@ -1,67 +0,0 @@ -package carapace - -import "sync" - -type ( - batch []Action - invokedBatch []InvokedAction -) - -// Batch creates a batch of Actions that can be invoked in parallel. -func Batch(actions ...Action) batch { - return batch(actions) -} - -// Invoke invokes contained Actions of the batch using goroutines. -func (b batch) Invoke(c Context) invokedBatch { - invokedActions := make([]InvokedAction, len(b)) - functions := make([]func(), len(b)) - - for index, action := range b { - localIndex := index - localAction := action - functions[index] = func() { - invokedActions[localIndex] = localAction.Invoke(c) - } - } - parallelize(functions...) - return invokedActions -} - -// ToA converts the batch to an implicitly merged action which is a shortcut for: -// -// ActionCallback(func(c Context) Action { -// return batch.Invoke(c).Merge().ToA() -// }) -func (b batch) ToA() Action { - return ActionCallback(func(c Context) Action { - return b.Invoke(c).Merge().ToA() - }) -} - -// Merge merges Actions of a batch. -func (b invokedBatch) Merge() InvokedAction { - switch len(b) { - case 0: - return ActionValues().Invoke(Context{}) - case 1: - return b[0] - default: - return b[0].Merge(b[1:]...) - } -} - -// Parallelize parallelizes the function calls (https://stackoverflow.com/a/44402936) -func parallelize(functions ...func()) { - var waitGroup sync.WaitGroup - waitGroup.Add(len(functions)) - - defer waitGroup.Wait() - - for _, function := range functions { - go func(copy func()) { - defer waitGroup.Done() - copy() - }(function) - } -} diff --git a/vendor/github.com/rsteube/carapace/carapace.go b/vendor/github.com/rsteube/carapace/carapace.go deleted file mode 100644 index 6573567..0000000 --- a/vendor/github.com/rsteube/carapace/carapace.go +++ /dev/null @@ -1,117 +0,0 @@ -// Package carapace is a command argument completion generator for spf13/cobra -package carapace - -import ( - "os" - - "github.com/rsteube/carapace/internal/shell" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -// Carapace wraps cobra.Command to define completions. -type Carapace struct { - cmd *cobra.Command -} - -// Gen initialized Carapace for given command. -func Gen(cmd *cobra.Command) *Carapace { - addCompletionCommand(cmd) - storage.bridge(cmd) - - return &Carapace{ - cmd: cmd, - } -} - -// PreRun sets a function to be run before completion. -func (c Carapace) PreRun(f func(cmd *cobra.Command, args []string)) { - if entry := storage.get(c.cmd); entry.prerun != nil { - _f := entry.prerun - entry.prerun = func(cmd *cobra.Command, args []string) { - // TODO yuck - probably best to append to a slice in storage - _f(cmd, args) - f(cmd, args) - } - } else { - entry.prerun = f - } -} - -// PreInvoke sets a function to alter actions before they are invoked. -func (c Carapace) PreInvoke(f func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action) { - if entry := storage.get(c.cmd); entry.preinvoke != nil { - _f := entry.preinvoke - entry.preinvoke = func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action { - return f(cmd, flag, _f(cmd, flag, action)) - } - } else { - entry.preinvoke = f - } -} - -// PositionalCompletion defines completion for positional arguments using a list of Actions. -func (c Carapace) PositionalCompletion(action ...Action) { - storage.get(c.cmd).positional = action -} - -// PositionalAnyCompletion defines completion for any positional arguments not already defined. -func (c Carapace) PositionalAnyCompletion(action Action) { - storage.get(c.cmd).positionalAny = action -} - -// DashCompletion defines completion for positional arguments after dash (`--`) using a list of Actions. -func (c Carapace) DashCompletion(action ...Action) { - storage.get(c.cmd).dash = action -} - -// DashAnyCompletion defines completion for any positional arguments after dash (`--`) not already defined. -func (c Carapace) DashAnyCompletion(action Action) { - storage.get(c.cmd).dashAny = action -} - -// FlagCompletion defines completion for flags using a map consisting of name and Action. -func (c Carapace) FlagCompletion(actions ActionMap) { - if e := storage.get(c.cmd); e.flag == nil { - e.flag = actions - } else { - for name, action := range actions { - e.flag[name] = action - } - } -} - -// Standalone prevents cobra defaults interfering with standalone mode (e.g. implicit help command). -func (c Carapace) Standalone() { - c.cmd.CompletionOptions = cobra.CompletionOptions{ - DisableDefaultCmd: true, - } - // TODO probably needs to be done for each subcommand - // TODO still needed? - if c.cmd.Flag("help") != nil { - c.cmd.Flags().Bool("help", false, "skip") - c.cmd.Flag("help").Hidden = true - } - c.cmd.SetHelpCommand(&cobra.Command{Hidden: true}) -} - -// Snippet creates completion script for given shell. -func (c Carapace) Snippet(name string) (string, error) { - return shell.Snippet(c.cmd, name) -} - -// IsCallback returns true if current program invocation is a callback. -func IsCallback() bool { - return len(os.Args) > 1 && os.Args[1] == "_carapace" -} - -// Test verifies the configuration (e.g. flag name exists) -// -// func TestCarapace(t *testing.T) { -// carapace.Test(t) -// } -func Test(t interface{ Error(args ...interface{}) }) { - for _, e := range storage.check() { - t.Error(e) - } -} diff --git a/vendor/github.com/rsteube/carapace/command.go b/vendor/github.com/rsteube/carapace/command.go deleted file mode 100644 index 6de00c4..0000000 --- a/vendor/github.com/rsteube/carapace/command.go +++ /dev/null @@ -1,107 +0,0 @@ -package carapace - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/rsteube/carapace/internal/uid" - "github.com/rsteube/carapace/pkg/style" - "github.com/spf13/cobra" -) - -func addCompletionCommand(cmd *cobra.Command) { - for _, c := range cmd.Commands() { - if c.Name() == "_carapace" { - return - } - } - - carapaceCmd := &cobra.Command{ - Use: "_carapace", - Hidden: true, - Run: func(cmd *cobra.Command, args []string) { - LOG.Printf("%#v", os.Args) - - if len(args) > 2 && strings.HasPrefix(args[2], "_") { - cmd.Hidden = false - } - - if !cmd.HasParent() { - panic("missing parent command") // this should never happen - } - - if s, err := complete(cmd.Parent(), args); err != nil { - fmt.Fprintln(io.MultiWriter(cmd.OutOrStderr(), LOG.Writer()), err.Error()) - } else { - fmt.Fprintln(io.MultiWriter(cmd.OutOrStdout(), LOG.Writer()), s) - } - }, - FParseErrWhitelist: cobra.FParseErrWhitelist{ - UnknownFlags: true, - }, - DisableFlagParsing: true, - } - - cmd.AddCommand(carapaceCmd) - - Carapace{carapaceCmd}.PositionalCompletion( - ActionStyledValues( - "bash", "#d35673", - "bash-ble", "#c2039a", - "elvish", "#ffd6c9", - "export", style.Default, - "fish", "#7ea8fc", - "ion", "#0e5d6d", - "nushell", "#29d866", - "oil", "#373a36", - "powershell", "#e8a16f", - "spec", style.Default, - "tcsh", "#412f09", - "xonsh", "#a8ffa9", - "zsh", "#efda53", - ), - ActionValues(cmd.Root().Name()), - ) - Carapace{carapaceCmd}.PositionalAnyCompletion( - ActionCallback(func(c Context) Action { - args := []string{"_carapace", "export", ""} - args = append(args, c.Args[2:]...) - args = append(args, c.Value) - return ActionExecCommand(uid.Executable(), args...)(func(output []byte) Action { - if string(output) == "" { - return ActionValues() - } - return ActionImport(output) - }) - }), - ) - - styleCmd := &cobra.Command{ - Use: "style", - Args: cobra.ExactArgs(1), - Run: func(cmd *cobra.Command, args []string) {}, - } - carapaceCmd.AddCommand(styleCmd) - - styleSetCmd := &cobra.Command{ - Use: "set", - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for _, arg := range args { - if splitted := strings.SplitN(arg, "=", 2); len(splitted) == 2 { - if err := style.Set(splitted[0], splitted[1]); err != nil { - fmt.Fprint(cmd.ErrOrStderr(), err.Error()) - } - } else { - fmt.Fprintf(cmd.ErrOrStderr(), "invalid format: '%v'", arg) - } - } - }, - } - styleCmd.AddCommand(styleSetCmd) - Carapace{styleSetCmd}.PositionalAnyCompletion( - ActionStyleConfig(), - ) -} diff --git a/vendor/github.com/rsteube/carapace/compat.go b/vendor/github.com/rsteube/carapace/compat.go deleted file mode 100644 index 69a02fa..0000000 --- a/vendor/github.com/rsteube/carapace/compat.go +++ /dev/null @@ -1,53 +0,0 @@ -package carapace - -import ( - "fmt" - - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -func registerValidArgsFunction(cmd *cobra.Command) { - if cmd.ValidArgsFunction == nil { - cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - action := storage.getPositional(cmd, len(args)).Invoke(Context{Args: args, Value: toComplete}) - return cobraValuesFor(action), cobraDirectiveFor(action) - } - } -} - -func registerFlagCompletion(cmd *cobra.Command) { - cmd.Flags().VisitAll(func(f *pflag.Flag) { - err := cmd.RegisterFlagCompletionFunc(f.Name, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - a := storage.getFlag(cmd, f.Name) - action := a.Invoke(Context{Args: args, Value: toComplete}) - return cobraValuesFor(action), cobraDirectiveFor(action) - }) - if err != nil { - LOG.Printf("failed to register flag completion func: %v", err.Error()) - } - }) -} - -func cobraValuesFor(action InvokedAction) []string { - result := make([]string, len(action.rawValues)) - for index, r := range action.rawValues { - if r.Description != "" { - result[index] = fmt.Sprintf("%v\t%v", r.Value, r.Description) - } else { - result[index] = r.Value - } - } - return result -} - -func cobraDirectiveFor(action InvokedAction) cobra.ShellCompDirective { - directive := cobra.ShellCompDirectiveNoFileComp - for _, val := range action.rawValues { - if action.meta.Nospace.Matches(val.Value) { - directive = directive | cobra.ShellCompDirectiveNoSpace - break - } - } - return directive -} diff --git a/vendor/github.com/rsteube/carapace/complete.go b/vendor/github.com/rsteube/carapace/complete.go deleted file mode 100644 index 62367b6..0000000 --- a/vendor/github.com/rsteube/carapace/complete.go +++ /dev/null @@ -1,78 +0,0 @@ -package carapace - -import ( - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/config" - "github.com/rsteube/carapace/pkg/ps" - "github.com/rsteube/carapace/pkg/style" - "github.com/spf13/cobra" -) - -// Complete can be used by Go programs wishing to produce completions for -// themselves, without passing through shell snippets/output or export formats. -// -// The `onFinalize` function parameter, if non nil, will be called after having -// generated the completions from the given command/tree. This function is generally -// used to reset the command tree, which is needed when the Go program is a shell itself. -// Also, and before calling `onFinalize` if not nil, the completion storage is cleared. -func Complete(cmd *cobra.Command, args []string, onFinalize func()) (common.RawValues, common.Meta) { - // Generate the completion as normally done for an external system shell - // action, current := generate(cmd, args) - action, context := traverse(cmd, args[2:]) - - invoked := action.Invoke(context) - - // And adapt/fetch the results from invoked action - return internalValues(invoked, context.Value, onFinalize) -} - -func complete(cmd *cobra.Command, args []string) (string, error) { - switch len(args) { - case 0: - return Gen(cmd).Snippet(ps.DetermineShell()) - case 1: - return Gen(cmd).Snippet(args[0]) - default: - action, context := traverse(cmd, args[2:]) - if err := config.Load(); err != nil { - action = ActionMessage("failed to load config: " + err.Error()) - } - - return action.Invoke(context).value(args[0], args[len(args)-1]), nil - } -} - -func internalValues(action InvokedAction, current string, onFinalize func()) (common.RawValues, common.Meta) { - unsorted := action.rawValues - sorted := make(common.RawValues, 0) - - // Ensure values are sorted. - unsorted.EachTag(func(_ string, values common.RawValues) { - vals := make(common.RawValues, len(values)) - for index, val := range values { - if !action.meta.Nospace.Matches(val.Value) { - val.Value += " " - } - if val.Style != "" { - val.Style = style.SGR(val.Style) - } - - vals[index] = val - } - sorted = append(sorted, vals...) - }) - - // Merge/filter completions and meta stuff. - filtered := sorted.FilterPrefix(current) - filtered = action.meta.Messages.Integrate(filtered, current) - - // Reset the storage (empty all commands) and run the finalize function, which is - // generally in charge of binding new command instances, with blank flags. - if onFinalize != nil { - storage = make(_storage) - - onFinalize() - } - - return filtered, action.meta -} diff --git a/vendor/github.com/rsteube/carapace/context.go b/vendor/github.com/rsteube/carapace/context.go deleted file mode 100644 index 2cf61c1..0000000 --- a/vendor/github.com/rsteube/carapace/context.go +++ /dev/null @@ -1,148 +0,0 @@ -package carapace - -import ( - "encoding/json" - "fmt" - "os" - "path/filepath" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/shell/zsh" - "github.com/rsteube/carapace/third_party/github.com/drone/envsubst" - "github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs" -) - -// Context provides information during completion. -type Context struct { - // Value contains the value currently being completed (or part of it during an ActionMultiParts). - Value string - // Args contains the positional arguments of current (sub)command (exclusive the one currently being completed). - Args []string - // Parts contains the splitted Value during an ActionMultiParts (exclusive the part currently being completed). - Parts []string - // Env contains environment variables for current context. - Env []string - // Dir contains the working directory for current context. - Dir string - - mockedReplies map[string]string -} - -// NewContext creates a new context for given arguments. -func NewContext(args ...string) Context { - if len(args) == 0 { - args = append(args, "") - } - - context := Context{ - Value: args[len(args)-1], - Args: args[:len(args)-1], - Env: os.Environ(), - } - - if wd, err := os.Getwd(); err == nil { - context.Dir = wd - } - - isGoRun := func() bool { return strings.HasPrefix(os.Args[0], os.TempDir()+"/go-build") } - if value, exists := os.LookupEnv("CARAPACE_SANDBOX"); exists && isGoRun() { - var m common.Mock - _ = json.Unmarshal([]byte(value), &m) - context.Dir = m.Dir - context.mockedReplies = m.Replies - } - return context -} - -// LookupEnv retrieves the value of the environment variable named by the key. -func (c Context) LookupEnv(key string) (string, bool) { - prefix := key + "=" - for i := len(c.Env) - 1; i >= 0; i-- { - if env := c.Env[i]; strings.HasPrefix(env, prefix) { - return strings.SplitN(env, "=", 2)[1], true - } - } - return "", false -} - -// Getenv retrieves the value of the environment variable named by the key. -func (c Context) Getenv(key string) string { - v, _ := c.LookupEnv(key) - return v -} - -// Setenv sets the value of the environment variable named by the key. -func (c *Context) Setenv(key, value string) { - if c.Env == nil { - c.Env = []string{} - } - c.Env = append(c.Env, fmt.Sprintf("%v=%v", key, value)) -} - -// Envsubst replaces ${var} in the string based on environment variables in current context. -func (c Context) Envsubst(s string) (string, error) { - return envsubst.Eval(s, c.Getenv) -} - -// Command returns the Cmd struct to execute the named program with the given arguments. -// Env and Dir are set using the Context. -// See exec.Command for most details. -func (c Context) Command(name string, arg ...string) *execabs.Cmd { - if c.mockedReplies != nil { - if m, err := json.Marshal(append([]string{name}, arg...)); err == nil { - if reply, exists := c.mockedReplies[string(m)]; exists { - return execabs.Command("echo", reply) - } - } - } - - cmd := execabs.Command(name, arg...) - cmd.Env = c.Env - cmd.Dir = c.Dir - return cmd -} - -func expandHome(s string) (string, error) { - if strings.HasPrefix(s, "~") { - if zsh.NamedDirectories.Matches(s) { - return zsh.NamedDirectories.Replace(s), nil - } - - home, err := os.UserHomeDir() - if err != nil { - return "", err - } - s = strings.Replace(s, "~/", home+"/", 1) - } - return s, nil -} - -// Abs returns an absolute representation of path. -func (c Context) Abs(path string) (string, error) { - if !strings.HasPrefix(path, "/") && !strings.HasPrefix(path, "~") { // path is relative - switch c.Dir { - case "": - path = "./" + path - default: - path = c.Dir + "/" + path - } - } - - path, err := expandHome(path) - if err != nil { - return "", err - } - - result, err := filepath.Abs(path) - if err != nil { - return "", err - } - - if strings.HasSuffix(path, "/") && !strings.HasSuffix(result, "/") { - result += "/" - } else if strings.HasSuffix(path, "/.") && !strings.HasSuffix(result, "/.") { - result += "/." - } - return result, nil -} diff --git a/vendor/github.com/rsteube/carapace/defaultActions.go b/vendor/github.com/rsteube/carapace/defaultActions.go deleted file mode 100644 index adfc516..0000000 --- a/vendor/github.com/rsteube/carapace/defaultActions.go +++ /dev/null @@ -1,456 +0,0 @@ -package carapace - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "os" - "os/exec" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/config" - "github.com/rsteube/carapace/internal/export" - "github.com/rsteube/carapace/internal/man" - "github.com/rsteube/carapace/pkg/style" - "github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -// ActionCallback invokes a go function during completion. -func ActionCallback(callback CompletionCallback) Action { - return Action{callback: callback} -} - -// ActionExecCommand invokes given command and transforms its output using given function on success or returns ActionMessage with the first line of stderr if available. -// -// carapace.ActionExecCommand("git", "remote")(func(output []byte) carapace.Action { -// lines := strings.Split(string(output), "\n") -// return carapace.ActionValues(lines[:len(lines)-1]...) -// }) -func ActionExecCommand(name string, arg ...string) func(f func(output []byte) Action) Action { - return func(f func(output []byte) Action) Action { - return ActionExecCommandE(name, arg...)(func(output []byte, err error) Action { - if err != nil { - if exitErr, ok := err.(*exec.ExitError); ok { - if firstLine := strings.SplitN(string(exitErr.Stderr), "\n", 2)[0]; strings.TrimSpace(firstLine) != "" { - err = errors.New(firstLine) - } - } - return ActionMessage(err.Error()) - } - return f(output) - }) - } -} - -// ActionExecCommandE is like ActionExecCommand but with custom error handling. -// -// carapace.ActionExecCommandE("supervisorctl", "--configuration", path, "status")(func(output []byte, err error) carapace.Action { -// if err != nil { -// const NOT_RUNNING = 3 -// if exitErr, ok := err.(*exec.ExitError); !ok || exitErr.ExitCode() != NOT_RUNNING { -// return carapace.ActionMessage(err.Error()) -// } -// } -// return carapace.ActionValues("success") -// }) -func ActionExecCommandE(name string, arg ...string) func(f func(output []byte, err error) Action) Action { - return func(f func(output []byte, err error) Action) Action { - return ActionCallback(func(c Context) Action { - var stdout, stderr bytes.Buffer - cmd := c.Command(name, arg...) - cmd.Stdout = &stdout - cmd.Stderr = &stderr - if err := cmd.Run(); err != nil { - if exitErr, ok := err.(*exec.ExitError); ok { - exitErr.Stderr = stderr.Bytes() // seems this needs to be set manually due to stdout being collected? - } - return f(stdout.Bytes(), err) - } - return f(stdout.Bytes(), nil) - }) - } -} - -// ActionImport parses the json output from export as Action -// -// carapace.Gen(rootCmd).PositionalAnyCompletion( -// carapace.ActionCallback(func(c carapace.Context) carapace.Action { -// args := []string{"_carapace", "export", ""} -// args = append(args, c.Args...) -// args = append(args, c.Value) -// return carapace.ActionExecCommand("command", args...)(func(output []byte) carapace.Action { -// return carapace.ActionImport(output) -// }) -// }), -// ) -func ActionImport(output []byte) Action { - return ActionCallback(func(c Context) Action { - var e export.Export - if err := json.Unmarshal(output, &e); err != nil { - return ActionMessage(err.Error()) - } - return Action{ - rawValues: e.Values, - meta: e.Meta, - } - }) -} - -// ActionExecute executes completion on an internal command -// TODO example. -func ActionExecute(cmd *cobra.Command) Action { - return ActionCallback(func(c Context) Action { - args := []string{"_carapace", "export", cmd.Name()} - args = append(args, c.Args...) - args = append(args, c.Value) - cmd.SetArgs(args) - - Gen(cmd).PreInvoke(func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action { - return ActionCallback(func(_c Context) Action { - _c.Env = c.Env - _c.Dir = c.Dir - return action.Invoke(_c).ToA() - }) - }) - - var stdout, stderr bytes.Buffer - cmd.SetOut(&stdout) - cmd.SetErr(&stderr) - - if err := cmd.Execute(); err != nil { - return ActionMessage(err.Error()) - } - return ActionImport(stdout.Bytes()) - }) -} - -// ActionDirectories completes directories. -func ActionDirectories() Action { - return ActionCallback(func(c Context) Action { - return actionPath([]string{""}, true).Invoke(c).ToMultiPartsA("/").StyleF(style.ForPath) - }).Tag("directories") -} - -// ActionFiles completes files with optional suffix filtering. -func ActionFiles(suffix ...string) Action { - return ActionCallback(func(c Context) Action { - return actionPath(suffix, false).Invoke(c).ToMultiPartsA("/").StyleF(style.ForPath) - }).Tag("files") -} - -// ActionValues completes arbitrary keywords (values). -func ActionValues(values ...string) Action { - return ActionCallback(func(c Context) Action { - vals := make([]common.RawValue, 0, len(values)) - for _, val := range values { - vals = append(vals, common.RawValue{Value: val, Display: val}) - } - return Action{rawValues: vals} - }) -} - -// ActionStyledValues is like ActionValues but also accepts a style. -func ActionStyledValues(values ...string) Action { - return ActionCallback(func(c Context) Action { - if length := len(values); length%2 != 0 { - return ActionMessage("invalid amount of arguments [ActionStyledValues]: %v", length) - } - - vals := make([]common.RawValue, 0, len(values)/2) - for i := 0; i < len(values); i += 2 { - vals = append(vals, common.RawValue{Value: values[i], Display: values[i], Style: values[i+1]}) - } - return Action{rawValues: vals} - }) -} - -// ActionValuesDescribed completes arbitrary key (values) with an additional description (value, description pairs). -func ActionValuesDescribed(values ...string) Action { - return ActionCallback(func(c Context) Action { - if length := len(values); length%2 != 0 { - return ActionMessage("invalid amount of arguments [ActionValuesDescribed]: %v", length) - } - - vals := make([]common.RawValue, 0, len(values)/2) - for i := 0; i < len(values); i += 2 { - vals = append(vals, common.RawValue{Value: values[i], Display: values[i], Description: values[i+1]}) - } - return Action{rawValues: vals} - }) -} - -// ActionStyledValuesDescribed is like ActionValues but also accepts a style. -func ActionStyledValuesDescribed(values ...string) Action { - return ActionCallback(func(c Context) Action { - if length := len(values); length%3 != 0 { - return ActionMessage("invalid amount of arguments [ActionStyledValuesDescribed]: %v", length) - } - - vals := make([]common.RawValue, 0, len(values)/3) - for i := 0; i < len(values); i += 3 { - vals = append(vals, common.RawValue{Value: values[i], Display: values[i], Description: values[i+1], Style: values[i+2]}) - } - return Action{rawValues: vals} - }) -} - -// ActionMessage displays a help messages in places where no completions can be generated. -func ActionMessage(msg string, args ...interface{}) Action { - return ActionCallback(func(c Context) Action { - if len(args) > 0 { - msg = fmt.Sprintf(msg, args...) - } - a := ActionValues().NoSpace() - a.meta.Messages.Add(stripansi.Strip(msg)) - return a - }) -} - -// ActionMultiParts completes multiple parts of words separately where each part is separated by some char (Context.Value is set to the currently completed part during invocation). -func ActionMultiParts(divider string, callback func(c Context) Action) Action { - return ActionCallback(func(c Context) Action { - index := strings.LastIndex(c.Value, string(divider)) - prefix := "" - if len(divider) == 0 { - prefix = c.Value - c.Value = "" - } else if index != -1 { - prefix = c.Value[0 : index+len(divider)] - c.Value = c.Value[index+len(divider):] // update Context.Value to only contain the currently completed part - } - parts := strings.Split(prefix, string(divider)) - if len(parts) > 0 && len(divider) > 0 { - parts = parts[0 : len(parts)-1] - } - c.Parts = parts - - nospace := '*' - if runes := []rune(divider); len(runes) > 0 { - nospace = runes[len(runes)-1] - } - return callback(c).Invoke(c).Prefix(prefix).ToA().NoSpace(nospace) - }) -} - -// ActionStyleConfig completes style configuration -// -// carapace.Value=blue -// carapace.Description=magenta -func ActionStyleConfig() Action { - return ActionMultiParts("=", func(c Context) Action { - switch len(c.Parts) { - case 0: - return ActionMultiParts(".", func(c Context) Action { - switch len(c.Parts) { - case 0: - return ActionValues(config.GetStyleConfigs()...).Invoke(c).Suffix(".").ToA() - - case 1: - fields, err := config.GetStyleFields(c.Parts[0]) - if err != nil { - return ActionMessage(err.Error()) - } - batch := Batch() - for _, field := range fields { - batch = append(batch, ActionStyledValuesDescribed(field.Name, field.Description, field.Style).Tag(field.Tag)) - } - return batch.Invoke(c).Merge().Suffix("=").ToA() - - default: - return ActionValues() - } - }) - case 1: - return ActionMultiParts(",", func(c Context) Action { - return ActionStyles(c.Parts...).Invoke(c).Filter(c.Parts).ToA().NoSpace() - }) - default: - return ActionValues() - } - }) -} - -// Actionstyles completes styles -// -// blue -// bg-magenta -func ActionStyles(styles ...string) Action { - return ActionCallback(func(c Context) Action { - fg := false - bg := false - - for _, s := range styles { - if strings.HasPrefix(s, "bg-") { - bg = true - } - if s == style.Black || - s == style.Red || - s == style.Green || - s == style.Yellow || - s == style.Blue || - s == style.Magenta || - s == style.Cyan || - s == style.White || - s == style.Gray || - s == style.BrightBlack || - s == style.BrightRed || - s == style.BrightGreen || - s == style.BrightYellow || - s == style.BrightBlue || - s == style.BrightMagenta || - s == style.BrightCyan || - s == style.BrightWhite || - strings.HasPrefix(s, "#") || - strings.HasPrefix(s, "color") || - strings.HasPrefix(s, "fg-") { - fg = true - } - } - - batch := Batch() - _s := func(s string) string { - return style.Of(append(styles, s)...) - } - - if !fg { - batch = append(batch, ActionStyledValues( - style.Black, _s(style.Black), - style.Red, _s(style.Red), - style.Green, _s(style.Green), - style.Yellow, _s(style.Yellow), - style.Blue, _s(style.Blue), - style.Magenta, _s(style.Magenta), - style.Cyan, _s(style.Cyan), - style.White, _s(style.White), - style.Gray, _s(style.Gray), - - style.BrightBlack, _s(style.BrightBlack), - style.BrightRed, _s(style.BrightRed), - style.BrightGreen, _s(style.BrightGreen), - style.BrightYellow, _s(style.BrightYellow), - style.BrightBlue, _s(style.BrightBlue), - style.BrightMagenta, _s(style.BrightMagenta), - style.BrightCyan, _s(style.BrightCyan), - style.BrightWhite, _s(style.BrightWhite), - )) - - if strings.HasPrefix(c.Value, "color") { - for i := 0; i <= 255; i++ { - batch = append(batch, ActionStyledValues( - fmt.Sprintf("color%v", i), _s(style.XTerm256Color(uint8(i))), - )) - } - } else { - batch = append(batch, ActionStyledValues("color", style.Of(styles...))) - } - } - - if !bg { - batch = append(batch, ActionStyledValues( - style.BgBlack, _s(style.BgBlack), - style.BgRed, _s(style.BgRed), - style.BgGreen, _s(style.BgGreen), - style.BgYellow, _s(style.BgYellow), - style.BgBlue, _s(style.BgBlue), - style.BgMagenta, _s(style.BgMagenta), - style.BgCyan, _s(style.BgCyan), - style.BgWhite, _s(style.BgWhite), - - style.BgBrightBlack, _s(style.BgBrightBlack), - style.BgBrightRed, _s(style.BgBrightRed), - style.BgBrightGreen, _s(style.BgBrightGreen), - style.BgBrightYellow, _s(style.BgBrightYellow), - style.BgBrightBlue, _s(style.BgBrightBlue), - style.BgBrightMagenta, _s(style.BgBrightMagenta), - style.BgBrightCyan, _s(style.BgBrightCyan), - style.BgBrightWhite, _s(style.BgBrightWhite), - )) - - if strings.HasPrefix(c.Value, "bg-color") { - for i := 0; i <= 255; i++ { - batch = append(batch, ActionStyledValues( - fmt.Sprintf("bg-color%v", i), _s("bg-"+style.XTerm256Color(uint8(i))), - )) - } - } else { - batch = append(batch, ActionStyledValues("bg-color", style.Of(styles...))) - } - } - - batch = append(batch, ActionStyledValues( - style.Bold, _s(style.Bold), - style.Dim, _s(style.Dim), - style.Italic, _s(style.Italic), - style.Underlined, _s(style.Underlined), - style.Blink, _s(style.Blink), - style.Inverse, _s(style.Inverse), - )) - - return batch.ToA() - }).Tag("styles") -} - -// ActionExecutables completes PATH executables -// -// nvim -// chmod -func ActionExecutables() Action { - return ActionCallback(func(c Context) Action { - // TODO allow additional descriptions to be registered somewhere for carapace-bin (key, value,...) - batch := Batch() - manDescriptions := man.Descriptions(c.Value) - dirs := strings.Split(os.Getenv("PATH"), string(os.PathListSeparator)) - for i := len(dirs) - 1; i >= 0; i-- { - batch = append(batch, actionDirectoryExecutables(dirs[i], c.Value, manDescriptions)) - } - return batch.ToA() - }).Tag("executables") -} - -func actionDirectoryExecutables(dir string, prefix string, manDescriptions map[string]string) Action { - return ActionCallback(func(c Context) Action { - if files, err := os.ReadDir(dir); err == nil { - vals := make([]string, 0) - for _, f := range files { - if strings.HasPrefix(f.Name(), prefix) { - if info, err := f.Info(); err == nil && !f.IsDir() && isExecAny(info.Mode()) { - vals = append(vals, f.Name(), manDescriptions[f.Name()], style.ForPath(dir+"/"+f.Name(), c)) - } - } - } - return ActionStyledValuesDescribed(vals...) - } - return ActionValues() - }) -} - -func isExecAny(mode os.FileMode) bool { - return mode&0o111 != 0 -} - -// ActionPositional completes positional arguments for given command ignoring `--` (dash). -// TODO: experimental - likely gives issues with preinvoke (does not have the full args) -// -// carapace.Gen(cmd).DashAnyCompletion( -// carapace.ActionPositional(cmd), -// ) -func ActionPositional(cmd *cobra.Command) Action { - return ActionCallback(func(c Context) Action { - if cmd.ArgsLenAtDash() < 0 { - return ActionMessage("only allowed for dash arguments [ActionPositional]") - } - - c.Args = cmd.Flags().Args() - entry := storage.get(cmd) - - a := entry.positionalAny - if index := len(c.Args); index < len(entry.positional) { - a = entry.positional[len(c.Args)] - } - return a.Invoke(c).ToA() - }) -} diff --git a/vendor/github.com/rsteube/carapace/docker-compose.yml b/vendor/github.com/rsteube/carapace/docker-compose.yml deleted file mode 100644 index 04ea586..0000000 --- a/vendor/github.com/rsteube/carapace/docker-compose.yml +++ /dev/null @@ -1,67 +0,0 @@ -version: '3' - -services: - build: &base - build: . - image: ghcr.io/rsteube/carapace - command: sh -c 'cd /carapace/example && go build -buildvcs=false .' - environment: - TARGET: /carapace/example/example - volumes: - - '.:/carapace/' - - bash: - <<: *base - command: bash - - ble: - <<: *base - command: bash - environment: - BLE: 1 - TARGET: /carapace/example/example - - elvish: - <<: *base - command: elvish - - fish: - <<: *base - command: fish - - ion: - <<: *base - command: ion - - nushell: - <<: *base - command: nu - - oil: - <<: *base - command: osh --completion-display minimal - - powershell: - <<: *base - command: pwsh - - tcsh: - <<: *base - command: tcsh - - xonsh: - <<: *base - command: xonsh - - zsh: - <<: *base - command: zsh - - test: - <<: *base - working_dir: /carapace - command: fish -c "go test -v ./..." - - -volumes: - go: diff --git a/vendor/github.com/rsteube/carapace/go.work b/vendor/github.com/rsteube/carapace/go.work deleted file mode 100644 index 8af5174..0000000 --- a/vendor/github.com/rsteube/carapace/go.work +++ /dev/null @@ -1,6 +0,0 @@ -go 1.19 - -use ( - . - ./example-nonposix -) diff --git a/vendor/github.com/rsteube/carapace/go.work.sum b/vendor/github.com/rsteube/carapace/go.work.sum deleted file mode 100644 index 46640fb..0000000 --- a/vendor/github.com/rsteube/carapace/go.work.sum +++ /dev/null @@ -1,7 +0,0 @@ -github.com/rsteube/carapace-pflag v0.0.4 h1:Onb0cLNLxg1xJr2EsMlBldAI5KkybrvZ89b5cRElZXI= -github.com/rsteube/carapace-pflag v0.0.4/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/rsteube/carapace-pflag v0.0.5 h1:QQC0KnthHMayHsX7B7DxqOkr0B6JSIM0glB+KrSTruU= -github.com/rsteube/carapace-pflag v0.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/rsteube/carapace-pflag v0.1.0 h1:CPJRlj3jbyOnxuMf5pdrM76hEwdQ0STDDmkAHQcGbhg= -github.com/rsteube/carapace-pflag v0.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/vendor/github.com/rsteube/carapace/internal/cache/cache.go b/vendor/github.com/rsteube/carapace/internal/cache/cache.go deleted file mode 100644 index e90ab03..0000000 --- a/vendor/github.com/rsteube/carapace/internal/cache/cache.go +++ /dev/null @@ -1,73 +0,0 @@ -// Package cache provides disk cache for Actions -package cache - -import ( - "crypto/sha1" - "encoding/json" - "errors" - "fmt" - "os" - "strconv" - "strings" - "time" - - "github.com/rsteube/carapace/internal/export" - "github.com/rsteube/carapace/internal/uid" - "github.com/rsteube/carapace/pkg/cache" - "github.com/rsteube/carapace/pkg/xdg" -) - -// Write persistests given values to file as json. -func Write(file string, e export.Export) (err error) { - var m []byte - if m, err = json.Marshal(e); err == nil { - err = os.WriteFile(file, m, 0o600) - } - return -} - -// Load loads values from file unless modification date exceeds timeout. -func Load(file string, timeout time.Duration) (e export.Export, err error) { - var stat os.FileInfo - if stat, err = os.Stat(file); os.IsNotExist(err) || (timeout > 0 && stat.ModTime().Add(timeout).Before(time.Now())) { - err = errors.New("not exists or timeout exceeded") - } else { - var content []byte - if content, err = os.ReadFile(file); err == nil { - err = json.Unmarshal(content, &e) - } - } - return -} - -// CacheDir creates a cache folder for current user and returns the path. -func CacheDir(name string) (dir string, err error) { - var userCacheDir string - if userCacheDir, err = xdg.UserCacheDir(); err == nil { - dir = fmt.Sprintf("%v/carapace/%v/%v", userCacheDir, uid.Executable(), name) - err = os.MkdirAll(dir, 0o700) - } - return -} - -// File returns the cache filename for given values -// TODO cleanup. -func File(callerFile string, callerLine int, keys ...cache.Key) (file string, err error) { - uid := uidKeys(callerFile, strconv.Itoa(callerLine)) - ids := make([]string, 0) - for _, key := range keys { - id, err := key() - if err != nil { - return "", err - } - ids = append(ids, id) - } - if dir, err := CacheDir(uid); err == nil { - file = dir + "/" + uidKeys(ids...) - } - return -} - -func uidKeys(keys ...string) string { - return fmt.Sprintf("%x", sha1.Sum([]byte(strings.Join(keys, "\001")))) -} diff --git a/vendor/github.com/rsteube/carapace/internal/common/dash.go b/vendor/github.com/rsteube/carapace/internal/common/dash.go deleted file mode 100644 index 0787e09..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/dash.go +++ /dev/null @@ -1,10 +0,0 @@ -package common - -import "github.com/spf13/cobra" - -// IsDash checks if command contains a dash disabling flag parsing -// -// example action positional1 -- dash1 dash2 -func IsDash(cmd *cobra.Command) bool { - return cmd.ArgsLenAtDash() != -1 -} diff --git a/vendor/github.com/rsteube/carapace/internal/common/group.go b/vendor/github.com/rsteube/carapace/internal/common/group.go deleted file mode 100644 index abdc309..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/group.go +++ /dev/null @@ -1,35 +0,0 @@ -package common - -import ( - "fmt" - - "github.com/rsteube/carapace/pkg/style" - "github.com/spf13/cobra" -) - -type Group struct { - Cmd *cobra.Command -} - -func (g Group) Tag() string { - tag := "commands" - if id := g.Cmd.GroupID; id != "" { - tag = fmt.Sprintf("%v %v", id, tag) - } else if len(g.Cmd.Parent().Groups()) != 0 { - tag = "other commands" - } - return tag -} - -func (g Group) Style() string { - if g.Cmd.Parent() == nil || g.Cmd.Parent().Groups() == nil { - return style.Default - } - - for index, group := range g.Cmd.Parent().Groups() { - if group.ID == g.Cmd.GroupID { - return style.Carapace.Highlight(index) - } - } - return style.Default -} diff --git a/vendor/github.com/rsteube/carapace/internal/common/message.go b/vendor/github.com/rsteube/carapace/internal/common/message.go deleted file mode 100644 index e183c61..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/message.go +++ /dev/null @@ -1,146 +0,0 @@ -package common - -import ( - "encoding/json" - "fmt" - "regexp" - "sort" - "strings" - - "github.com/rsteube/carapace/pkg/style" -) - -type Messages struct { - messages map[string]bool -} - -func (m *Messages) init() { - if m.messages == nil { - m.messages = make(map[string]bool) - } -} - -func (m Messages) IsEmpty() bool { - // TODO replacement for Action.skipCache - does this need to consider suppressed messages or is this fine? - return len(m.messages) == 0 -} - -func (m *Messages) Add(s string) { - m.init() - m.messages[s] = true -} - -func (m Messages) Get() []string { - messages := make([]string, 0) - for message := range m.messages { - messages = append(messages, message) - } - sort.Strings(messages) - return messages -} - -func (m *Messages) Suppress(expr ...string) error { - m.init() - - for _, e := range expr { - r, err := regexp.Compile(e) - if err != nil { - return err - } - - for key := range m.messages { - if r.MatchString(key) { - delete(m.messages, key) - } - } - } - return nil -} - -func (m *Messages) Merge(other Messages) { - if other.messages == nil { - return - } - - for key := range other.messages { - m.Add(key) - } -} - -func (m Messages) Integrate(values RawValues, prefix string) RawValues { - m.init() - - if len(m.messages) == 0 { - return values - } - - sorted := make([]string, 0) - for message := range m.messages { - sorted = append(sorted, message) - } - sort.Strings(sorted) - - switch { - case strings.HasSuffix(prefix, "ERR"): - prefix = strings.TrimSuffix(prefix, "ERR") - case strings.HasSuffix(prefix, "ER"): - prefix = strings.TrimSuffix(prefix, "ER") - case strings.HasSuffix(prefix, "E"): - prefix = strings.TrimSuffix(prefix, "E") - } - - i := 0 - for _, message := range sorted { - value := prefix + "ERR" - display := "ERR" - for { - if i > 0 { - value = fmt.Sprintf("%vERR%v", prefix, i) - display = fmt.Sprintf("ERR%v", i) - } - i += 1 - - if !values.contains(value) { - break - } - } - - values = append(values, RawValue{ - Value: value, - Display: display, - Description: message, - Style: style.Carapace.Error, - }) - } - - if len(values) == 1 { - values = append(values, RawValue{ - Value: prefix + "_", - Display: "_", - Description: "", - Style: style.Default, - }) - } - sort.Sort(ByDisplay(values)) - return values -} - -func (m Messages) MarshalJSON() ([]byte, error) { - var result []string = make([]string, 0, len(m.messages)) - for key := range m.messages { - result = append(result, key) - } - sort.Strings(result) - return json.Marshal(&result) -} - -func (m *Messages) UnmarshalJSON(data []byte) (err error) { - var result []string - if err = json.Unmarshal(data, &result); err != nil { - return err - } - for _, item := range result { - m.Add(item) - } - return -} diff --git a/vendor/github.com/rsteube/carapace/internal/common/meta.go b/vendor/github.com/rsteube/carapace/internal/common/meta.go deleted file mode 100644 index 953b43c..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/meta.go +++ /dev/null @@ -1,15 +0,0 @@ -package common - -type Meta struct { - Messages Messages `json:"messages"` - Nospace SuffixMatcher `json:"nospace"` - Usage string `json:"usage"` -} - -func (m *Meta) Merge(other Meta) { - if other.Usage != "" { - m.Usage = other.Usage - } - m.Nospace.Merge(other.Nospace) - m.Messages.Merge(other.Messages) -} diff --git a/vendor/github.com/rsteube/carapace/internal/common/mock.go b/vendor/github.com/rsteube/carapace/internal/common/mock.go deleted file mode 100644 index 8ef8dd9..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/mock.go +++ /dev/null @@ -1,6 +0,0 @@ -package common - -type Mock struct { - Dir string - Replies map[string]string -} diff --git a/vendor/github.com/rsteube/carapace/internal/common/suffix.go b/vendor/github.com/rsteube/carapace/internal/common/suffix.go deleted file mode 100644 index d4ae4b9..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/suffix.go +++ /dev/null @@ -1,63 +0,0 @@ -package common - -import ( - "encoding/json" - "sort" - "strings" -) - -type SuffixMatcher struct { - string -} - -func (sm *SuffixMatcher) Add(suffixes ...rune) { - if strings.Contains(sm.string, "*") || strings.Contains(string(suffixes), "*") { - sm.string = "*" - return - } - - unique := []rune(sm.string) - for _, r := range suffixes { - if !strings.Contains(sm.string, string(r)) { - unique = append(unique, r) - } - } - sort.Sort(ByRune(unique)) - sm.string = string(unique) -} - -func (sm *SuffixMatcher) Merge(other SuffixMatcher) { - for _, r := range other.string { - sm.Add(r) - } -} - -func (sm SuffixMatcher) Matches(s string) bool { - for _, r := range sm.string { - if r == '*' || strings.HasSuffix(s, string(r)) { - return true - } - } - return false -} - -func (sm SuffixMatcher) String() string { - return sm.string -} - -func (sm SuffixMatcher) MarshalJSON() ([]byte, error) { - return json.Marshal(sm.string) -} - -func (sm *SuffixMatcher) UnmarshalJSON(data []byte) (err error) { - if err = json.Unmarshal(data, &sm.string); err != nil { - return err - } - return -} - -type ByRune []rune - -func (r ByRune) Len() int { return len(r) } -func (r ByRune) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r ByRune) Less(i, j int) bool { return r[i] < r[j] } diff --git a/vendor/github.com/rsteube/carapace/internal/common/value.go b/vendor/github.com/rsteube/carapace/internal/common/value.go deleted file mode 100644 index 2a25640..0000000 --- a/vendor/github.com/rsteube/carapace/internal/common/value.go +++ /dev/null @@ -1,130 +0,0 @@ -// Package common code -package common - -import ( - "sort" - "strings" - - "github.com/rsteube/carapace/pkg/style" -) - -// FromInvokedAction provides access to RawValues within an InvokedAction. -// It is intended for testing purposes in Sandbox (circumventing dependency issues). -var FromInvokedAction func(action interface{}) (Meta, RawValues) - -// RawValue represents a completion candidate. -type RawValue struct { - Value string `json:"value"` - Display string `json:"display"` - Description string `json:"description,omitempty"` - Style string `json:"style,omitempty"` - Tag string `json:"tag,omitempty"` -} - -// TrimmedDescription returns the trimmed description. -func (r RawValue) TrimmedDescription() string { - maxLength := 80 - description := strings.SplitN(r.Description, "\n", 2)[0] - description = strings.TrimSpace(description) - if len([]rune(description)) > maxLength { - description = string([]rune(description)[:maxLength-3]) + "..." - } - return description -} - -// RawValues is an alias for []RawValue. -type RawValues []RawValue - -// RawValuesFrom creates RawValues from given values. -func RawValuesFrom(values ...string) RawValues { - rawValues := make([]RawValue, len(values)) - for index, val := range values { - rawValues[index] = RawValue{Value: val, Display: val, Style: style.Default} - } - return rawValues -} - -func (r RawValues) Unique() RawValues { - uniqueRawValues := make(map[string]RawValue) - for _, value := range r { - uniqueRawValues[value.Value] = value - } - - rawValues := make([]RawValue, 0, len(uniqueRawValues)) - for _, value := range uniqueRawValues { - rawValues = append(rawValues, value) - } - sort.Sort(ByDisplay(rawValues)) - return rawValues -} - -func (r RawValues) contains(s string) bool { - for _, value := range r { - if value.Value == s { - return true - } - } - return false -} - -// Filter filters values. -func (r RawValues) Filter(values ...string) RawValues { - toremove := make(map[string]bool) - for _, v := range values { - toremove[v] = true - } - filtered := make([]RawValue, 0) - for _, rawValue := range r { - if _, ok := toremove[rawValue.Value]; !ok { - filtered = append(filtered, rawValue) - } - } - return filtered -} - -// FilterPrefix filters values with given prefix. -func (r RawValues) FilterPrefix(prefix string) RawValues { - filtered := make(RawValues, 0) - for _, r := range r { - if strings.HasPrefix(r.Value, prefix) { - filtered = append(filtered, r) - } - } - return filtered -} - -func (r RawValues) EachTag(f func(tag string, values RawValues)) { - tags := make([]string, 0) - tagGroups := make(map[string]RawValues) - for _, val := range r { - if _, exists := tagGroups[val.Tag]; !exists { - tagGroups[val.Tag] = make(RawValues, 0) - tags = append(tags, val.Tag) - } - tagGroups[val.Tag] = append(tagGroups[val.Tag], val) - } - - // tags := make([]string, 0) - // for tag := range tagGroups { - // tags = append(tags, tag) - // } - sort.Strings(tags) - - for _, tag := range tags { - f(tag, tagGroups[tag]) - } -} - -// ByValue alias to filter by value. -type ByValue []RawValue - -func (a ByValue) Len() int { return len(a) } -func (a ByValue) Less(i, j int) bool { return a[i].Value < a[j].Value } -func (a ByValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -// ByDisplay alias to filter by display. -type ByDisplay []RawValue - -func (a ByDisplay) Len() int { return len(a) } -func (a ByDisplay) Less(i, j int) bool { return a[i].Display < a[j].Display } -func (a ByDisplay) Swap(i, j int) { a[i], a[j] = a[j], a[i] } diff --git a/vendor/github.com/rsteube/carapace/internal/config/config.go b/vendor/github.com/rsteube/carapace/internal/config/config.go deleted file mode 100644 index 90fc3ca..0000000 --- a/vendor/github.com/rsteube/carapace/internal/config/config.go +++ /dev/null @@ -1,142 +0,0 @@ -package config - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "reflect" - "strings" - - "github.com/rsteube/carapace/pkg/xdg" -) - -type configMap map[string]interface{} - -func (c configMap) Keys() []string { - keys := make([]string, 0) - for k := range c { - keys = append(keys, k) - } - return keys -} - -type Field struct { - Name string - Description string - Style string - Tag string -} - -func (c configMap) Fields(name string) ([]Field, error) { - if i, ok := c[name]; ok { - fields := make([]Field, 0) - t := reflect.TypeOf(i).Elem() - v := reflect.ValueOf(i).Elem() - for index := 0; index < t.NumField(); index++ { - field := t.Field(index) - if field.Type.Name() != "string" { - return nil, fmt.Errorf("invalid field type [name: '%v', type: '%v']", field.Name, field.Type.Name()) - } - fields = append(fields, Field{field.Name, field.Tag.Get("desc"), v.FieldByName(field.Name).String(), field.Tag.Get("tag")}) - } - return fields, nil - } - return nil, fmt.Errorf("unknown config: '%v'", name) -} - -var config = struct { - Styles configMap -}{ - Styles: make(configMap), -} - -func RegisterStyle(name string, i interface{}) { - config.Styles[name] = i -} - -func Load() error { - if err := load("styles", config.Styles); err != nil { - return err - } - return nil -} - -func load(name string, c configMap) error { - if dir, err := xdg.UserConfigDir(); err == nil { - content, err := os.ReadFile(fmt.Sprintf("%v/carapace/%v.json", dir, name)) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return err - } - - var unmarshalled map[string]map[string]string - if err := json.Unmarshal(content, &unmarshalled); err != nil { - return err - } - - for key, value := range unmarshalled { - if s, ok := c[key]; ok { - elem := reflect.ValueOf(s).Elem() - for k, v := range value { - if field := elem.FieldByName(k); field != (reflect.Value{}) { - field.SetString(v) - } - } - } - } - } - return nil -} - -func GetStyleConfigs() []string { return config.Styles.Keys() } -func GetStyleFields(name string) ([]Field, error) { return config.Styles.Fields(name) } -func SetStyle(key, value string) error { - return set("styles", key, strings.Replace(value, ",", " ", -1)) -} - -func set(name, key, value string) error { - dir, err := xdg.UserConfigDir() - if err != nil { - return err - } - - file := fmt.Sprintf("%v/carapace/%v.json", dir, name) - content, err := os.ReadFile(file) - if err != nil { - if !os.IsNotExist(err) { - return err - } - if err := os.MkdirAll(filepath.Dir(file), os.ModePerm); err != nil { - return err - } - content = []byte("{}") - } - - var config map[string]map[string]string - if err := json.Unmarshal(content, &config); err != nil { - return err - } - - if splitted := strings.Split(key, "."); len(splitted) != 2 { - return errors.New("invalid key") - } else { - if _, ok := config[splitted[0]]; !ok { - config[splitted[0]] = make(map[string]string, 0) - } - if strings.TrimSpace(value) == "" { - delete(config[splitted[0]], splitted[1]) - } else { - config[splitted[0]][splitted[1]] = value - } - } - - marshalled, err := json.MarshalIndent(config, "", " ") - if err != nil { - return err - } - return os.WriteFile(file, marshalled, os.ModePerm) -} diff --git a/vendor/github.com/rsteube/carapace/internal/config/env.go b/vendor/github.com/rsteube/carapace/internal/config/env.go deleted file mode 100644 index 02a0e9a..0000000 --- a/vendor/github.com/rsteube/carapace/internal/config/env.go +++ /dev/null @@ -1,8 +0,0 @@ -package config - -import "os" - -func IsLenient() (lenient bool) { - _, lenient = os.LookupEnv("CARAPACE_LENIENT") - return -} diff --git a/vendor/github.com/rsteube/carapace/internal/export/export.go b/vendor/github.com/rsteube/carapace/internal/export/export.go deleted file mode 100644 index 61df619..0000000 --- a/vendor/github.com/rsteube/carapace/internal/export/export.go +++ /dev/null @@ -1,39 +0,0 @@ -package export - -import ( - "encoding/json" - "runtime/debug" - "sort" - - "github.com/rsteube/carapace/internal/common" -) - -type Export struct { - Version string `json:"version"` - common.Meta - Values common.RawValues `json:"values"` -} - -func (e Export) MarshalJSON() ([]byte, error) { - sort.Sort(common.ByValue(e.Values)) - return json.Marshal(&struct { - Version string `json:"version"` - common.Meta - Values common.RawValues `json:"values"` - }{ - Version: version(), - Meta: e.Meta, - Values: e.Values, - }) -} - -func version() string { - if info, ok := debug.ReadBuildInfo(); ok { - for _, dep := range info.Deps { - if dep.Path == "github.com/rsteube/carapace" { - return dep.Version - } - } - } - return "unknown" -} diff --git a/vendor/github.com/rsteube/carapace/internal/man/man.go b/vendor/github.com/rsteube/carapace/internal/man/man.go deleted file mode 100644 index a4dabab..0000000 --- a/vendor/github.com/rsteube/carapace/internal/man/man.go +++ /dev/null @@ -1,30 +0,0 @@ -package man - -import ( - "regexp" - "strings" - - "github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs" -) - -// Descriptions returns manpage descriptions for commands matching given prefix. -func Descriptions(s string) (descriptions map[string]string) { - descriptions = make(map[string]string) - if strings.HasPrefix(s, ".") || strings.HasPrefix(s, "~") || strings.HasPrefix(s, "/") { - return - } - - output, err := execabs.Command("man", "--names-only", "-k", "^"+s).Output() - if err != nil { - return - } - - r := regexp.MustCompile(`^(?P[^ ]+) [^-]+- (?P.*)$`) - lines := strings.Split(string(output), "\n") - for _, line := range lines { - if matches := r.FindStringSubmatch(line); len(matches) > 2 { - descriptions[matches[1]] = matches[2] - } - } - return -} diff --git a/vendor/github.com/rsteube/carapace/internal/pflagfork/flag.go b/vendor/github.com/rsteube/carapace/internal/pflagfork/flag.go deleted file mode 100644 index 1fb3ff5..0000000 --- a/vendor/github.com/rsteube/carapace/internal/pflagfork/flag.go +++ /dev/null @@ -1,160 +0,0 @@ -package pflagfork - -import ( - "fmt" - "reflect" - "strings" - - "github.com/rsteube/carapace/pkg/style" - "github.com/spf13/pflag" -) - -// mode defines how flags are represented. -type mode int - -const ( - Default mode = iota // default behaviour - ShorthandOnly // only the shorthand should be used - NameAsShorthand // non-posix mode where the name is also added as shorthand (single `-` prefix) -) - -type Flag struct { - *pflag.Flag -} - -func (f Flag) Nargs() int { - if field := reflect.ValueOf(f.Flag).Elem().FieldByName("Nargs"); field.IsValid() && field.Kind() == reflect.Int { - return int(field.Int()) - } - return 0 -} - -func (f Flag) Mode() mode { - if field := reflect.ValueOf(f.Flag).Elem().FieldByName("Mode"); field.IsValid() && field.Kind() == reflect.Int { - return mode(field.Int()) - } - return Default -} - -func (f Flag) OptargDelimiter() rune { - if field := reflect.ValueOf(f.Flag).Elem().FieldByName("OptargDelimiter"); field.IsValid() && field.Kind() == reflect.Int32 { - return (rune(field.Int())) - } - return '=' -} - -func (f Flag) IsRepeatable() bool { - if strings.Contains(f.Value.Type(), "Slice") || - strings.Contains(f.Value.Type(), "Array") || - f.Value.Type() == "count" { - return true - } - return false -} - -func (f Flag) Split(arg string) (prefix, optarg string) { - delimiter := string(f.OptargDelimiter()) - splitted := strings.SplitN(arg, delimiter, 2) - return splitted[0] + delimiter, splitted[1] -} - -func (f Flag) Matches(arg string, posix bool) bool { - if !strings.HasPrefix(arg, "-") { // not a flag - return false - } - - switch { - - case strings.HasPrefix(arg, "--"): - name := strings.TrimPrefix(arg, "--") - name = strings.SplitN(name, string(f.OptargDelimiter()), 2)[0] - - switch f.Mode() { - case ShorthandOnly, NameAsShorthand: - return false - default: - return name == f.Name - } - - case !posix: - name := strings.TrimPrefix(arg, "-") - name = strings.SplitN(name, string(f.OptargDelimiter()), 2)[0] - - if name == "" { - return false - } - - switch f.Mode() { - case ShorthandOnly: - return name == f.Shorthand - default: - return name == f.Name || name == f.Shorthand - } - - default: - if f.Shorthand != "" { - return strings.HasSuffix(arg, f.Shorthand) - } - return false - } -} - -func (f Flag) TakesValue() bool { - switch f.Value.Type() { - case "bool", "boolSlice", "count": - return false - default: - return true - } -} - -func (f Flag) IsOptarg() bool { - return f.NoOptDefVal != "" -} - -func (f Flag) Style() string { - switch { - case !f.TakesValue(): - return style.Carapace.FlagNoArg - case f.IsOptarg(): - return style.Carapace.FlagOptArg - case f.Nargs() != 0: - return style.Carapace.FlagMultiArg - default: - return style.Carapace.FlagArg - } -} - -func (f Flag) Definition() string { - var definition string - switch f.Mode() { - case ShorthandOnly: - definition = fmt.Sprintf("-%v", f.Shorthand) - case NameAsShorthand: - definition = fmt.Sprintf("-%v, -%v", f.Shorthand, f.Name) - default: - switch f.Shorthand { - case "": - definition = fmt.Sprintf("--%v", f.Name) - default: - definition = fmt.Sprintf("-%v, --%v", f.Shorthand, f.Name) - } - } - - if f.IsRepeatable() { - definition += "*" - } - - switch { - case f.IsOptarg(): - switch f.Value.Type() { - case "bool", "boolSlice", "count": - default: - definition += "?" - } - case f.TakesValue(): - definition += "=" - } - - return definition -} diff --git a/vendor/github.com/rsteube/carapace/internal/pflagfork/flagset.go b/vendor/github.com/rsteube/carapace/internal/pflagfork/flagset.go deleted file mode 100644 index 53b3aae..0000000 --- a/vendor/github.com/rsteube/carapace/internal/pflagfork/flagset.go +++ /dev/null @@ -1,60 +0,0 @@ -package pflagfork - -import ( - "reflect" - "regexp" - "strings" - - "github.com/spf13/pflag" -) - -type FlagSet struct { - *pflag.FlagSet -} - -func (f FlagSet) IsPosix() bool { - if method := reflect.ValueOf(f.FlagSet).MethodByName("IsPosix"); method.IsValid() { - if values := method.Call([]reflect.Value{}); len(values) == 1 && values[0].Kind() == reflect.Bool { - return values[0].Bool() - } - } - return true -} - -func (f FlagSet) IsShorthandSeries(arg string) bool { - re := regexp.MustCompile("^-(?P[^-=]+)") - return re.MatchString(arg) && f.IsPosix() -} - -func (f FlagSet) IsMutuallyExclusive(flag *pflag.Flag) bool { - if groups, ok := flag.Annotations["cobra_annotation_mutually_exclusive"]; ok { - for _, group := range groups { - for _, name := range strings.Split(group, " ") { - if other := f.Lookup(name); other != nil && other.Changed { - return true - } - } - } - } - return false -} - -func (f *FlagSet) VisitAll(fn func(*Flag)) { - f.FlagSet.VisitAll(func(flag *pflag.Flag) { - fn(&Flag{flag}) - }) -} - -func (fs FlagSet) LookupArg(arg string) (result *Flag) { - isPosix := fs.IsPosix() - fs.VisitAll(func(f *Flag) { - if result != nil { - return - } - - if f.Matches(arg, isPosix) { - result = f - } - }) - return -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/bash/action.go b/vendor/github.com/rsteube/carapace/internal/shell/bash/action.go deleted file mode 100644 index 9607a60..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/bash/action.go +++ /dev/null @@ -1,115 +0,0 @@ -package bash - -import ( - "fmt" - "os" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, - "\t", ``, -) - -var quoter = strings.NewReplacer( - // seems readline provides quotation only for the filename completion (which would add suffixes) so do that here - `&`, `\&`, - `<`, `\<`, - `>`, `\>`, - "`", "\\`", - `'`, `\'`, - `"`, `\"`, - `{`, `\{`, - `}`, `\}`, - `$`, `\$`, - `#`, `\#`, - `|`, `\|`, - `?`, `\?`, - `(`, `\(`, - `)`, `\)`, - `;`, `\;`, - ` `, `\ `, - `[`, `\[`, - `]`, `\]`, - `*`, `\*`, - `\`, `\\`, -) - -func commonPrefix(a, b string) string { - i := 0 - for i < len(a) && i < len(b) && a[i] == b[i] { - i++ - } - return a[0:i] -} - -func commonDisplayPrefix(values ...common.RawValue) (prefix string) { - for index, val := range values { - if index == 0 { - prefix = val.Display - } else { - prefix = commonPrefix(prefix, val.Display) - } - } - return -} - -func commonValuePrefix(values ...common.RawValue) (prefix string) { - for index, val := range values { - if index == 0 { - prefix = val.Value - } else { - prefix = commonPrefix(prefix, val.Value) - } - } - return -} - -// ActionRawValues formats values for bash. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - lastSegment := currentWord // last segment of currentWord split by COMP_WORDBREAKS - - for valueIndex, value := range values { - // TODO optimize - if wordbreaks, ok := os.LookupEnv("COMP_WORDBREAKS"); ok { - wordbreaks = strings.Replace(wordbreaks, " ", "", -1) - if index := strings.LastIndexAny(currentWord, wordbreaks); index != -1 { - values[valueIndex].Value = strings.TrimPrefix(value.Value, currentWord[:index+1]) - lastSegment = currentWord[index+1:] - } - } - } - - if len(values) > 1 && commonDisplayPrefix(values...) != "" { - // When all display values have the same prefix bash will insert is as partial completion (which skips prefixes/formatting). - if valuePrefix := commonValuePrefix(values...); lastSegment != valuePrefix { - // replace values with common value prefix - values = common.RawValuesFrom(commonValuePrefix(values...)) - } else { - // prevent insertion of partial display values by prefixing one with space - values[0].Display = " " + values[0].Display - } - meta.Nospace.Add('*') - } - - vals := make([]string, len(values)) - for index, val := range values { - if len(values) == 1 { - vals[index] = quoter.Replace(sanitizer.Replace(val.Value)) - if !meta.Nospace.Matches(val.Value) { - vals[index] = val.Value + " " - } - - } else { - if val.Description != "" { - vals[index] = fmt.Sprintf("%v (%v)", val.Display, sanitizer.Replace(val.TrimmedDescription())) - } else { - vals[index] = val.Display - } - } - } - return strings.Join(vals, "\n") -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/bash/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/bash/snippet.go deleted file mode 100644 index ca30645..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/bash/snippet.go +++ /dev/null @@ -1,29 +0,0 @@ -// Package bash provides bash completion -package bash - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the bash completion script. -func Snippet(cmd *cobra.Command) string { - result := fmt.Sprintf(`#!/bin/bash -_%v_completion() { - export COMP_WORDBREAKS - - local compline="${COMP_LINE:0:${COMP_POINT}}" - local IFS=$'\n' - mapfile -t COMPREPLY < <(echo "$compline" | sed -e "s/ \$/ ''/" -e 's/"/\"/g' | xargs %v _carapace bash) - [[ "${COMPREPLY[*]}" == "" ]] && COMPREPLY=() # fix for mapfile creating a non-empty array from empty command output - - compopt -o nospace -} - -complete -F _%v_completion %v -`, cmd.Name(), uid.Executable(), cmd.Name(), cmd.Name()) - - return result -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/bash_ble/action.go b/vendor/github.com/rsteube/carapace/internal/shell/bash_ble/action.go deleted file mode 100644 index 62dbb8b..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/bash_ble/action.go +++ /dev/null @@ -1,21 +0,0 @@ -package bash_ble - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -// ActionRawValues formats values for bash_ble. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - vals := make([]string, len(values)) - for index, val := range values { - suffix := " " - if meta.Nospace.Matches(val.Value) { - suffix = "" - } - vals[index] = fmt.Sprintf("%v\t%v\x1c%v\x1c%v\x1c%v", val.Value, val.Display, "", suffix, val.TrimmedDescription()) - } - return strings.Join(vals, "\n") -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/bash_ble/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/bash_ble/snippet.go deleted file mode 100644 index bf1c4e7..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/bash_ble/snippet.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package bash_ble provides bash-ble completion -package bash_ble - -import ( - "fmt" - "regexp" - - "github.com/rsteube/carapace/internal/shell/bash" - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the bash-ble completion script. -func Snippet(cmd *cobra.Command) string { - bashSnippet := bash.Snippet(cmd) - bashSnippet = regexp.MustCompile("complete -F [^\n]+").ReplaceAllString(bashSnippet, "") - - result := fmt.Sprintf(` -_%v_completion_ble() { - if [[ ${BLE_ATTACHED-} ]]; then - [[ :$comp_type: == *:auto:* ]] && return - - compopt -o ble/no-default - bleopt complete_menu_style=desc - - local compline="${COMP_LINE:0:${COMP_POINT}}" - local IFS=$'\n' - local c - mapfile -t c < <(echo "$compline" | sed -e "s/ \$/ ''/" -e 's/"/\"/g' | xargs %v _carapace bash-ble) - [[ "${c[*]}" == "" ]] && c=() # fix for mapfile creating a non-empty array from empty command output - - local cand - for cand in "${c[@]}"; do - [ ! -z "$cand" ] && ble/complete/cand/yield mandb "${cand%%$'\t'*}" "${cand##*$'\t'}" - done - else - complete -F _%v_completion %v - fi -} - -complete -F _%v_completion_ble %v -`, cmd.Name(), uid.Executable(), cmd.Name(), cmd.Name(), cmd.Name(), cmd.Name()) - - return bashSnippet + result -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/elvish/action.go b/vendor/github.com/rsteube/carapace/internal/shell/elvish/action.go deleted file mode 100644 index 3a59203..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/elvish/action.go +++ /dev/null @@ -1,77 +0,0 @@ -package elvish - -import ( - "encoding/json" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/pkg/style" - "github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, -) - -func sanitize(values []common.RawValue) []common.RawValue { - for index, v := range values { - (&values[index]).Value = sanitizer.Replace(v.Value) - (&values[index]).Display = sanitizer.Replace(v.Display) - (&values[index]).Description = sanitizer.Replace(v.TrimmedDescription()) - } - return values -} - -type completion struct { - Usage string - Messages common.Messages - DescriptionStyle string - Candidates []complexCandidate -} - -type complexCandidate struct { - Value string - Display string - Description string - CodeSuffix string - Style string -} - -// ActionRawValues formats values for elvish. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - valueStyle := "default" - if s := style.Carapace.Value; s != "" && ui.ParseStyling(s) != nil { - valueStyle = s - } - - descriptionStyle := "default" - if s := style.Carapace.Description; s != "" && ui.ParseStyling(s) != nil { - descriptionStyle = s - } - - vals := make([]complexCandidate, len(values)) - for index, val := range sanitize(values) { - suffix := " " - if meta.Nospace.Matches(val.Value) { - suffix = "" - } - - if val.Style == "" || ui.ParseStyling(val.Style) == nil { - val.Style = valueStyle - } - vals[index] = complexCandidate{Value: val.Value, Display: val.Display, Description: val.Description, CodeSuffix: suffix, Style: val.Style} - } - - if len(values) > 0 { - meta.Usage = "" // TODO edit:notify is persistent, so avoid spamming the user for now - } - - m, _ := json.Marshal(completion{ - Usage: meta.Usage, - Messages: meta.Messages, - DescriptionStyle: descriptionStyle, - Candidates: vals, - }) - return string(m) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/elvish/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/elvish/snippet.go deleted file mode 100644 index 9c5a8b6..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/elvish/snippet.go +++ /dev/null @@ -1,31 +0,0 @@ -// Package elvish provides elvish completion -package elvish - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the elvish completion script. -func Snippet(cmd *cobra.Command) string { - return fmt.Sprintf(`set edit:completion:arg-completer[%v] = {|@arg| - %v _carapace elvish (all $arg) | from-json | each {|completion| - put $completion[Messages] | all (one) | each {|m| - edit:notify (styled "error: " red)$m - } - if (not-eq $completion[Usage] "") { - edit:notify (styled "usage: " $completion[DescriptionStyle])$completion[Usage] - } - put $completion[Candidates] | all (one) | each {|c| - if (eq $c[Description] "") { - edit:complex-candidate $c[Value] &display=(styled $c[Display] $c[Style]) &code-suffix=$c[CodeSuffix] - } else { - edit:complex-candidate $c[Value] &display=(styled $c[Display] $c[Style])(styled " " $completion[DescriptionStyle]" bg-default")(styled "("$c[Description]")" $completion[DescriptionStyle]) &code-suffix=$c[CodeSuffix] - } - } - } -} -`, cmd.Name(), uid.Executable()) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/export/action.go b/vendor/github.com/rsteube/carapace/internal/shell/export/action.go deleted file mode 100644 index 3504347..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/export/action.go +++ /dev/null @@ -1,16 +0,0 @@ -package export - -import ( - "encoding/json" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/export" -) - -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - m, _ := json.Marshal(export.Export{ - Meta: meta, - Values: values, - }) - return string(m) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/export/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/export/snippet.go deleted file mode 100644 index 8314c2f..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/export/snippet.go +++ /dev/null @@ -1,86 +0,0 @@ -// Package export provides command structure export -package export - -import ( - "encoding/json" - - "github.com/rsteube/carapace/internal/pflagfork" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -type command struct { - Name string - Short string - Long string `json:",omitempty"` - Aliases []string `json:",omitempty"` - Commands []command `json:",omitempty"` - LocalFlags []flag `json:",omitempty"` - PersistentFlags []flag `json:",omitempty"` -} - -type flag struct { - Longhand string `json:",omitempty"` - Shorthand string `json:",omitempty"` - Usage string - Type string - NoOptDefVal string `json:",omitempty"` -} - -func convertFlag(f *pflag.Flag) flag { - longhand := "" - if (pflagfork.Flag{Flag: f}).Mode() != pflagfork.ShorthandOnly { - longhand = f.Name - } - - noOptDefVal := "" - if f.Value.Type() != "bool" { - noOptDefVal = f.NoOptDefVal - } - return flag{ - Longhand: longhand, - Shorthand: f.Shorthand, - Usage: f.Usage, - Type: f.Value.Type(), - NoOptDefVal: noOptDefVal, - } -} - -func convert(cmd *cobra.Command) command { - c := command{ - Name: cmd.Name(), - Short: cmd.Short, - Long: cmd.Long, - Aliases: cmd.Aliases, - } - - lflags := make([]flag, 0) - cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { - lflags = append(lflags, convertFlag(f)) - }) - c.LocalFlags = lflags - - pflags := make([]flag, 0) - cmd.PersistentFlags().VisitAll(func(f *pflag.Flag) { - pflags = append(pflags, convertFlag(f)) - }) - c.PersistentFlags = pflags - - subcommands := make([]command, 0) - for _, s := range cmd.Commands() { - if !s.Hidden { - subcommands = append(subcommands, convert(s)) - } - } - c.Commands = subcommands - return c -} - -// Snippet exports the command structure as json. -func Snippet(cmd *cobra.Command) string { - out, err := json.Marshal(convert(cmd)) - if err == nil { - return string(out) - } - return err.Error() -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/fish/action.go b/vendor/github.com/rsteube/carapace/internal/shell/fish/action.go deleted file mode 100644 index 7dbae1b..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/fish/action.go +++ /dev/null @@ -1,23 +0,0 @@ -package fish - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, - "\t", ``, -) - -// ActionRawValues formats values for fish. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - vals := make([]string, len(values)) - for index, val := range values { - vals[index] = fmt.Sprintf("%v\t%v", sanitizer.Replace(val.Value), sanitizer.Replace(val.TrimmedDescription())) - } - return strings.Join(vals, "\n") -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/fish/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/fish/snippet.go deleted file mode 100644 index 75a4875..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/fish/snippet.go +++ /dev/null @@ -1,32 +0,0 @@ -// Package fish provides fish completion -package fish - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the fish completion script. -func Snippet(cmd *cobra.Command) string { - return fmt.Sprintf(`function _%v_quote_suffix - if not commandline -cp | xargs echo 2>/dev/null >/dev/null - if commandline -cp | sed 's/$/"/'| xargs echo 2>/dev/null >/dev/null - echo '"' - else if commandline -cp | sed "s/\$/'/"| xargs echo 2>/dev/null >/dev/null - echo "'" - end - else - echo "" - end -end - -function _%v_callback - commandline -cp | sed "s/\$/"(_%v_quote_suffix)"/" | sed "s/ \$/ ''/" | xargs %v _carapace fish -end - -complete -c %v -f -complete -c '%v' -f -a '(_%v_callback)' -r -`, cmd.Name(), cmd.Name(), cmd.Name(), uid.Executable(), cmd.Name(), cmd.Name(), cmd.Name()) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/ion/action.go b/vendor/github.com/rsteube/carapace/internal/shell/ion/action.go deleted file mode 100644 index 71b20cf..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/ion/action.go +++ /dev/null @@ -1,46 +0,0 @@ -package ion - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, -) - -func sanitize(values []common.RawValue) []common.RawValue { - for index, v := range values { - (&values[index]).Value = sanitizer.Replace(v.Value) - (&values[index]).Display = sanitizer.Replace(v.Display) - (&values[index]).Description = sanitizer.Replace(v.Description) - } - return values -} - -type suggestion struct { - Value string - Display string -} - -// ActionRawValues formats values for ion. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - vals := make([]suggestion, len(values)) - for index, val := range sanitize(values) { - if !meta.Nospace.Matches(val.Value) { - val.Value = val.Value + " " - } - - if val.Description == "" { - vals[index] = suggestion{Value: val.Value, Display: val.Display} - } else { - vals[index] = suggestion{Value: val.Value, Display: fmt.Sprintf(`%v (%v)`, val.Display, val.TrimmedDescription())} - } - } - m, _ := json.Marshal(vals) - return string(m) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/ion/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/ion/snippet.go deleted file mode 100644 index d1f72e2..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/ion/snippet.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package ion provides Ion completion -package ion - -import ( - "github.com/spf13/cobra" -) - -// Snippet creates the ion completion script. -func Snippet(cmd *cobra.Command) string { - return "" -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/nushell/action.go b/vendor/github.com/rsteube/carapace/internal/shell/nushell/action.go deleted file mode 100644 index 361393b..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/nushell/action.go +++ /dev/null @@ -1,46 +0,0 @@ -package nushell - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -type record struct { - Value string `json:"value"` - Description string `json:"description,omitempty"` -} - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, -) - -func sanitize(values []common.RawValue) []common.RawValue { - for index, v := range values { - (&values[index]).Value = sanitizer.Replace(v.Value) - (&values[index]).Display = sanitizer.Replace(v.Display) - (&values[index]).Description = sanitizer.Replace(v.Description) - } - return values -} - -// ActionRawValues formats values for nushell. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - vals := make([]record, len(values)) - for index, val := range sanitize(values) { - if strings.ContainsAny(val.Value, ` {}()[]<>$&"|;#\`+"`") { - val.Value = fmt.Sprintf("'%v'", val.Value) - } - - if !meta.Nospace.Matches(val.Value) { - val.Value = val.Value + " " - } - - vals[index] = record{Value: val.Value, Description: val.TrimmedDescription()} - } - m, _ := json.Marshal(vals) - return string(m) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/nushell/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/nushell/snippet.go deleted file mode 100644 index 72357e4..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/nushell/snippet.go +++ /dev/null @@ -1,28 +0,0 @@ -// Package nushell provides Nushell completion -package nushell - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the nushell completion script. -func Snippet(cmd *cobra.Command) string { - return fmt.Sprintf(`let external_completer = {|spans| - { - $spans.0: { } # default - %v: { %v _carapace nushell $spans | from json } - } | get $spans.0 | each {|it| do $it} -} - -let-env config = { - completions: { - external: { - enable: true - completer: $external_completer - } - } -}`, cmd.Name(), uid.Executable()) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/oil/action.go b/vendor/github.com/rsteube/carapace/internal/shell/oil/action.go deleted file mode 100644 index 2ee5917..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/oil/action.go +++ /dev/null @@ -1,37 +0,0 @@ -package oil - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\t", ``, -) - -const nospaceIndicator = "\001" - -// ActionRawValues formats values for oil. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - vals := make([]string, len(values)) - for index, val := range values { - if meta.Nospace.Matches(val.Value) { - val.Value = val.Value + nospaceIndicator - } - - if len(values) == 1 { - formattedVal := sanitizer.Replace(val.Value) - vals[index] = formattedVal - } else { - if val.Description != "" { - vals[index] = fmt.Sprintf("%v (%v)", val.Value, sanitizer.Replace(val.TrimmedDescription())) - } else { - vals[index] = val.Value - } - } - } - return strings.Join(vals, "\n") -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/oil/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/oil/snippet.go deleted file mode 100644 index 800d474..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/oil/snippet.go +++ /dev/null @@ -1,29 +0,0 @@ -// Package oil provides Oil completion -package oil - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the oil completion script. -func Snippet(cmd *cobra.Command) string { - result := fmt.Sprintf(`#!/bin/osh -_%v_completion() { - local compline="${COMP_LINE:0:${COMP_POINT}}" - local IFS=$'\n' - mapfile -t COMPREPLY < <(echo "$compline" | sed -e "s/ \$/ ''/" -e 's/"/\"/g' | xargs %v _carapace oil) - [[ "${COMPREPLY[@]}" == "" ]] && COMPREPLY=() # fix for mapfile creating a non-empty array from empty command output - [[ ${COMPREPLY[0]} == *[/=@:.,$'\001'] ]] && compopt -o nospace - # TODO use mapfile - # shellcheck disable=SC2206 - [[ ${#COMPREPLY[@]} -eq 1 ]] && COMPREPLY=(${COMPREPLY[@]%%$'\001'}) -} - -complete -F _%v_completion %v -`, cmd.Name(), uid.Executable(), cmd.Name(), cmd.Name()) - - return result -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/powershell/action.go b/vendor/github.com/rsteube/carapace/internal/shell/powershell/action.go deleted file mode 100644 index f1ddb85..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/powershell/action.go +++ /dev/null @@ -1,83 +0,0 @@ -package powershell - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/pkg/style" - "github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui" -) - -var sanitizer = strings.NewReplacer( // TODO - "\n", ``, - "\t", ``, -) - -type completionResult struct { - CompletionText string - ListItemText string - ToolTip string -} - -// CompletionResult doesn't like empty parameters, so just replace with space if needed. -func ensureNotEmpty(s string) string { - if s == "" { - return " " - } - return s -} - -// ActionRawValues formats values for powershell. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - valueStyle := "default" - if s := style.Carapace.Value; s != "" && ui.ParseStyling(s) != nil { - valueStyle = s - } - - descriptionStyle := "default" - if s := style.Carapace.Description; s != "" && ui.ParseStyling(s) != nil { - descriptionStyle = s - } - - vals := make([]completionResult, 0, len(values)) - for _, val := range values { - if val.Value != "" { // must not be empty - any empty `''` parameter in CompletionResult causes an error - val.Value = sanitizer.Replace(val.Value) - - if strings.ContainsAny(val.Value, ` {}()[]*$?\"|<>&(),;#`+"`") { - val.Value = fmt.Sprintf("'%v'", val.Value) - } - - if !meta.Nospace.Matches(val.Value) { - val.Value = val.Value + " " - } - - if val.Style == "" || ui.ParseStyling(val.Style) == nil { - val.Style = valueStyle - } - - listItemText := fmt.Sprintf("`e[21;22;23;24;25;29m`e[%vm%v`e[21;22;23;24;25;29;39;49m", sgr(val.Style), sanitizer.Replace(val.Display)) - if val.Description != "" { - listItemText = listItemText + fmt.Sprintf("`e[%vm `e[%vm(%v)`e[21;22;23;24;25;29;39;49m", sgr(descriptionStyle+" bg-default"), sgr(descriptionStyle), sanitizer.Replace(val.TrimmedDescription())) - } - listItemText = listItemText + "`e[0m" - - vals = append(vals, completionResult{ - CompletionText: val.Value, - ListItemText: ensureNotEmpty(listItemText), - ToolTip: ensureNotEmpty(" "), - }) - } - } - m, _ := json.Marshal(vals) - return string(m) -} - -func sgr(s string) string { - if result := style.SGR(s); result != "" { - return result - } - return "39;49" -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/powershell/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/powershell/snippet.go deleted file mode 100644 index fb70af8..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/powershell/snippet.go +++ /dev/null @@ -1,59 +0,0 @@ -// Package powershell provides powershell completion -package powershell - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the powershell completion script. -func Snippet(cmd *cobra.Command) string { - return fmt.Sprintf(`using namespace System.Management.Automation -using namespace System.Management.Automation.Language -Function _%v_completer { - [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingInvokeExpression", "", Scope="Function", Target="*")] - param($wordToComplete, $commandAst, $cursorPosition) - $commandElements = $commandAst.CommandElements - - # double quoted value works but seems single quoted needs some fixing (e.g. "example 'acti" -> "example acti") - $elems = @() - foreach ($_ in $commandElements) { - if ($_.Extent.StartOffset -gt $cursorPosition) { - break - } - $t = $_.Extent.Text - if ($_.Extent.EndOffset -gt $cursorPosition) { - $t = $t.Substring(0, $_.Extent.Text.get_Length() - ($_.Extent.EndOffset - $cursorPosition)) - } - - if ($t.Substring(0,1) -eq "'"){ - $t = $t.Substring(1) - } - if ($t.get_Length() -gt 0 -and $t.Substring($t.get_Length()-1) -eq "'"){ - $t = $t.Substring(0,$t.get_Length()-1) - } - if ($t.get_Length() -eq 0){ - $t = '""' - } - $elems += $t.replace('`+"`"+`,', ',') # quick fix - } - - $completions = @( - if (!$wordToComplete) { - %v _carapace powershell $($elems| ForEach-Object {$_}) '' | ConvertFrom-Json | ForEach-Object { [CompletionResult]::new($_.CompletionText, $_.ListItemText.replace('`+"`"+`e[', "`+"`"+`e["), [CompletionResultType]::ParameterValue, $_.ToolTip) } - } else { - %v _carapace powershell $($elems| ForEach-Object {$_}) | ConvertFrom-Json | ForEach-Object { [CompletionResult]::new($_.CompletionText, $_.ListItemText.replace('`+"`"+`e[', "`+"`"+`e["), [CompletionResultType]::ParameterValue, $_.ToolTip) } - } - ) - - if ($completions.count -eq 0) { - return "" # prevent default file completion - } - - $completions -} -Register-ArgumentCompleter -Native -CommandName '%v' -ScriptBlock (Get-Item "Function:_%v_completer").ScriptBlock -`, cmd.Name(), uid.Executable(), uid.Executable(), cmd.Name(), cmd.Name()) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/shell.go b/vendor/github.com/rsteube/carapace/internal/shell/shell.go deleted file mode 100644 index fc5e239..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/shell.go +++ /dev/null @@ -1,84 +0,0 @@ -package shell - -import ( - "fmt" - "sort" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/shell/bash" - "github.com/rsteube/carapace/internal/shell/bash_ble" - "github.com/rsteube/carapace/internal/shell/elvish" - "github.com/rsteube/carapace/internal/shell/export" - "github.com/rsteube/carapace/internal/shell/fish" - "github.com/rsteube/carapace/internal/shell/ion" - "github.com/rsteube/carapace/internal/shell/nushell" - "github.com/rsteube/carapace/internal/shell/oil" - "github.com/rsteube/carapace/internal/shell/powershell" - "github.com/rsteube/carapace/internal/shell/spec" - "github.com/rsteube/carapace/internal/shell/tcsh" - "github.com/rsteube/carapace/internal/shell/xonsh" - "github.com/rsteube/carapace/internal/shell/zsh" - "github.com/rsteube/carapace/pkg/ps" - "github.com/spf13/cobra" -) - -// Snippet creates completion script for given shell. -func Snippet(cmd *cobra.Command, shell string) (string, error) { - if shell == "" { - shell = ps.DetermineShell() - } - shellSnippets := map[string]func(cmd *cobra.Command) string{ - "bash": bash.Snippet, - "bash-ble": bash_ble.Snippet, - "export": export.Snippet, - "fish": fish.Snippet, - "elvish": elvish.Snippet, - "ion": ion.Snippet, - "nushell": nushell.Snippet, - "oil": oil.Snippet, - "powershell": powershell.Snippet, - "spec": spec.Snippet, - "tcsh": tcsh.Snippet, - "xonsh": xonsh.Snippet, - "zsh": zsh.Snippet, - } - if s, ok := shellSnippets[shell]; ok { - return s(cmd.Root()), nil - } - - expected := make([]string, 0) - for key := range shellSnippets { - expected = append(expected, key) - } - sort.Strings(expected) - return "", fmt.Errorf("expected one of '%v' [was: %v]", strings.Join(expected, "', '"), shell) -} - -func Value(shell string, value string, meta common.Meta, values common.RawValues) string { // TODO use context instead? - shellFuncs := map[string]func(currentWord string, meta common.Meta, values common.RawValues) string{ - "bash": bash.ActionRawValues, - "bash-ble": bash_ble.ActionRawValues, - "fish": fish.ActionRawValues, - "elvish": elvish.ActionRawValues, - "export": export.ActionRawValues, - "ion": ion.ActionRawValues, - "nushell": nushell.ActionRawValues, - "oil": oil.ActionRawValues, - "powershell": powershell.ActionRawValues, - "tcsh": tcsh.ActionRawValues, - "xonsh": xonsh.ActionRawValues, - "zsh": zsh.ActionRawValues, - } - if f, ok := shellFuncs[shell]; ok { - filtered := values.FilterPrefix(value) - switch shell { - case "elvish", "export", "zsh": // shells with support for showing messages - default: - filtered = meta.Messages.Integrate(filtered, value) - } - sort.Sort(common.ByDisplay(filtered)) - return f(value, meta, filtered) - } - return "" -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/spec/command.go b/vendor/github.com/rsteube/carapace/internal/shell/spec/command.go deleted file mode 100644 index 49eb17d..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/spec/command.go +++ /dev/null @@ -1,18 +0,0 @@ -package spec - -type Command struct { - Name string `yaml:"name"` - Aliases []string `yaml:"aliases,omitempty"` - Description string `yaml:"description,omitempty"` - Group string `yaml:"group,omitempty"` - Flags map[string]string `yaml:"flags,omitempty"` - PersistentFlags map[string]string `yaml:"persistentflags,omitempty"` - Completion struct { - Flag map[string][]string `yaml:"flag,omitempty"` - Positional [][]string `yaml:"positional,omitempty"` - PositionalAny []string `yaml:"positionalany,omitempty"` - Dash [][]string `yaml:"dash,omitempty"` - DashAny []string `yaml:"dashany,omitempty"` - } `yaml:"completion,omitempty"` - Commands []Command `yaml:"commands,omitempty"` -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/spec/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/spec/snippet.go deleted file mode 100644 index d34e2d6..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/spec/snippet.go +++ /dev/null @@ -1,53 +0,0 @@ -// Package spec provides spec file generation for use with carapace-bin -package spec - -import ( - "github.com/rsteube/carapace/internal/pflagfork" - "github.com/spf13/cobra" - "github.com/spf13/pflag" - "gopkg.in/yaml.v3" -) - -// Snippet generates the spec file. -func Snippet(cmd *cobra.Command) string { - m, _ := yaml.Marshal(command(cmd)) - return string(m) -} - -func command(cmd *cobra.Command) Command { - c := Command{ - Name: cmd.Use, - Description: cmd.Short, - Aliases: cmd.Aliases, - Group: cmd.GroupID, - Flags: make(map[string]string), - PersistentFlags: make(map[string]string), - Commands: make([]Command, 0), - } - - cmd.LocalFlags().VisitAll(func(flag *pflag.Flag) { - if flag.Hidden { - return - } - f := pflagfork.Flag{Flag: flag} - c.Flags[f.Definition()] = f.Usage - - }) - - cmd.PersistentFlags().VisitAll(func(flag *pflag.Flag) { - if flag.Hidden { - return - } - f := pflagfork.Flag{Flag: flag} - c.PersistentFlags[f.Definition()] = f.Usage - - }) - - for _, subcmd := range cmd.Commands() { - if !subcmd.Hidden { - c.Commands = append(c.Commands, command(subcmd)) - } - } - - return c -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/tcsh/action.go b/vendor/github.com/rsteube/carapace/internal/shell/tcsh/action.go deleted file mode 100644 index 02a986c..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/tcsh/action.go +++ /dev/null @@ -1,110 +0,0 @@ -package tcsh - -import ( - "fmt" - "os" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, - "\t", ``, -) - -var quoter = strings.NewReplacer( - `&`, `\&`, - `<`, `\<`, - `>`, `\>`, - "`", "\\`", - `'`, `\'`, - `"`, `\"`, - `{`, ``, // TODO seems escaping is not working - `}`, ``, // TODO seems escaping is not working - `$`, `\$`, - `#`, `\#`, - `|`, `\|`, - `?`, `\?`, - `(`, `\(`, - `)`, `\)`, - `;`, `\;`, - ` `, `\ `, - `[`, `\[`, - `]`, `\]`, - `*`, `\*`, - `\`, `\\`, -) - -func commonPrefix(a, b string) string { - i := 0 - for i < len(a) && i < len(b) && a[i] == b[i] { - i++ - } - return a[0:i] -} - -func commonDisplayPrefix(values ...common.RawValue) (prefix string) { - for index, val := range values { - if index == 0 { - prefix = val.Display - } else { - prefix = commonPrefix(prefix, val.Display) - } - } - return -} - -func commonValuePrefix(values ...common.RawValue) (prefix string) { - for index, val := range values { - if index == 0 { - prefix = val.Value - } else { - prefix = commonPrefix(prefix, val.Value) - } - } - return -} - -// ActionRawValues formats values for bash. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - lastSegment := currentWord // last segment of currentWord split by COMP_WORDBREAKS - - for _, r := range values { - // TODO optimize - if wordbreaks, ok := os.LookupEnv("COMP_WORDBREAKS"); ok { - wordbreaks = strings.Replace(wordbreaks, " ", "", -1) - if index := strings.LastIndexAny(currentWord, wordbreaks); index != -1 { - r.Value = strings.TrimPrefix(r.Value, currentWord[:index+1]) - lastSegment = currentWord[index+1:] - } - } - } - - if len(values) > 1 && commonDisplayPrefix(values...) != "" { - // When all display values have the same prefix bash will insert is as partial completion (which skips prefixes/formatting). - if valuePrefix := commonValuePrefix(values...); lastSegment != valuePrefix { - // replace values with common value prefix (`\001` is removed in snippet and compopt nospace will be set) - values = common.RawValuesFrom(commonValuePrefix(values...)) // TODO nospaceIndicator - } else { - // prevent insertion of partial display values by prefixing one with space - values[0].Display = " " + values[0].Display - } - } - - vals := make([]string, len(values)) - for index, val := range values { - if len(values) == 1 { - vals[index] = quoter.Replace(sanitizer.Replace(val.Value)) - } else { - if val.Description != "" { - // TODO seems actual value needs to be used or it won't be shown if the prefix doesn't match - vals[index] = fmt.Sprintf("%v_(%v)", quoter.Replace(sanitizer.Replace(val.Value)), quoter.Replace(strings.Replace(sanitizer.Replace(val.TrimmedDescription()), " ", "_", -1))) - } else { - vals[index] = quoter.Replace(sanitizer.Replace(val.Value)) - } - } - } - return strings.Join(vals, "\n") -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/tcsh/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/tcsh/snippet.go deleted file mode 100644 index 422b624..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/tcsh/snippet.go +++ /dev/null @@ -1,15 +0,0 @@ -// Package tcsh provides tcsh completion -package tcsh - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the tcsh completion script. -func Snippet(cmd *cobra.Command) string { - // TODO initial version - needs to handle open quotes - return fmt.Sprintf("complete \"%v\" 'p@*@`echo \"$COMMAND_LINE'\"''\"'\" | xargs %v _carapace tcsh `@@' ;", cmd.Name(), uid.Executable()) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/xonsh/action.go b/vendor/github.com/rsteube/carapace/internal/shell/xonsh/action.go deleted file mode 100644 index 81e0ad7..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/xonsh/action.go +++ /dev/null @@ -1,45 +0,0 @@ -package xonsh - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( // TODO - "\n", ``, - "\t", ``, - `'`, `\'`, -) - -type richCompletion struct { - Value string - Display string - Description string -} - -// ActionRawValues formats values for xonsh. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - vals := make([]richCompletion, len(values)) - for index, val := range values { - val.Value = sanitizer.Replace(val.Value) - - if strings.ContainsAny(val.Value, ` ()[]{}*$?\"|<>&;#`+"`") { - if strings.Contains(val.Value, `\`) { - val.Value = fmt.Sprintf("r'%v'", val.Value) // backslash needs raw string - } else { - val.Value = fmt.Sprintf("'%v'", val.Value) - } - } - - if !meta.Nospace.Matches(val.Value) { - val.Value = val.Value + " " - } - - vals[index] = richCompletion{Value: val.Value, Display: val.Display, Description: val.TrimmedDescription()} - } - m, _ := json.Marshal(vals) - return string(m) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/xonsh/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/xonsh/snippet.go deleted file mode 100644 index caa9875..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/xonsh/snippet.go +++ /dev/null @@ -1,42 +0,0 @@ -// Package xonsh provides Xonsh completion -package xonsh - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the xonsh completion script. -func Snippet(cmd *cobra.Command) string { - functionName := strings.Replace(cmd.Name(), "-", "__", -1) - return fmt.Sprintf(`from xonsh.completers.tools import * - -@contextual_command_completer -def _%v_completer(context): - """carapace completer for %v""" - if context.completing_command('%v'): - from json import loads - from subprocess import Popen, PIPE - from xonsh.completers.tools import RichCompletion - - def fix_prefix(s): - """quick fix for partially quoted prefix completion ('prefix',)""" - return s.translate(str.maketrans('', '', '\'"')) - - output, _ = Popen(['%v', '_carapace', 'xonsh', *[a.value for a in context.args], fix_prefix(context.prefix)], stdout=PIPE, stderr=PIPE).communicate() - try: - result = {RichCompletion(c["Value"], display=c["Display"], description=c["Description"], prefix_len=len(context.raw_prefix), append_closing_quote=False) for c in loads(output)} - except: - result = {} - if len(result) == 0: - result = {RichCompletion(context.prefix, display=context.prefix, description='', prefix_len=len(context.raw_prefix), append_closing_quote=False)} - return result - - -from xonsh.completers._aliases import _add_one_completer -_add_one_completer('%v', _%v_completer, 'start') -`, functionName, cmd.Name(), cmd.Name(), uid.Executable(), cmd.Name(), functionName) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/zsh/action.go b/vendor/github.com/rsteube/carapace/internal/shell/zsh/action.go deleted file mode 100644 index 6e49518..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/zsh/action.go +++ /dev/null @@ -1,78 +0,0 @@ -package zsh - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" -) - -var sanitizer = strings.NewReplacer( - "\n", ``, - "\r", ``, - "\t", ``, -) - -// TODO verify these are correct/complete (copied from bash). -var quoter = strings.NewReplacer( - `\`, `\\`, - `&`, `\&`, - `<`, `\<`, - `>`, `\>`, - "`", "\\`", - `'`, `\'`, - `"`, `\"`, - `{`, `\{`, - `}`, `\}`, - `$`, `\$`, - `#`, `\#`, - `|`, `\|`, - `?`, `\?`, - `(`, `\(`, - `)`, `\)`, - `;`, `\;`, - ` `, `\ `, - `[`, `\[`, - `]`, `\]`, - `*`, `\*`, - `~`, `\~`, -) - -func quoteValue(s string) string { - if strings.HasPrefix(s, "~/") || NamedDirectories.Matches(s) { - return "~" + quoter.Replace(strings.TrimPrefix(s, "~")) // assume file path expansion - } - return quoter.Replace(s) -} - -// ActionRawValues formats values for zsh. -func ActionRawValues(currentWord string, meta common.Meta, values common.RawValues) string { - tagGroup := make([]string, 0) - values.EachTag(func(tag string, values common.RawValues) { - vals := make([]string, len(values)) - displays := make([]string, len(values)) - for index, val := range values { - val.Value = sanitizer.Replace(val.Value) - val.Value = quoteValue(val.Value) - val.Value = strings.ReplaceAll(val.Value, `\`, `\\`) // TODO find out why `_describe` needs another backslash - val.Value = strings.ReplaceAll(val.Value, `:`, `\:`) // TODO find out why `_describe` needs another backslash - if !meta.Nospace.Matches(val.Value) { - val.Value = val.Value + " " - } - val.Display = sanitizer.Replace(val.Display) - val.Display = strings.ReplaceAll(val.Display, `\`, `\\`) // TODO find out why `_describe` needs another backslash - val.Display = strings.ReplaceAll(val.Display, `:`, `\:`) // TODO find out why `_describe` needs another backslash - val.Description = sanitizer.Replace(val.Description) - - vals[index] = val.Value - - if strings.TrimSpace(val.Description) == "" { - displays[index] = val.Display - } else { - displays[index] = fmt.Sprintf("%v:%v", val.Display, val.Description) - } - } - tagGroup = append(tagGroup, strings.Join([]string{tag, strings.Join(displays, "\n"), strings.Join(vals, "\n")}, "\003")) - }) - return fmt.Sprintf("%v\001%v\001%v\001", zstyles{values}.Format(), message{meta}.Format(), strings.Join(tagGroup, "\002")+"\002") -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/zsh/message.go b/vendor/github.com/rsteube/carapace/internal/shell/zsh/message.go deleted file mode 100644 index 0dd8fea..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/zsh/message.go +++ /dev/null @@ -1,41 +0,0 @@ -package zsh - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/pkg/style" -) - -type message struct { - common.Meta -} - -func (m message) Format() string { - formatted := make([]string, 0) - for _, message := range m.Messages.Get() { - formatted = append(formatted, m.formatMessage(message, style.Carapace.Error)) - } - if m.Usage != "" { - formatted = append(formatted, m.formatMessage(m.Usage, style.Carapace.Usage)) - } - - if len(formatted) > 0 { - return strings.Join(formatted, "\n") - } - return "" -} - -func (m message) formatMessage(message, _style string) string { - msg := strings.NewReplacer( - "\n", ``, - "\r", ``, - "\t", ``, - "\v", ``, - "\f", ``, - "\b", ``, - ).Replace(message) - - return fmt.Sprintf("\x1b[%vm%v\x1b[%vm", style.SGR(_style), msg, style.SGR("fg-default")) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/zsh/namedDirectory.go b/vendor/github.com/rsteube/carapace/internal/shell/zsh/namedDirectory.go deleted file mode 100644 index be3f7e1..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/zsh/namedDirectory.go +++ /dev/null @@ -1,44 +0,0 @@ -package zsh - -import ( - "os" - "strings" -) - -type namedDirectories map[string]string - -// NamedDirectories provides rudimentary named directory support as these aren't expanded by zsh in the `${words}` provided to the compdef function. -var NamedDirectories = make(namedDirectories) - -func (nd *namedDirectories) match(s string) string { - if strings.HasPrefix(s, "~") && !strings.HasPrefix(s, "~/") && strings.Contains(s, "/") { - return NamedDirectories[strings.SplitN(s, "/", 2)[0][1:]] - } - return "" -} - -// Matches checks if given string has a known named directory prefix. -func (nd *namedDirectories) Matches(s string) bool { - return nd.match(s) != "" -} - -// Replace replaces a known named directory prefix with the actual folder. -func (nd *namedDirectories) Replace(s string) string { - if match := nd.match(s); match != "" { - if !strings.HasSuffix(match, "/") { - match = match + "/" - } - return match + strings.SplitN(s, "/", 2)[1] - } - return s -} - -func init() { - if hashDirs, ok := os.LookupEnv("CARAPACE_ZSH_HASH_DIRS"); ok { - for _, line := range strings.Split(hashDirs, "\n") { - if splitted := strings.SplitN(line, "=", 2); len(splitted) == 2 { - NamedDirectories[splitted[0]] = splitted[1] - } - } - } -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/zsh/snippet.go b/vendor/github.com/rsteube/carapace/internal/shell/zsh/snippet.go deleted file mode 100644 index 45dfb16..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/zsh/snippet.go +++ /dev/null @@ -1,46 +0,0 @@ -// Package zsh provides zsh completion -package zsh - -import ( - "fmt" - - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" -) - -// Snippet creates the zsh completion script. -func Snippet(cmd *cobra.Command) string { - return fmt.Sprintf(`#compdef %v -function _%v_completion { - local IFS=$'\n' - - # shellcheck disable=SC2086,SC2154,SC2155 - if echo ${words}"''" | xargs echo 2>/dev/null > /dev/null; then - local lines="$(echo ${words}"''" | CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %v _carapace zsh )" - elif echo ${words} | sed "s/\$/'/" | xargs echo 2>/dev/null > /dev/null; then - local lines="$(echo ${words} | sed "s/\$/'/" | CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %v _carapace zsh)" - else - local lines="$(echo ${words} | sed 's/$/"/' | CARAPACE_ZSH_HASH_DIRS="$(hash -d)" xargs %v _carapace zsh)" - fi - - local zstyle message data - IFS=$'\001' read -r -d '' zstyle message data <<<"${lines}" - # shellcheck disable=SC2154 - zstyle ":completion:${curcontext}:*" list-colors "${zstyle}" - zstyle ":completion:${curcontext}:*" group-name '' - [ -z "$message" ] || _message -r "${message}" - - local block tag displays values displaysArr valuesArr - while IFS=$'\002' read -r -d $'\002' block; do - IFS=$'\003' read -r -d '' tag displays values <<<"${block}" - # shellcheck disable=SC2034 - IFS=$'\n' read -r -d $'\004' -A displaysArr <<<"${displays}"$'\004' - IFS=$'\n' read -r -d $'\004' -A valuesArr <<<"${values}"$'\004' - - [[ ${#valuesArr[@]} -gt 1 ]] && _describe -t "${tag}" "${tag}" displaysArr valuesArr -Q -S '' - done <<<"${data}" -} -compquote '' 2>/dev/null && _%v_completion -compdef _%v_completion %v -`, cmd.Name(), cmd.Name(), uid.Executable(), uid.Executable(), uid.Executable(), cmd.Name(), cmd.Name(), cmd.Name()) -} diff --git a/vendor/github.com/rsteube/carapace/internal/shell/zsh/zstyle.go b/vendor/github.com/rsteube/carapace/internal/shell/zsh/zstyle.go deleted file mode 100644 index 0933b49..0000000 --- a/vendor/github.com/rsteube/carapace/internal/shell/zsh/zstyle.go +++ /dev/null @@ -1,57 +0,0 @@ -package zsh - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/pkg/style" - "github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui" -) - -type zstyles struct { - rawValues common.RawValues -} - -func (z zstyles) descriptionSGR() string { - if s := style.Carapace.Description; s != "" && ui.ParseStyling(s) != nil { - return style.SGR(s) - } - return style.SGR(style.Default) -} - -func (z zstyles) valueSGR(val common.RawValue) string { - if val.Style != "" && ui.ParseStyling(val.Style) != nil { - return style.SGR(val.Style) - } - - if ui.ParseStyling(style.Carapace.Value) != nil { - return style.SGR(style.Carapace.Value) - } - return style.SGR(style.Default) -} - -func (z zstyles) Format() string { - replacer := strings.NewReplacer( - "#", `\#`, - "*", `\*`, - "(", `\(`, - ")", `\)`, - "[", `\[`, - "]", `\]`, - "|", `\|`, - "~", `\~`, - ) - - formatted := make([]string, 0) - if len(z.rawValues) < 1000 { // disable styling for large amount of values (bad performance) - for _, val := range z.rawValues { - // match value with description - formatted = append(formatted, fmt.Sprintf("=(#b)(%v)([ ]## -- *)=0=%v=%v", replacer.Replace(val.Display), z.valueSGR(val), z.descriptionSGR())) - // only match value (also matches aliased completions that are placed on the same line if the space allows it) - formatted = append(formatted, fmt.Sprintf("=(#b)(%v)=0=%v", replacer.Replace(val.Display), z.valueSGR(val))) - } - } - formatted = append(formatted, fmt.Sprintf("=(#b)(%v)=0=%v", "-- *", z.descriptionSGR())) // match description for aliased completions - return strings.Join(formatted, ":") -} diff --git a/vendor/github.com/rsteube/carapace/internal/uid/uid.go b/vendor/github.com/rsteube/carapace/internal/uid/uid.go deleted file mode 100644 index 98b7642..0000000 --- a/vendor/github.com/rsteube/carapace/internal/uid/uid.go +++ /dev/null @@ -1,41 +0,0 @@ -// Package uid provides unique identifiers -package uid - -import ( - "os" - "path/filepath" - "strings" - - "github.com/spf13/cobra" -) - -// Command creates a uid for given command. -func Command(cmd *cobra.Command) string { - names := make([]string, 0) - current := cmd - for { - names = append(names, current.Name()) - current = current.Parent() - if current == nil { - break - } - } - - reverse := make([]string, len(names)) - for i, entry := range names { - reverse[len(names)-i-1] = entry - } - - return "_" + strings.Join(reverse, "__") -} - -// Executable returns the name of the executable. -func Executable() string { - if executable, err := os.Executable(); err != nil { - return "echo" // safe fallback that should never happen - } else if filepath.Base(executable) == "cmd.test" { - return "example" // for `go test -v ./...` - } else { - return filepath.Base(executable) - } -} diff --git a/vendor/github.com/rsteube/carapace/internalActions.go b/vendor/github.com/rsteube/carapace/internalActions.go deleted file mode 100644 index b0cd9d4..0000000 --- a/vendor/github.com/rsteube/carapace/internalActions.go +++ /dev/null @@ -1,131 +0,0 @@ -package carapace - -import ( - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/pflagfork" - "github.com/rsteube/carapace/pkg/style" - "github.com/spf13/cobra" -) - -func actionPath(fileSuffixes []string, dirOnly bool) Action { - return ActionCallback(func(c Context) Action { - abs, err := c.Abs(c.Value) - if err != nil { - return ActionMessage(err.Error()) - } - - displayFolder := filepath.Dir(c.Value) - if displayFolder == "." { - displayFolder = "" - } else if !strings.HasSuffix(displayFolder, "/") { - displayFolder = displayFolder + "/" - } - - actualFolder := filepath.Dir(abs) - files, err := ioutil.ReadDir(actualFolder) - if err != nil { - return ActionMessage(err.Error()) - } - - showHidden := !strings.HasSuffix(abs, "/") && strings.HasPrefix(filepath.Base(abs), ".") - - vals := make([]string, 0, len(files)*2) - for _, file := range files { - if !showHidden && strings.HasPrefix(file.Name(), ".") { - continue - } - - resolvedFile := file - if resolved, err := filepath.EvalSymlinks(actualFolder + file.Name()); err == nil { - if stat, err := os.Stat(resolved); err == nil { - resolvedFile = stat - } - } - - if resolvedFile.IsDir() { - vals = append(vals, displayFolder+file.Name()+"/", style.ForPath(filepath.Clean(actualFolder+"/"+file.Name()+"/"), c)) - } else if !dirOnly { - if len(fileSuffixes) == 0 { - fileSuffixes = []string{""} - } - for _, suffix := range fileSuffixes { - if strings.HasSuffix(file.Name(), suffix) { - vals = append(vals, displayFolder+file.Name(), style.ForPath(filepath.Clean(actualFolder+"/"+file.Name()), c)) - break - } - } - } - } - if strings.HasPrefix(c.Value, "./") { - return ActionStyledValues(vals...).Invoke(Context{}).Prefix("./").ToA() - } - return ActionStyledValues(vals...) - }).Tag("files").NoSpace('/') -} - -func actionFlags(cmd *cobra.Command) Action { - return ActionCallback(func(c Context) Action { - flagSet := pflagfork.FlagSet{FlagSet: cmd.Flags()} - isShorthandSeries := flagSet.IsShorthandSeries(c.Value) - - vals := make([]string, 0) - flagSet.VisitAll(func(f *pflagfork.Flag) { - switch { - case f.Deprecated != "": - return // skip deprecated flags - case f.Changed && !f.IsRepeatable(): - return // don't repeat flag - case flagSet.IsMutuallyExclusive(f.Flag): - return // skip flag of group already set - } - - if isShorthandSeries { - if f.Shorthand != "" && f.ShorthandDeprecated == "" { - for _, shorthand := range c.Value[1:] { - if shorthandFlag := cmd.Flags().ShorthandLookup(string(shorthand)); shorthandFlag != nil && shorthandFlag.Value.Type() != "bool" && shorthandFlag.Value.Type() != "count" && shorthandFlag.NoOptDefVal == "" { - return // abort shorthand flag series if a previous one is not bool or count and requires an argument (no default value) - } - } - vals = append(vals, f.Shorthand, f.Usage, f.Style()) - } - } else { - switch f.Mode() { - case pflagfork.NameAsShorthand: - vals = append(vals, "-"+f.Name, f.Usage, f.Style()) - case pflagfork.Default: - vals = append(vals, "--"+f.Name, f.Usage, f.Style()) - } - - if f.Shorthand != "" && f.ShorthandDeprecated == "" { - vals = append(vals, "-"+f.Shorthand, f.Usage, f.Style()) - } - } - }) - - if isShorthandSeries { - return ActionStyledValuesDescribed(vals...).Prefix(c.Value).NoSpace('*') - } - return ActionStyledValuesDescribed(vals...).MultiParts(".") // multiparts completion for flags grouped with `.` - }).Tag("flags") -} - -func actionSubcommands(cmd *cobra.Command) Action { - return ActionCallback(func(c Context) Action { - batch := Batch() - for _, subcommand := range cmd.Commands() { - if !subcommand.Hidden && subcommand.Deprecated == "" { - group := common.Group{Cmd: subcommand} - batch = append(batch, ActionStyledValuesDescribed(subcommand.Name(), subcommand.Short, group.Style()).Tag(group.Tag())) - for _, alias := range subcommand.Aliases { - batch = append(batch, ActionStyledValuesDescribed(alias, subcommand.Short, group.Style()).Tag(group.Tag())) - } - } - } - return batch.ToA() - }) -} diff --git a/vendor/github.com/rsteube/carapace/invokedAction.go b/vendor/github.com/rsteube/carapace/invokedAction.go deleted file mode 100644 index 0b1d603..0000000 --- a/vendor/github.com/rsteube/carapace/invokedAction.go +++ /dev/null @@ -1,147 +0,0 @@ -package carapace - -import ( - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/export" - _shell "github.com/rsteube/carapace/internal/shell" -) - -// InvokedAction is a logical alias for an Action whose (nested) callback was invoked. -type InvokedAction struct { - Action -} - -func (a InvokedAction) export() export.Export { - return export.Export{Meta: a.meta, Values: a.rawValues} -} - -// Filter filters given values (this should be done before any call to Prefix/Suffix as those alter the values being filtered) -// -// a := carapace.ActionValues("A", "B", "C").Invoke(c) -// b := a.Filter([]string{"B"}) // ["A", "C"] -func (a InvokedAction) Filter(values []string) InvokedAction { - a.rawValues = a.rawValues.Filter(values...) - return a -} - -// Merge merges InvokedActions (existing values are overwritten) -// -// a := carapace.ActionValues("A", "B").Invoke(c) -// b := carapace.ActionValues("B", "C").Invoke(c) -// c := a.Merge(b) // ["A", "B", "C"] -func (a InvokedAction) Merge(others ...InvokedAction) InvokedAction { - for _, other := range append([]InvokedAction{a}, others...) { - a.rawValues = append(a.rawValues, other.rawValues...) - a.meta.Merge(other.meta) - } - a.rawValues = a.rawValues.Unique() - return a -} - -// Prefix adds a prefix to values (only the ones inserted, not the display values) -// -// carapace.ActionValues("melon", "drop", "fall").Invoke(c).Prefix("water") -func (a InvokedAction) Prefix(prefix string) InvokedAction { - for index, val := range a.rawValues { - a.rawValues[index].Value = prefix + val.Value - } - return a -} - -// Suffix adds a suffx to values (only the ones inserted, not the display values) -// -// carapace.ActionValues("apple", "melon", "orange").Invoke(c).Suffix("juice") -func (a InvokedAction) Suffix(suffix string) InvokedAction { - for index, val := range a.rawValues { - a.rawValues[index].Value = val.Value + suffix - } - return a -} - -// ToA casts an InvokedAction to Action. -func (a InvokedAction) ToA() Action { - return a.Action -} - -func tokenize(s string, dividers ...string) []string { - if len(dividers) == 0 { - return []string{s} - } - - result := make([]string, 0) - for _, word := range strings.SplitAfter(s, dividers[0]) { - tokens := tokenize(strings.TrimSuffix(word, dividers[0]), dividers[1:]...) - if len(tokens) > 0 && strings.HasSuffix(word, dividers[0]) { - tokens[len(tokens)-1] = tokens[len(tokens)-1] + dividers[0] - } - result = append(result, tokens...) - } - return result -} - -// ToMultiPartsA create an ActionMultiParts from values with given dividers -// -// a := carapace.ActionValues("A/B/C", "A/C", "B/C", "C").Invoke(c) -// b := a.ToMultiPartsA("/") // completes segments separately (first one is ["A/", "B/", "C"]) -func (a InvokedAction) ToMultiPartsA(dividers ...string) Action { - return ActionCallback(func(c Context) Action { - splittedCV := tokenize(c.Value, dividers...) - - uniqueVals := make(map[string]common.RawValue) - for _, val := range a.rawValues { - if strings.HasPrefix(val.Value, c.Value) { - if splitted := tokenize(val.Value, dividers...); len(splitted) >= len(splittedCV) { - v := strings.Join(splitted[:len(splittedCV)], "") - d := splitted[len(splittedCV)-1] - - if len(splitted) == len(splittedCV) { - uniqueVals[v] = common.RawValue{ - Value: v, - Display: d, - Description: val.Description, - Style: val.Style, - } - } else { - uniqueVals[v] = common.RawValue{ - Value: v, - Display: d, - Description: "", - Style: "", - } - } - } - } - } - - vals := make([]common.RawValue, 0) - for _, val := range uniqueVals { - vals = append(vals, val) - } - - a := Action{rawValues: vals} - for _, divider := range dividers { - if runes := []rune(divider); len(runes) == 0 { - a.meta.Nospace.Add('*') - break - } else { - a.meta.Nospace.Add(runes[len(runes)-1]) - } - } - return a - }) -} - -func (a InvokedAction) value(shell string, value string) string { - return _shell.Value(shell, value, a.meta, a.rawValues) -} - -func init() { - common.FromInvokedAction = func(i interface{}) (common.Meta, common.RawValues) { - if a, ok := i.(InvokedAction); ok { - return a.meta, a.rawValues - } - return common.Meta{}, nil - } -} diff --git a/vendor/github.com/rsteube/carapace/log.go b/vendor/github.com/rsteube/carapace/log.go deleted file mode 100644 index 5f5646c..0000000 --- a/vendor/github.com/rsteube/carapace/log.go +++ /dev/null @@ -1,31 +0,0 @@ -package carapace - -import ( - "fmt" - "io/ioutil" - "log" - "os" - - "github.com/rsteube/carapace/internal/uid" - "github.com/rsteube/carapace/pkg/ps" -) - -var LOG = log.New(ioutil.Discard, "", log.Flags()) - -func init() { - if _, enabled := os.LookupEnv("CARAPACE_LOG"); !enabled { - return - } - - tmpdir := fmt.Sprintf("%v/carapace", os.TempDir()) - if err := os.MkdirAll(tmpdir, os.ModePerm); err != nil { - log.Fatal(err.Error()) - } - - file := fmt.Sprintf("%v/%v.log", tmpdir, uid.Executable()) - if logfileWriter, err := os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o666); err != nil { - log.Fatal(err.Error()) - } else { - LOG = log.New(logfileWriter, ps.DetermineShell()+" ", log.Flags()|log.Lmsgprefix|log.Lmicroseconds) - } -} diff --git a/vendor/github.com/rsteube/carapace/pkg/cache/cache.go b/vendor/github.com/rsteube/carapace/pkg/cache/cache.go deleted file mode 100644 index 40846a3..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/cache/cache.go +++ /dev/null @@ -1,46 +0,0 @@ -// Package cache provides cache keys -package cache - -import ( - "crypto/sha1" - "fmt" - "os" - "path/filepath" - "strconv" - "strings" -) - -// Key provides a cache key. -type Key func() (string, error) - -// String creates a CacheKey for given strings. -func String(s ...string) Key { - return func() (string, error) { - return strings.Join(s, "\n"), nil - } -} - -// FileChecksum creates a CacheKey for given file. -func FileChecksum(file string) Key { - return func() (checksum string, err error) { - var content []byte - if content, err = os.ReadFile(file); err == nil { - checksum = fmt.Sprintf("%x", sha1.Sum(content)) - } - return - } -} - -// FileStats creates a CacheKey for given file. -func FileStats(file string) Key { - return func() (checksum string, err error) { - var path string - if path, err = filepath.Abs(file); err == nil { - var info os.FileInfo - if info, err = os.Stat(file); err == nil { - return String(path, strconv.FormatInt(info.Size(), 10), info.ModTime().String())() - } - } - return - } -} diff --git a/vendor/github.com/rsteube/carapace/pkg/ps/ps.go b/vendor/github.com/rsteube/carapace/pkg/ps/ps.go deleted file mode 100644 index 7f8d5e4..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/ps/ps.go +++ /dev/null @@ -1,73 +0,0 @@ -// Package ps provides shell determination by process name -package ps - -import ( - "os" - "strings" - - "github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps" -) - -// DetermineShell determines shell by parent process name. -func DetermineShell() string { - process, err := ps.FindProcess(os.Getpid()) - if err != nil { - return "" - } - for { - if process, err = ps.FindProcess(process.PPid()); err != nil || process == nil { - return "" - } - - executable := process.Executable() - switch strings.SplitN(strings.TrimSuffix(executable, ".exe"), "-", 2)[0] { - case "bash": - if isBLE() { - return "bash-ble" - } - return "bash" - case "elvish": - return "elvish" - case "fish": - return "fish" - case "ion": - return "ion" - case "nu": - return "nushell" - case "oil": - return "oil" - case "osh": - return "oil" - case "powershell": - return "powershell" - case "pwsh": - return "powershell" - case "tcsh": - return "tcsh" - case "xonsh": - return "xonsh" - case "zsh": - return "zsh" - default: - if strings.Contains(executable, "xonsh-wrapped") { // nix packaged version - return "xonsh" - } - } - } -} - -func isBLE() bool { - bleEnvs := []string{ - "_ble_util_fd_null", - "_ble_util_fd_stderr", - "_ble_util_fd_stdin", - "_ble_util_fd_stdout", - "_ble_util_fd_zero", - } - for _, e := range bleEnvs { - if _, ok := os.LookupEnv(e); ok { - return true - } - } - return false -} diff --git a/vendor/github.com/rsteube/carapace/pkg/style/config.go b/vendor/github.com/rsteube/carapace/pkg/style/config.go deleted file mode 100644 index a1a70e5..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/style/config.go +++ /dev/null @@ -1,141 +0,0 @@ -package style - -import ( - "github.com/rsteube/carapace/internal/config" -) - -// Register a style configuration -// -// var Carapace = struct { -// Value string `desc:"default style for values"` -// Description string `desc:"default style for descriptions"` -// }{ -// Value: Default, -// Description: Gray, -// } -// -// func init() { -// Register("carapace", &Carapace) -// } -func Register(name string, i interface{}) { config.RegisterStyle(name, i) } - -// Set a style -// -// Set("carapace.Value", "bold magenta") -func Set(key, value string) error { return config.SetStyle(key, value) } - -type carapace struct { - Value string `desc:"default style for values" tag:"core styles"` - Description string `desc:"default style for descriptions" tag:"core styles"` - Error string `desc:"default style for errors" tag:"core styles"` - Usage string `desc:"default style for usage" tag:"core styles"` - - KeywordAmbiguous string `desc:"keyword describing a ambiguous state" tag:"keyword styles"` - KeywordNegative string `desc:"keyword describing a negative state" tag:"keyword styles"` - KeywordPositive string `desc:"keyword describing a positive state" tag:"keyword styles"` - KeywordUnknown string `desc:"keyword describing an unknown state" tag:"keyword styles"` - - LogLevelTrace string `desc:"LogLevel TRACE" tag:"loglevel styles"` - LogLevelDebug string `desc:"LogLevel DEBUG" tag:"loglevel styles"` - LogLevelInfo string `desc:"LogLevel INFO" tag:"loglevel styles"` - LogLevelWarning string `desc:"LogLevel WARNING" tag:"loglevel styles"` - LogLevelError string `desc:"LogLevel ERROR" tag:"loglevel styles"` - LogLevelCritical string `desc:"LogLevel CRITICAL" tag:"loglevel styles"` - LogLevelFatal string `desc:"LogLevel FATAL" tag:"loglevel styles"` - - Highlight1 string `desc:"Highlight 1" tag:"highlight styles"` - Highlight2 string `desc:"Highlight 2" tag:"highlight styles"` - Highlight3 string `desc:"Highlight 3" tag:"highlight styles"` - Highlight4 string `desc:"Highlight 4" tag:"highlight styles"` - Highlight5 string `desc:"Highlight 5" tag:"highlight styles"` - Highlight6 string `desc:"Highlight 6" tag:"highlight styles"` - - Highlight7 string `desc:"Highlight 7" tag:"highlight styles"` - Highlight8 string `desc:"Highlight 8" tag:"highlight styles"` - Highlight9 string `desc:"Highlight 9" tag:"highlight styles"` - Highlight10 string `desc:"Highlight 10" tag:"highlight styles"` - - Highlight11 string `desc:"Highlight 11" tag:"highlight styles"` - Highlight12 string `desc:"Highlight 12" tag:"highlight styles"` - - FlagArg string `desc:"flag with argument" tag:"flag styles"` - FlagMultiArg string `desc:"flag with multiple arguments" tag:"flag styles"` - FlagNoArg string `desc:"flag without argument" tag:"flag styles"` - FlagOptArg string `desc:"flag with optional argument" tag:"flag styles"` -} - -var Carapace = carapace{ - Value: Default, - Description: Gray, - Error: Of(Bold, Red), - Usage: Gray, - - KeywordAmbiguous: Yellow, - KeywordNegative: Red, - KeywordPositive: Green, - KeywordUnknown: Gray, - - LogLevelTrace: Blue, - LogLevelDebug: Gray, - LogLevelInfo: Green, - LogLevelWarning: Yellow, - LogLevelError: Magenta, - LogLevelCritical: Red, - LogLevelFatal: Cyan, - - Highlight1: Blue, - Highlight2: Yellow, - Highlight3: Magenta, - Highlight4: Cyan, - Highlight5: Green, - - Highlight6: Of(Blue, Dim), - Highlight7: Of(Yellow, Dim), - Highlight8: Of(Magenta, Dim), - Highlight9: Of(Cyan, Dim), - Highlight10: Of(Green, Dim), - - Highlight11: Bold, - Highlight12: Of(Bold, Dim), - - FlagArg: Blue, - FlagMultiArg: Magenta, - FlagNoArg: Default, - FlagOptArg: Yellow, -} - -// Highlight returns the style for given level (0..n). -func (c carapace) Highlight(level int) string { - switch level { - case 0: - return c.Highlight1 - case 1: - return c.Highlight2 - case 2: - return c.Highlight3 - case 3: - return c.Highlight4 - case 4: - return c.Highlight5 - case 5: - return c.Highlight6 - case 6: - return c.Highlight7 - case 7: - return c.Highlight8 - case 8: - return c.Highlight9 - case 9: - return c.Highlight10 - case 10: - return c.Highlight11 - case 11: - return c.Highlight12 - default: - return Default - } -} - -func init() { - Register("carapace", &Carapace) -} diff --git a/vendor/github.com/rsteube/carapace/pkg/style/keyword.go b/vendor/github.com/rsteube/carapace/pkg/style/keyword.go deleted file mode 100644 index d9e9220..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/style/keyword.go +++ /dev/null @@ -1,94 +0,0 @@ -package style - -import "strings" - -var keywords = map[string]*string{ - "y": &Carapace.KeywordPositive, - "n": &Carapace.KeywordNegative, - - "yes": &Carapace.KeywordPositive, - "no": &Carapace.KeywordNegative, - - "true": &Carapace.KeywordPositive, - "false": &Carapace.KeywordNegative, - - "on": &Carapace.KeywordPositive, - "off": &Carapace.KeywordNegative, - - "all": &Carapace.KeywordPositive, - "some": &Carapace.KeywordAmbiguous, - "none": &Carapace.KeywordNegative, - - "full": &Carapace.KeywordPositive, - "empty": &Carapace.KeywordNegative, - - "strict": &Carapace.KeywordPositive, - "loose": &Carapace.KeywordNegative, - - "open": &Carapace.KeywordPositive, - "opened": &Carapace.KeywordPositive, - "close": &Carapace.KeywordNegative, - "closed": &Carapace.KeywordNegative, - - "always": &Carapace.KeywordPositive, - "auto": &Carapace.KeywordAmbiguous, - "never": &Carapace.KeywordNegative, - - "start": &Carapace.KeywordPositive, - "started": &Carapace.KeywordPositive, - "starting": &Carapace.KeywordPositive, - "run": &Carapace.KeywordPositive, - "running": &Carapace.KeywordPositive, - "inprogress": &Carapace.KeywordAmbiguous, - "pause": &Carapace.KeywordAmbiguous, - "paused": &Carapace.KeywordAmbiguous, - "pausing": &Carapace.KeywordAmbiguous, - "restart": &Carapace.KeywordAmbiguous, - "restarted": &Carapace.KeywordAmbiguous, - "restarting": &Carapace.KeywordAmbiguous, - "remove": &Carapace.KeywordNegative, - "removed": &Carapace.KeywordNegative, - "removing": &Carapace.KeywordNegative, - "stop": &Carapace.KeywordNegative, - "stopped": &Carapace.KeywordNegative, - "stopping": &Carapace.KeywordNegative, - "exit": &Carapace.KeywordNegative, - "exited": &Carapace.KeywordNegative, - "exiting": &Carapace.KeywordNegative, - "dead": &Carapace.KeywordNegative, - - "create": &Carapace.KeywordPositive, - "created": &Carapace.KeywordPositive, - "delete": &Carapace.KeywordNegative, - "deleted": &Carapace.KeywordNegative, - - "onsuccess": &Carapace.KeywordPositive, - "onfailure": &Carapace.KeywordNegative, - "onerror": &Carapace.KeywordNegative, - - "success": &Carapace.KeywordPositive, - "unknown": &Carapace.KeywordUnknown, - "backoff": &Carapace.KeywordUnknown, - "warn": &Carapace.KeywordAmbiguous, - "error": &Carapace.KeywordNegative, - "failed": &Carapace.KeywordNegative, - "fatal": &Carapace.KeywordNegative, - - "nonblock": &Carapace.KeywordAmbiguous, - "block": &Carapace.KeywordNegative, - - "ondemand": &Carapace.KeywordAmbiguous, -} - -var keywordReplacer = strings.NewReplacer( - "-", "", - "_", "", -) - -// ForKeyword returns the style for given keyword. -func ForKeyword(s string, _ Context) string { - if _style, ok := keywords[keywordReplacer.Replace(strings.ToLower(s))]; ok { - return *_style - } - return Default -} diff --git a/vendor/github.com/rsteube/carapace/pkg/style/loglevel.go b/vendor/github.com/rsteube/carapace/pkg/style/loglevel.go deleted file mode 100644 index 8d7745e..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/style/loglevel.go +++ /dev/null @@ -1,22 +0,0 @@ -package style - -import ( - "strings" -) - -// ForLogLevel returns the style for given log level. -func ForLogLevel(s string, _ Context) string { - return map[string]string{ - "trace": Carapace.LogLevelTrace, - "debug": Carapace.LogLevelDebug, - "vdebug": Carapace.LogLevelDebug, - "info": Carapace.LogLevelInfo, - "warn": Carapace.LogLevelWarning, - "warning": Carapace.LogLevelWarning, - "err": Carapace.LogLevelError, - "error": Carapace.LogLevelError, - "crit": Carapace.LogLevelCritical, - "critical": Carapace.LogLevelCritical, - "fatal": Carapace.LogLevelFatal, - }[strings.ToLower(s)] -} diff --git a/vendor/github.com/rsteube/carapace/pkg/style/path.go b/vendor/github.com/rsteube/carapace/pkg/style/path.go deleted file mode 100644 index 7b22bf8..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/style/path.go +++ /dev/null @@ -1,59 +0,0 @@ -package style - -import ( - "github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors" - "github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui" -) - -type Context interface { - Abs(s string) (string, error) - Getenv(key string) string - LookupEnv(key string) (string, bool) -} - -// ForPath returns the style for given path -// -// /tmp/locally/reachable/file.txt -func ForPath(path string, sc Context) string { - if abs, err := sc.Abs(path); err == nil { - path = abs - } - return fromSGR(lscolors.GetColorist(sc.Getenv("LS_COLORS")).GetStyle(path)) -} - -// ForPath returns the style for given path by extension only -// -// /tmp/non/existing/file.txt -func ForPathExt(path string, sc Context) string { - return fromSGR(lscolors.GetColorist(sc.Getenv("LS_COLORS")).GetStyleExt(path)) -} - -func fromSGR(sgr string) string { - s := ui.StyleFromSGR(sgr) - result := []string{"fg-default", "bg-default"} - if s.Foreground != nil { - result = append(result, s.Foreground.String()) - } - if s.Background != nil { - result = append(result, "bg-"+s.Background.String()) - } - if s.Bold { - result = append(result, Bold) - } - if s.Dim { - result = append(result, Dim) - } - if s.Italic { - result = append(result, Italic) - } - if s.Underlined { - result = append(result, Underlined) - } - if s.Blink { - result = append(result, Blink) - } - if s.Inverse { - result = append(result, Inverse) - } - return Of(result...) -} diff --git a/vendor/github.com/rsteube/carapace/pkg/style/style.go b/vendor/github.com/rsteube/carapace/pkg/style/style.go deleted file mode 100644 index 5729ed7..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/style/style.go +++ /dev/null @@ -1,78 +0,0 @@ -// Package style provide display coloring -package style - -import ( - "strings" - - "github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui" -) - -var ( - Default = "" - - Black = "black" - Red = "red" - Green = "green" - Yellow = "yellow" - Blue = "blue" - Magenta = "magenta" - Cyan = "cyan" - White = "white" - Gray = Of(Dim, White) - - BrightBlack = "bright-black" - BrightRed = "bright-red" - BrightGreen = "bright-green" - BrightYellow = "bright-yellow" - BrightBlue = "bright-blue" - BrightMagenta = "bright-magenta" - BrightCyan = "bright-cyan" - BrightWhite = "bright-white" - - BgBlack = "bg-black" - BgRed = "bg-red" - BgGreen = "bg-green" - BgYellow = "bg-yellow" - BgBlue = "bg-blue" - BgMagenta = "bg-magenta" - BgCyan = "bg-cyan" - BgWhite = "bg-white" - - BgBrightBlack = "bg-bright-black" - BgBrightRed = "bg-bright-red" - BgBrightGreen = "bg-bright-green" - BgBrightYellow = "bg-bright-yellow" - BgBrightBlue = "bg-bright-blue" - BgBrightMagenta = "bg-bright-magenta" - BgBrightCyan = "bg-bright-cyan" - BgBrightWhite = "bg-bright-white" - - Bold = "bold" - Dim = "dim" - Italic = "italic" - Underlined = "underlined" - Blink = "blink" - Inverse = "inverse" -) - -// Of combines different styles. -func Of(s ...string) string { return strings.Join(s, " ") } - -// XTerm256Color returns a color from the xterm 256-color palette. -func XTerm256Color(i uint8) string { return ui.XTerm256Color(i).String() } - -// TrueColor returns a 24-bit true color. -func TrueColor(r, g, b uint8) string { return ui.TrueColor(r, g, b).String() } - -// SGR returns the SGR sequence for given style. -func SGR(s string) string { return parseStyle(s).SGR() } - -func parseStyle(s string) ui.Style { - stylings := make([]ui.Styling, 0) - for _, word := range strings.Split(s, " ") { - if styling := ui.ParseStyling(word); styling != nil { - stylings = append(stylings, styling) - } - } - return ui.ApplyStyling(ui.Style{}, stylings...) -} diff --git a/vendor/github.com/rsteube/carapace/pkg/xdg/xdg.go b/vendor/github.com/rsteube/carapace/pkg/xdg/xdg.go deleted file mode 100644 index 7347a29..0000000 --- a/vendor/github.com/rsteube/carapace/pkg/xdg/xdg.go +++ /dev/null @@ -1,19 +0,0 @@ -package xdg - -import "os" - -// UserCacheDir returns the cache base directory. -func UserCacheDir() (dir string, err error) { - if dir = os.Getenv("XDG_CACHE_HOME"); dir == "" { - dir, err = os.UserCacheDir() - } - return -} - -// UserConfigDir returns the config base directory. -func UserConfigDir() (dir string, err error) { - if dir = os.Getenv("XDG_CONFIG_HOME"); dir == "" { - dir, err = os.UserConfigDir() - } - return -} diff --git a/vendor/github.com/rsteube/carapace/storage.go b/vendor/github.com/rsteube/carapace/storage.go deleted file mode 100644 index 9673ffc..0000000 --- a/vendor/github.com/rsteube/carapace/storage.go +++ /dev/null @@ -1,121 +0,0 @@ -package carapace - -import ( - "fmt" - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/uid" - "github.com/spf13/cobra" - "github.com/spf13/pflag" -) - -// TODO storage needs better naming and structure - -type entry struct { - flag ActionMap - positional []Action - positionalAny Action - dash []Action - dashAny Action - preinvoke func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action - prerun func(cmd *cobra.Command, args []string) - bridged bool -} - -type _storage map[*cobra.Command]*entry - -func (s _storage) get(cmd *cobra.Command) (e *entry) { - var ok bool - if e, ok = s[cmd]; !ok { - e = &entry{} - s[cmd] = e - } - return -} - -func (s _storage) bridge(cmd *cobra.Command) { - if entry := storage.get(cmd); !entry.bridged { - cobra.OnInitialize(func() { - registerValidArgsFunction(cmd) - registerFlagCompletion(cmd) - }) - entry.bridged = true - } -} - -func (s _storage) getFlag(cmd *cobra.Command, name string) Action { - if flag := cmd.LocalFlags().Lookup(name); flag == nil && cmd.HasParent() { - return s.getFlag(cmd.Parent(), name) - } else { - a := s.preinvoke(cmd, flag, s.get(cmd).flag[name]) - - return ActionCallback(func(c Context) Action { // TODO verify order of execution is correct - invoked := a.Invoke(c) - if invoked.meta.Usage == "" { - invoked.meta.Usage = flag.Usage - } - return invoked.ToA() - }) - } -} - -func (s _storage) preRun(cmd *cobra.Command, args []string) { - if entry := s.get(cmd); entry.prerun != nil { - LOG.Printf("executing PreRun for %#v with args %#v", cmd.Name(), args) - entry.prerun(cmd, args) - } -} - -func (s _storage) preinvoke(cmd *cobra.Command, flag *pflag.Flag, action Action) Action { - a := action - if entry := s.get(cmd); entry.preinvoke != nil { - a = ActionCallback(func(c Context) Action { - return entry.preinvoke(cmd, flag, action) - }) - } - - if cmd.HasParent() { - return s.preinvoke(cmd.Parent(), flag, a) - } - return a -} - -func (s _storage) getPositional(cmd *cobra.Command, index int) Action { - entry := s.get(cmd) - isDash := common.IsDash(cmd) - - var a Action - switch { - case !isDash && len(entry.positional) > index: - a = s.preinvoke(cmd, nil, entry.positional[index]) - case !isDash: - a = s.preinvoke(cmd, nil, entry.positionalAny) - case len(entry.dash) > index: - a = s.preinvoke(cmd, nil, entry.dash[index]) - default: - a = s.preinvoke(cmd, nil, entry.dashAny) - } - - return ActionCallback(func(c Context) Action { - invoked := a.Invoke(c) - if invoked.meta.Usage == "" && len(strings.Fields(cmd.Use)) > 1 { - invoked.meta.Usage = cmd.Use - } - return invoked.ToA() - }) -} - -func (s _storage) check() []string { - errors := make([]string, 0) - for cmd, entry := range s { - for name := range entry.flag { - if flag := cmd.LocalFlags().Lookup(name); flag == nil { - errors = append(errors, fmt.Sprintf("unknown flag for %s: %s\n", uid.Command(cmd), name)) - } - } - } - return errors -} - -var storage = make(_storage) diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi/LICENSE b/vendor/github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi/LICENSE deleted file mode 100644 index 00abe0d..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Andrew Carlson - -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/rsteube/carapace/third_party/github.com/acarl005/stripansi/stripansi.go b/vendor/github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi/stripansi.go deleted file mode 100644 index 235732a..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi/stripansi.go +++ /dev/null @@ -1,13 +0,0 @@ -package stripansi - -import ( - "regexp" -) - -const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))" - -var re = regexp.MustCompile(ansi) - -func Strip(str string) string { - return re.ReplaceAllString(str, "") -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/LICENSE b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/LICENSE deleted file mode 100644 index 1de55b7..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 drone.io - -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/rsteube/carapace/third_party/github.com/drone/envsubst/eval.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/eval.go deleted file mode 100644 index 375ca4c..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/eval.go +++ /dev/null @@ -1,19 +0,0 @@ -package envsubst - -import "os" - -// Eval replaces ${var} in the string based on the mapping function. -func Eval(s string, mapping func(string) string) (string, error) { - t, err := Parse(s) - if err != nil { - return s, err - } - return t.Execute(mapping) -} - -// EvalEnv replaces ${var} in the string according to the values of the -// current environment variables. References to undefined variables are -// replaced by the empty string. -func EvalEnv(s string) (string, error) { - return Eval(s, os.Getenv) -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/funcs.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/funcs.go deleted file mode 100644 index a3ed0a6..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/funcs.go +++ /dev/null @@ -1,246 +0,0 @@ -package envsubst - -import ( - "strconv" - "strings" - "unicode" - "unicode/utf8" - - "github.com/rsteube/carapace/third_party/github.com/drone/envsubst/path" -) - -// defines a parameter substitution function. -type substituteFunc func(string, ...string) string - -// toLen returns the length of string s. -func toLen(s string, args ...string) string { - return strconv.Itoa(len(s)) -} - -// toLower returns a copy of the string s with all characters -// mapped to their lower case. -func toLower(s string, args ...string) string { - return strings.ToLower(s) -} - -// toUpper returns a copy of the string s with all characters -// mapped to their upper case. -func toUpper(s string, args ...string) string { - return strings.ToUpper(s) -} - -// toLowerFirst returns a copy of the string s with the first -// character mapped to its lower case. -func toLowerFirst(s string, args ...string) string { - if s == "" { - return s - } - r, n := utf8.DecodeRuneInString(s) - return string(unicode.ToLower(r)) + s[n:] -} - -// toUpperFirst returns a copy of the string s with the first -// character mapped to its upper case. -func toUpperFirst(s string, args ...string) string { - if s == "" { - return s - } - r, n := utf8.DecodeRuneInString(s) - return string(unicode.ToUpper(r)) + s[n:] -} - -// toDefault returns a copy of the string s if not empty, else -// returns a concatenation of the args without a separator. -func toDefault(s string, args ...string) string { - if len(s) == 0 && len(args) > 0 { - // don't use any separator - s = strings.Join(args, "") - } - return s -} - -// toSubstr returns a slice of the string s at the specified -// length and position. -func toSubstr(s string, args ...string) string { - if len(args) == 0 { - return s // should never happen - } - - pos, err := strconv.Atoi(args[0]) - if err != nil { - // bash returns the string if the position - // cannot be parsed. - return s - } - - if pos < 0 { - // if pos is negative (counts from the end) add it - // to length to get first character offset - pos = len(s) + pos - - // if negative offset exceeds the length of the string - // start from 0 - if pos < 0 { - pos = 0 - } - } - - if len(args) == 1 { - if pos < len(s) { - return s[pos:] - } - // if the position exceeds the length of the - // string an empty string is returned - return "" - } - - length, err := strconv.Atoi(args[1]) - if err != nil { - // bash returns the string if the length - // cannot be parsed. - return s - } - - if pos+length >= len(s) { - if pos < len(s) { - // if the position exceeds the length of the - // string just return the rest of it like bash - return s[pos:] - } - // if the position exceeds the length of the - // string an empty string is returned - return "" - } - - return s[pos : pos+length] -} - -// replaceAll returns a copy of the string s with all instances -// of the substring replaced with the replacement string. -func replaceAll(s string, args ...string) string { - switch len(args) { - case 0: - return s - case 1: - return strings.Replace(s, args[0], "", -1) - default: - return strings.Replace(s, args[0], args[1], -1) - } -} - -// replaceFirst returns a copy of the string s with the first -// instance of the substring replaced with the replacement string. -func replaceFirst(s string, args ...string) string { - switch len(args) { - case 0: - return s - case 1: - return strings.Replace(s, args[0], "", 1) - default: - return strings.Replace(s, args[0], args[1], 1) - } -} - -// replacePrefix returns a copy of the string s with the matching -// prefix replaced with the replacement string. -func replacePrefix(s string, args ...string) string { - if len(args) != 2 { - return s - } - if strings.HasPrefix(s, args[0]) { - return strings.Replace(s, args[0], args[1], 1) - } - return s -} - -// replaceSuffix returns a copy of the string s with the matching -// suffix replaced with the replacement string. -func replaceSuffix(s string, args ...string) string { - if len(args) != 2 { - return s - } - if strings.HasSuffix(s, args[0]) { - s = strings.TrimSuffix(s, args[0]) - s = s + args[1] - } - return s -} - -// TODO - -func trimShortestPrefix(s string, args ...string) string { - if len(args) != 0 { - s = trimShortest(s, args[0]) - } - return s -} - -func trimShortestSuffix(s string, args ...string) string { - if len(args) != 0 { - r := reverse(s) - rarg := reverse(args[0]) - s = reverse(trimShortest(r, rarg)) - } - return s -} - -func trimLongestPrefix(s string, args ...string) string { - if len(args) != 0 { - s = trimLongest(s, args[0]) - } - return s -} - -func trimLongestSuffix(s string, args ...string) string { - if len(args) != 0 { - r := reverse(s) - rarg := reverse(args[0]) - s = reverse(trimLongest(r, rarg)) - } - return s -} - -func trimShortest(s, arg string) string { - var shortestMatch string - for i := 0; i < len(s); i++ { - match, err := path.Match(arg, s[0:len(s)-i]) - - if err != nil { - return s - } - - if match { - shortestMatch = s[0 : len(s)-i] - } - } - - if shortestMatch != "" { - return strings.TrimPrefix(s, shortestMatch) - } - - return s -} - -func trimLongest(s, arg string) string { - for i := 0; i < len(s); i++ { - match, err := path.Match(arg, s[0:len(s)-i]) - - if err != nil { - return s - } - - if match { - return strings.TrimPrefix(s, s[0:len(s)-i]) - } - } - - return s -} - -func reverse(s string) string { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r) -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/node.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/node.go deleted file mode 100644 index 09787eb..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/node.go +++ /dev/null @@ -1,86 +0,0 @@ -package parse - -// Node is an element in the parse tree. -type Node interface { - node() -} - -// empty string node -var empty = new(TextNode) - -// a template is represented by a tree consisting of one -// or more of the following nodes. -type ( - // TextNode represents a string of text. - TextNode struct { - Value string - } - - // FuncNode represents a string function. - FuncNode struct { - Param string - Name string - Args []Node - } - - // ListNode represents a list of nodes. - ListNode struct { - Nodes []Node - } - - // ParamNode struct{ - // Name string - // } - // - // CaseNode struct { - // Name string - // First bool - // } - // - // LowerNode struct { - // Name string - // First bool - // } - // - // SubstrNode struct { - // Name string - // Pos Node - // Len Node - // } - // - // ReplaceNode struct { - // Name string - // Substring Node - // Replacement Node - // } - // - // TrimNode struct{ - // - // } - // - // DefaultNode struct { - // Name string - // Default Node - // } -) - -// newTextNode returns a new TextNode. -func newTextNode(text string) *TextNode { - return &TextNode{Value: text} -} - -// newListNode returns a new ListNode. -func newListNode(nodes ...Node) *ListNode { - return &ListNode{Nodes: nodes} -} - -// newFuncNode returns a new FuncNode. -func newFuncNode(name string) *FuncNode { - return &FuncNode{Param: name} -} - -// node() defines the node in a parse tree - -func (*TextNode) node() {} -func (*ListNode) node() {} -func (*FuncNode) node() {} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/parse.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/parse.go deleted file mode 100644 index bc418fb..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/parse.go +++ /dev/null @@ -1,402 +0,0 @@ -package parse - -import ( - "errors" -) - -var ( - // ErrBadSubstitution represents a substitution parsing error. - ErrBadSubstitution = errors.New("bad substitution") - - // ErrMissingClosingBrace represents a missing closing brace "}" error. - ErrMissingClosingBrace = errors.New("missing closing brace") - - // ErrParseVariableName represents the error when unable to parse a - // variable name within a substitution. - ErrParseVariableName = errors.New("unable to parse variable name") - - // ErrParseFuncSubstitution represents the error when unable to parse the - // substitution within a function parameter. - ErrParseFuncSubstitution = errors.New("unable to parse substitution within function") - - // ErrParseDefaultFunction represent the error when unable to parse a - // default function. - ErrParseDefaultFunction = errors.New("unable to parse default function") -) - -// Tree is the representation of a single parsed SQL statement. -type Tree struct { - Root Node - - // Parsing only; cleared after parse. - scanner *scanner -} - -// Parse parses the string and returns a Tree. -func Parse(buf string) (*Tree, error) { - t := new(Tree) - t.scanner = new(scanner) - return t.Parse(buf) -} - -// Parse parses the string buffer to construct an ast -// representation for expansion. -func (t *Tree) Parse(buf string) (tree *Tree, err error) { - t.scanner.init(buf) - t.Root, err = t.parseAny() - return t, err -} - -func (t *Tree) parseAny() (Node, error) { - t.scanner.accept = acceptRune - t.scanner.mode = scanIdent | scanLbrack | scanEscape - t.scanner.escapeChars = dollar - - switch t.scanner.scan() { - case tokenIdent: - left := newTextNode( - t.scanner.string(), - ) - right, err := t.parseAny() - switch { - case err != nil: - return nil, err - case right == empty: - return left, nil - } - return newListNode(left, right), nil - case tokenEOF: - return empty, nil - case tokenLbrack: - left, err := t.parseFunc() - if err != nil { - return nil, err - } - - right, err := t.parseAny() - switch { - case err != nil: - return nil, err - case right == empty: - return left, nil - } - return newListNode(left, right), nil - } - - return nil, ErrBadSubstitution -} - -func (t *Tree) parseFunc() (Node, error) { - // Turn on all escape characters - t.scanner.escapeChars = escapeAll - switch t.scanner.peek() { - case '#': - return t.parseLenFunc() - } - - var name string - t.scanner.accept = acceptIdent - t.scanner.mode = scanIdent - - switch t.scanner.scan() { - case tokenIdent: - name = t.scanner.string() - default: - return nil, ErrParseVariableName - } - - switch t.scanner.peek() { - case ':': - return t.parseDefaultOrSubstr(name) - case '=': - return t.parseDefaultFunc(name) - case ',', '^': - return t.parseCasingFunc(name) - case '/': - return t.parseReplaceFunc(name) - case '#': - return t.parseRemoveFunc(name, acceptHashFunc) - case '%': - return t.parseRemoveFunc(name, acceptPercentFunc) - } - - t.scanner.accept = acceptIdent - t.scanner.mode = scanRbrack - switch t.scanner.scan() { - case tokenRbrack: - return newFuncNode(name), nil - default: - return nil, ErrMissingClosingBrace - } -} - -// parse a substitution function parameter. -func (t *Tree) parseParam(accept acceptFunc, mode byte) (Node, error) { - t.scanner.accept = accept - t.scanner.mode = mode | scanLbrack - switch t.scanner.scan() { - case tokenLbrack: - return t.parseFunc() - case tokenIdent: - return newTextNode( - t.scanner.string(), - ), nil - case tokenRbrack: - return newTextNode( - t.scanner.string(), - ), nil - default: - return nil, ErrParseFuncSubstitution - } -} - -// parse either a default or substring substitution function. -func (t *Tree) parseDefaultOrSubstr(name string) (Node, error) { - t.scanner.read() - r := t.scanner.peek() - t.scanner.unread() - switch r { - case '=', '-', '?', '+': - return t.parseDefaultFunc(name) - default: - return t.parseSubstrFunc(name) - } -} - -// parses the ${param:offset} string function -// parses the ${param:offset:length} string function -func (t *Tree) parseSubstrFunc(name string) (Node, error) { - node := new(FuncNode) - node.Param = name - - t.scanner.accept = acceptOneColon - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Name = t.scanner.string() - default: - return nil, ErrBadSubstitution - } - - // scan arg[1] - { - param, err := t.parseParam(rejectColonClose, scanIdent) - if err != nil { - return nil, err - } - - // param.Value = t.scanner.string() - node.Args = append(node.Args, param) - } - - // expect delimiter or close - t.scanner.accept = acceptColon - t.scanner.mode = scanIdent | scanRbrack - switch t.scanner.scan() { - case tokenRbrack: - return node, nil - case tokenIdent: - // no-op - default: - return nil, ErrBadSubstitution - } - - // scan arg[2] - { - param, err := t.parseParam(acceptNotClosing, scanIdent) - if err != nil { - return nil, err - } - node.Args = append(node.Args, param) - } - - return node, t.consumeRbrack() -} - -// parses the ${param%word} string function -// parses the ${param%%word} string function -// parses the ${param#word} string function -// parses the ${param##word} string function -func (t *Tree) parseRemoveFunc(name string, accept acceptFunc) (Node, error) { - node := new(FuncNode) - node.Param = name - - t.scanner.accept = accept - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Name = t.scanner.string() - default: - return nil, ErrBadSubstitution - } - - // scan arg[1] - { - param, err := t.parseParam(acceptNotClosing, scanIdent) - if err != nil { - return nil, err - } - - // param.Value = t.scanner.string() - node.Args = append(node.Args, param) - } - - return node, t.consumeRbrack() -} - -// parses the ${param/pattern/string} string function -// parses the ${param//pattern/string} string function -// parses the ${param/#pattern/string} string function -// parses the ${param/%pattern/string} string function -func (t *Tree) parseReplaceFunc(name string) (Node, error) { - node := new(FuncNode) - node.Param = name - - t.scanner.accept = acceptReplaceFunc - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Name = t.scanner.string() - default: - return nil, ErrBadSubstitution - } - - // scan arg[1] - { - param, err := t.parseParam(acceptNotSlash, scanIdent|scanEscape) - if err != nil { - return nil, err - } - node.Args = append(node.Args, param) - } - - // expect delimiter - t.scanner.accept = acceptSlash - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - // no-op - default: - return nil, ErrBadSubstitution - } - - // check for blank string - switch t.scanner.peek() { - case '}': - return node, t.consumeRbrack() - } - - // scan arg[2] - { - param, err := t.parseParam(acceptNotClosing, scanIdent|scanEscape) - if err != nil { - return nil, err - } - node.Args = append(node.Args, param) - } - - return node, t.consumeRbrack() -} - -// parses the ${parameter=word} string function -// parses the ${parameter:=word} string function -// parses the ${parameter:-word} string function -// parses the ${parameter:?word} string function -// parses the ${parameter:+word} string function -func (t *Tree) parseDefaultFunc(name string) (Node, error) { - node := new(FuncNode) - node.Param = name - - t.scanner.accept = acceptDefaultFunc - if t.scanner.peek() == '=' { - t.scanner.accept = acceptOneEqual - } - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Name = t.scanner.string() - default: - return nil, ErrParseDefaultFunction - } - - // loop through all possible runes in default param - for { - // this acts as the break condition. Peek to see if we reached the end - switch t.scanner.peek() { - case '}': - return node, t.consumeRbrack() - } - param, err := t.parseParam(acceptNotClosing, scanIdent) - if err != nil { - return nil, err - } - - node.Args = append(node.Args, param) - } -} - -// parses the ${param,} string function -// parses the ${param,,} string function -// parses the ${param^} string function -// parses the ${param^^} string function -func (t *Tree) parseCasingFunc(name string) (Node, error) { - node := new(FuncNode) - node.Param = name - - t.scanner.accept = acceptCasingFunc - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Name = t.scanner.string() - default: - return nil, ErrBadSubstitution - } - - return node, t.consumeRbrack() -} - -// parses the ${#param} string function -func (t *Tree) parseLenFunc() (Node, error) { - node := new(FuncNode) - - t.scanner.accept = acceptOneHash - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Name = t.scanner.string() - default: - return nil, ErrBadSubstitution - } - - t.scanner.accept = acceptIdent - t.scanner.mode = scanIdent - switch t.scanner.scan() { - case tokenIdent: - node.Param = t.scanner.string() - default: - return nil, ErrBadSubstitution - } - - return node, t.consumeRbrack() -} - -// consumeRbrack consumes a right closing bracket. If a closing -// bracket token is not consumed an ErrBadSubstitution is returned. -func (t *Tree) consumeRbrack() error { - t.scanner.mode = scanRbrack - if t.scanner.scan() != tokenRbrack { - return ErrBadSubstitution - } - return nil -} - -// consumeDelimiter consumes a function argument delimiter. If a -// delimiter is not consumed an ErrBadSubstitution is returned. -// func (t *Tree) consumeDelimiter(accept acceptFunc, mode uint) error { -// t.scanner.accept = accept -// t.scanner.mode = mode -// if t.scanner.scan() != tokenRbrack { -// return ErrBadSubstitution -// } -// return nil -// } diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/scan.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/scan.go deleted file mode 100644 index 2710879..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse/scan.go +++ /dev/null @@ -1,294 +0,0 @@ -package parse - -import ( - "unicode" - "unicode/utf8" -) - -// eof rune sent when end of file is reached -var eof = rune(0) - -// token is a lexical token. -type token uint - -// list of lexical tokens. -const ( - // special tokens - tokenIllegal token = iota - tokenEOF - - // identifiers and literals - tokenIdent - - // operators and delimiters - tokenLbrack - tokenRbrack - tokenQuote -) - -// predefined mode bits to control recognition of tokens. -const ( - scanIdent byte = 1 << iota - scanLbrack - scanRbrack - scanEscape -) - -// predefined mode bits to control escape tokens. -const ( - dollar byte = 1 << iota - backslash - escapeAll = dollar | backslash -) - -// returns true if rune is accepted. -type acceptFunc func(r rune, i int) bool - -// scanner implements a lexical scanner that reads unicode -// characters and tokens from a string buffer. -type scanner struct { - buf string - pos int - start int - width int - mode byte - escapeChars byte - - accept acceptFunc -} - -// init initializes a scanner with a new buffer. -func (s *scanner) init(buf string) { - s.buf = buf - s.pos = 0 - s.start = 0 - s.width = 0 - s.accept = nil -} - -// read returns the next unicode character. It returns eof at -// the end of the string buffer. -func (s *scanner) read() rune { - if s.pos >= len(s.buf) { - s.width = 0 - return eof - } - r, w := utf8.DecodeRuneInString(s.buf[s.pos:]) - s.width = w - s.pos += s.width - return r -} - -func (s *scanner) unread() { - s.pos -= s.width -} - -// skip skips over the curring unicode character in the buffer -// by slicing and removing from the buffer. -func (s *scanner) skip() { - l := s.buf[:s.pos-1] - r := s.buf[s.pos:] - s.buf = l + r -} - -// peek returns the next unicode character in the buffer without -// advancing the scanner. It returns eof if the scanner's position -// is at the last character of the source. -func (s *scanner) peek() rune { - r := s.read() - s.unread() - return r -} - -// string returns the string corresponding to the most recently -// scanned token. Valid after calling scan(). -func (s *scanner) string() string { - return s.buf[s.start:s.pos] -} - -// tests if the bit exists for a given character bit -func (s *scanner) shouldEscape(character byte) bool { - return s.escapeChars&character != 0 -} - -// scan reads the next token or Unicode character from source and -// returns it. It returns EOF at the end of the source. -func (s *scanner) scan() token { - s.start = s.pos - r := s.read() - switch { - case r == eof: - return tokenEOF - case s.scanLbrack(r): - return tokenLbrack - case s.scanRbrack(r): - return tokenRbrack - case s.scanIdent(r): - return tokenIdent - } - return tokenIllegal -} - -// scanIdent reads the next token or Unicode character from source -// and returns true if the Ident character is accepted. -func (s *scanner) scanIdent(r rune) bool { - if s.mode&scanIdent == 0 { - return false - } - if s.scanEscaped(r) { - s.skip() - } else if !s.accept(r, s.pos-s.start) { - return false - } -loop: - for { - r := s.read() - switch { - case r == eof: - s.unread() - break loop - case s.scanLbrack(r): - s.unread() - s.unread() - break loop - } - if s.scanEscaped(r) { - s.skip() - continue - } - if !s.accept(r, s.pos-s.start) { - s.unread() - break loop - } - } - return true -} - -// scanLbrack reads the next token or Unicode character from source -// and returns true if the open bracket is encountered. -func (s *scanner) scanLbrack(r rune) bool { - if s.mode&scanLbrack == 0 { - return false - } - if r == '$' { - if s.read() == '{' { - return true - } - s.unread() - } - return false -} - -// scanRbrack reads the next token or Unicode character from source -// and returns true if the closing bracket is encountered. -func (s *scanner) scanRbrack(r rune) bool { - if s.mode&scanRbrack == 0 { - return false - } - return r == '}' -} - -// scanEscaped reads the next token or Unicode character from source -// and returns true if it being escaped and should be skipped. -func (s *scanner) scanEscaped(r rune) bool { - if s.mode&scanEscape == 0 { - return false - } - if r == '$' && s.shouldEscape(dollar) { - if s.peek() == '$' { - return true - } - } - if r == '\\' && s.shouldEscape(backslash) { - switch s.peek() { - case '/', '\\': - return true - default: - return false - } - } - - return false -} - -// -// scanner functions accept or reject runes. -// - -func acceptRune(r rune, i int) bool { - return true -} - -func acceptIdent(r rune, i int) bool { - return unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' -} - -func acceptColon(r rune, i int) bool { - return r == ':' -} - -func acceptOneHash(r rune, i int) bool { - return r == '#' && i == 1 -} - -func acceptNone(r rune, i int) bool { - return false -} - -func acceptNotClosing(r rune, i int) bool { - return r != '}' -} - -func acceptHashFunc(r rune, i int) bool { - return r == '#' && i < 3 -} - -func acceptPercentFunc(r rune, i int) bool { - return r == '%' && i < 3 -} - -func acceptDefaultFunc(r rune, i int) bool { - switch { - case i == 1 && r == ':': - return true - case i == 2 && (r == '=' || r == '-' || r == '?' || r == '+'): - return true - default: - return false - } -} - -func acceptReplaceFunc(r rune, i int) bool { - switch { - case i == 1 && r == '/': - return true - case i == 2 && (r == '/' || r == '#' || r == '%'): - return true - default: - return false - } -} - -func acceptOneEqual(r rune, i int) bool { - return i == 1 && r == '=' -} - -func acceptOneColon(r rune, i int) bool { - return i == 1 && r == ':' -} - -func rejectColonClose(r rune, i int) bool { - return r != ':' && r != '}' -} - -func acceptSlash(r rune, i int) bool { - return r == '/' -} - -func acceptNotSlash(r rune, i int) bool { - return r != '/' -} - -func acceptCasingFunc(r rune, i int) bool { - return (r == ',' || r == '^') && i < 3 -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/path/match.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/path/match.go deleted file mode 100644 index 2b3dfd6..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/path/match.go +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 2010 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 path - -import ( - "errors" - "unicode/utf8" -) - -// ErrBadPattern indicates a globbing pattern was malformed. -var ErrBadPattern = errors.New("syntax error in pattern") - -// Match reports whether name matches the shell file name pattern. -// The pattern syntax is: -// -// pattern: -// { term } -// term: -// '*' matches any sequence of non-/ characters -// '?' matches any single non-/ character -// '[' [ '^' ] { character-range } ']' -// character class (must be non-empty) -// c matches character c (c != '*', '?', '\\', '[') -// '\\' c matches character c -// -// character-range: -// c matches character c (c != '\\', '-', ']') -// '\\' c matches character c -// lo '-' hi matches character c for lo <= c <= hi -// -// Match requires pattern to match all of name, not just a substring. -// The only possible returned error is ErrBadPattern, when pattern -// is malformed. -func Match(pattern, name string) (matched bool, err error) { -Pattern: - for len(pattern) > 0 { - var star bool - var chunk string - star, chunk, pattern = scanChunk(pattern) - if star && chunk == "" { - // Trailing * matches rest of string unless it has a /. - // return !strings.Contains(name, "/"), nil - - // Return rest of string - return true, nil - } - // Look for match at current position. - t, ok, err := matchChunk(chunk, name) - // if we're the last chunk, make sure we've exhausted the name - // otherwise we'll give a false result even if we could still match - // using the star - if ok && (len(t) == 0 || len(pattern) > 0) { - name = t - continue - } - if err != nil { - return false, err - } - if star { - // Look for match skipping i+1 bytes. - for i := 0; i < len(name); i++ { - t, ok, err := matchChunk(chunk, name[i+1:]) - if ok { - // if we're the last chunk, make sure we exhausted the name - if len(pattern) == 0 && len(t) > 0 { - continue - } - name = t - continue Pattern - } - if err != nil { - return false, err - } - } - } - return false, nil - } - return len(name) == 0, nil -} - -// scanChunk gets the next segment of pattern, which is a non-star string -// possibly preceded by a star. -func scanChunk(pattern string) (star bool, chunk, rest string) { - for len(pattern) > 0 && pattern[0] == '*' { - pattern = pattern[1:] - star = true - } - inrange := false - var i int -Scan: - for i = 0; i < len(pattern); i++ { - switch pattern[i] { - case '\\': - // error check handled in matchChunk: bad pattern. - if i+1 < len(pattern) { - i++ - } - case '[': - inrange = true - case ']': - inrange = false - case '*': - if !inrange { - break Scan - } - } - } - return star, pattern[0:i], pattern[i:] -} - -// matchChunk checks whether chunk matches the beginning of s. -// If so, it returns the remainder of s (after the match). -// Chunk is all single-character operators: literals, char classes, and ?. -func matchChunk(chunk, s string) (rest string, ok bool, err error) { - for len(chunk) > 0 { - if len(s) == 0 { - return - } - switch chunk[0] { - case '[': - // character class - r, n := utf8.DecodeRuneInString(s) - s = s[n:] - chunk = chunk[1:] - // possibly negated - notNegated := true - if len(chunk) > 0 && chunk[0] == '^' { - notNegated = false - chunk = chunk[1:] - } - // parse all ranges - match := false - nrange := 0 - for { - if len(chunk) > 0 && chunk[0] == ']' && nrange > 0 { - chunk = chunk[1:] - break - } - var lo, hi rune - if lo, chunk, err = getEsc(chunk); err != nil { - return - } - hi = lo - if chunk[0] == '-' { - if hi, chunk, err = getEsc(chunk[1:]); err != nil { - return - } - } - if lo <= r && r <= hi { - match = true - } - nrange++ - } - if match != notNegated { - return - } - - case '?': - _, n := utf8.DecodeRuneInString(s) - s = s[n:] - chunk = chunk[1:] - - case '\\': - chunk = chunk[1:] - if len(chunk) == 0 { - err = ErrBadPattern - return - } - fallthrough - - default: - if chunk[0] != s[0] { - return - } - s = s[1:] - chunk = chunk[1:] - } - } - return s, true, nil -} - -// getEsc gets a possibly-escaped character from chunk, for a character class. -func getEsc(chunk string) (r rune, nchunk string, err error) { - if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' { - err = ErrBadPattern - return - } - if chunk[0] == '\\' { - chunk = chunk[1:] - if len(chunk) == 0 { - err = ErrBadPattern - return - } - } - r, n := utf8.DecodeRuneInString(chunk) - if r == utf8.RuneError && n == 1 { - err = ErrBadPattern - } - nchunk = chunk[n:] - if len(nchunk) == 0 { - err = ErrBadPattern - } - return -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/template.go b/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/template.go deleted file mode 100644 index 367e565..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/drone/envsubst/template.go +++ /dev/null @@ -1,157 +0,0 @@ -package envsubst - -import ( - "bytes" - "io" - "io/ioutil" - - "github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse" -) - -// state represents the state of template execution. It is not part of the -// template so that multiple executions can run in parallel. -type state struct { - template *Template - writer io.Writer - node parse.Node // current node - - // maps variable names to values - mapper func(string) string -} - -// Template is the representation of a parsed shell format string. -type Template struct { - tree *parse.Tree -} - -// Parse creates a new shell format template and parses the template -// definition from string s. -func Parse(s string) (t *Template, err error) { - t = new(Template) - t.tree, err = parse.Parse(s) - if err != nil { - return nil, err - } - return t, nil -} - -// ParseFile creates a new shell format template and parses the template -// definition from the named file. -func ParseFile(path string) (*Template, error) { - b, err := ioutil.ReadFile(path) - if err != nil { - return nil, err - } - return Parse(string(b)) -} - -// Execute applies a parsed template to the specified data mapping. -func (t *Template) Execute(mapping func(string) string) (str string, err error) { - b := new(bytes.Buffer) - s := new(state) - s.node = t.tree.Root - s.mapper = mapping - s.writer = b - err = t.eval(s) - if err != nil { - return - } - return b.String(), nil -} - -func (t *Template) eval(s *state) (err error) { - switch node := s.node.(type) { - case *parse.TextNode: - err = t.evalText(s, node) - case *parse.FuncNode: - err = t.evalFunc(s, node) - case *parse.ListNode: - err = t.evalList(s, node) - } - return err -} - -func (t *Template) evalText(s *state, node *parse.TextNode) error { - _, err := io.WriteString(s.writer, node.Value) - return err -} - -func (t *Template) evalList(s *state, node *parse.ListNode) (err error) { - for _, n := range node.Nodes { - s.node = n - err = t.eval(s) - if err != nil { - return err - } - } - return nil -} - -func (t *Template) evalFunc(s *state, node *parse.FuncNode) error { - var w = s.writer - var buf bytes.Buffer - var args []string - for _, n := range node.Args { - buf.Reset() - s.writer = &buf - s.node = n - err := t.eval(s) - if err != nil { - return err - } - args = append(args, buf.String()) - } - - // restore the origin writer - s.writer = w - s.node = node - - v := s.mapper(node.Param) - - fn := lookupFunc(node.Name, len(args)) - - _, err := io.WriteString(s.writer, fn(v, args...)) - return err -} - -// lookupFunc returns the parameters substitution function by name. If the -// named function does not exists, a default function is returned. -func lookupFunc(name string, args int) substituteFunc { - switch name { - case ",": - return toLowerFirst - case ",,": - return toLower - case "^": - return toUpperFirst - case "^^": - return toUpper - case "#": - if args == 0 { - return toLen - } - return trimShortestPrefix - case "##": - return trimLongestPrefix - case "%": - return trimShortestSuffix - case "%%": - return trimLongestSuffix - case ":": - return toSubstr - case "/#": - return replacePrefix - case "/%": - return replaceSuffix - case "/": - return replaceFirst - case "//": - return replaceAll - case "=", ":=", ":-": - return toDefault - case ":?", ":+", "-", "+": - return toDefault - default: - return toDefault - } -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/LICENSE b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/LICENSE deleted file mode 100644 index 7447ac1..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/LICENSE +++ /dev/null @@ -1,5 +0,0 @@ -Copyright (c) elvish developers and contributors, 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. 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 HOLDER 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/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/feature.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/feature.go deleted file mode 100644 index fdce6d3..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/feature.go +++ /dev/null @@ -1,115 +0,0 @@ -package lscolors - -import ( - "os" -) - -type feature int - -const ( - featureInvalid feature = iota - - featureOrphanedSymlink - featureSymlink - - featureMultiHardLink - - featureNamedPipe - featureSocket - featureDoor - featureBlockDevice - featureCharDevice - - featureWorldWritableStickyDirectory - featureWorldWritableDirectory - featureStickyDirectory - featureDirectory - - featureCapability - - featureSetuid - featureSetgid - featureExecutable - - featureRegular -) - -// Some platforms, such as Windows, have simulated UNIX style permission masks. -// On Windows the only two permission masks are 0o666 (RW) and 0o444 (RO). -const worldWritable = 0o002 - -func determineFeature(fname string, mh bool) (feature, error) { - stat, err := os.Lstat(fname) - - if err != nil { - return featureInvalid, err - } - - m := stat.Mode() - - // Symlink and OrphanedSymlink has highest precedence - if is(m, os.ModeSymlink) { - _, err := os.Stat(fname) - if err != nil { - return featureOrphanedSymlink, nil - } - return featureSymlink, nil - } - - // featureMultiHardLink - if mh && isMultiHardlink(stat) { - return featureMultiHardLink, nil - } - - // type bits features - switch { - case is(m, os.ModeNamedPipe): - return featureNamedPipe, nil - case is(m, os.ModeSocket): // Never on Windows - return featureSocket, nil - case isDoor(stat): - return featureDoor, nil - case is(m, os.ModeCharDevice): - return featureCharDevice, nil - case is(m, os.ModeDevice): - // There is no dedicated os.Mode* flag for block device. On all - // supported Unix platforms, when os.ModeDevice is set but - // os.ModeCharDevice is not, the file is a block device (i.e. - // syscall.S_IFBLK is set). On Windows, this branch is unreachable. - // - // On Plan9, this in inaccurate. - return featureBlockDevice, nil - case is(m, os.ModeDir): - // Perm bits features for directory - perm := m.Perm() - switch { - case is(m, os.ModeSticky) && is(perm, worldWritable): - return featureWorldWritableStickyDirectory, nil - case is(perm, worldWritable): - return featureWorldWritableDirectory, nil - case is(m, os.ModeSticky): - return featureStickyDirectory, nil - default: - return featureDirectory, nil - } - } - - // TODO(xiaq): Support featureCapacity - - // Perm bits features for regular files - switch { - case is(m, os.ModeSetuid): - return featureSetuid, nil - case is(m, os.ModeSetgid): - return featureSetgid, nil - case IsExecutable(stat): - return featureExecutable, nil - } - - // Check extension - return featureRegular, nil -} - -func is(m, p os.FileMode) bool { - return m&p == p -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/lscolors.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/lscolors.go deleted file mode 100644 index 5601450..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/lscolors.go +++ /dev/null @@ -1,135 +0,0 @@ -// Package lscolors provides styling of filenames based on file features. -// -// This is a reverse-engineered implementation of the parsing and -// interpretation of the LS_COLORS environmental variable used by GNU -// coreutils. -package lscolors - -import ( - "path" - "strings" - "sync" -) - -// Colorist styles filenames based on the features of the file. -type Colorist interface { - // GetStyle returns the style for the named file. - GetStyle(fname string) string - // GetStyle returns the style for the named file only by its extension. - GetStyleExt(fname string) string -} - -type colorist struct { - styleForFeature map[feature]string - styleForExt map[string]string -} - -const defaultLsColorString = `rs=:di=01;34:ln=01;36:mh=:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=36:*.au=36:*.flac=36:*.mid=36:*.midi=36:*.mka=36:*.mp3=36:*.mpc=36:*.ogg=36:*.ra=36:*.wav=36:*.axa=36:*.oga=36:*.spx=36:*.xspf=36:` - -var ( - lastColorist *colorist - lastColoristMutex sync.Mutex - lastLsColors string -) - -func init() { - lastColorist = parseLsColor(defaultLsColorString) -} - -func GetColorist(lsColorString string) Colorist { - lastColoristMutex.Lock() - defer lastColoristMutex.Unlock() - - s := getLsColors(lsColorString) - if lastLsColors != s { - lastLsColors = s - lastColorist = parseLsColor(s) - } - return lastColorist -} - -func getLsColors(lsColorString string) string { - if len(lsColorString) == 0 { - return defaultLsColorString - } - return lsColorString -} - -var featureForName = map[string]feature{ - "rs": featureRegular, - "di": featureDirectory, - "ln": featureSymlink, - "mh": featureMultiHardLink, - "pi": featureNamedPipe, - "so": featureSocket, - "do": featureDoor, - "bd": featureBlockDevice, - "cd": featureCharDevice, - "or": featureOrphanedSymlink, - "su": featureSetuid, - "sg": featureSetgid, - "ca": featureCapability, - "tw": featureWorldWritableStickyDirectory, - "ow": featureWorldWritableDirectory, - "st": featureStickyDirectory, - "ex": featureExecutable, -} - -// parseLsColor parses a string in the LS_COLORS format into lsColor. Erroneous -// fields are silently ignored. -func parseLsColor(s string) *colorist { - lc := &colorist{make(map[feature]string), make(map[string]string)} - for _, spec := range strings.Split(s, ":") { - words := strings.Split(spec, "=") - if len(words) != 2 { - continue - } - key, value := words[0], words[1] - filterValues := []string{} - for _, splitValue := range strings.Split(value, ";") { - if strings.Count(splitValue, "0") == len(splitValue) { - continue - } - filterValues = append(filterValues, splitValue) - } - if len(filterValues) == 0 { - continue - } - value = strings.Join(filterValues, ";") - if strings.HasPrefix(key, "*.") { - lc.styleForExt[key[1:]] = value - } else { - feature, ok := featureForName[key] - if !ok { - continue - } - lc.styleForFeature[feature] = value - } - } - return lc -} - -func (lc *colorist) GetStyle(fname string) string { - mh := strings.Trim(lc.styleForFeature[featureMultiHardLink], "0") != "" - // TODO Handle error from determineFeature - feature, _ := determineFeature(fname, mh) - if feature == featureRegular { - if ext := path.Ext(fname); ext != "" { - if style, ok := lc.styleForExt[ext]; ok { - return style - } - } - } - return lc.styleForFeature[feature] -} - -func (lc *colorist) GetStyleExt(fname string) string { - if !strings.HasSuffix(fname, "/") { - if ext := path.Ext(fname); ext != "" { - if style, ok := lc.styleForExt[ext]; ok { - return style - } - } - } - return lc.styleForFeature[featureDirectory] -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_notsolaris.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_notsolaris.go deleted file mode 100644 index 37ae6e1..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_notsolaris.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !solaris -// +build !solaris - -package lscolors - -import "os" - -func isDoor(info os.FileInfo) bool { - // Doors are only supported on Solaris. - return false -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_solaris.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_solaris.go deleted file mode 100644 index 7824f12..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_solaris.go +++ /dev/null @@ -1,13 +0,0 @@ -package lscolors - -import ( - "os" - "syscall" -) - -// Taken from Illumos header file. -const sIFDOOR = 0xD000 - -func isDoor(info os.FileInfo) bool { - return info.Sys().(*syscall.Stat_t).Mode&sIFDOOR == sIFDOOR -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_unix.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_unix.go deleted file mode 100644 index 37ab1d3..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_unix.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !windows && !plan9 -// +build !windows,!plan9 - -package lscolors - -import ( - "os" - "syscall" -) - -func isMultiHardlink(info os.FileInfo) bool { - return info.Sys().(*syscall.Stat_t).Nlink > 1 -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_windows.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_windows.go deleted file mode 100644 index abc7e72..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/stat_windows.go +++ /dev/null @@ -1,10 +0,0 @@ -package lscolors - -import "os" - -func isMultiHardlink(info os.FileInfo) bool { - // Windows supports hardlinks, but it is not exposed directly. We omit the - // implementation for now. - // TODO: Maybe implement it? - return false -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/util.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/util.go deleted file mode 100644 index fb50288..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors/util.go +++ /dev/null @@ -1,14 +0,0 @@ -package lscolors - -import "os" - -// IsExecutable returns whether the FileInfo refers to an executable file. -// -// This is determined by permission bits on UNIX, and by file name on Windows. -func IsExecutable(stat os.FileInfo) bool { - return isExecutable(stat) -} - -func isExecutable(stat os.FileInfo) bool { - return !stat.IsDir() && stat.Mode()&0o111 != 0 -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/color.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/color.go deleted file mode 100644 index fb84672..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/color.go +++ /dev/null @@ -1,117 +0,0 @@ -package ui - -import ( - "fmt" - "strconv" - "strings" -) - -// Color represents a color. -type Color interface { - fgSGR() string - bgSGR() string - String() string -} - -// Builtin ANSI colors. -var ( - Black Color = ansiColor(0) - Red Color = ansiColor(1) - Green Color = ansiColor(2) - Yellow Color = ansiColor(3) - Blue Color = ansiColor(4) - Magenta Color = ansiColor(5) - Cyan Color = ansiColor(6) - White Color = ansiColor(7) - - BrightBlack Color = ansiBrightColor(0) - BrightRed Color = ansiBrightColor(1) - BrightGreen Color = ansiBrightColor(2) - BrightYellow Color = ansiBrightColor(3) - BrightBlue Color = ansiBrightColor(4) - BrightMagenta Color = ansiBrightColor(5) - BrightCyan Color = ansiBrightColor(6) - BrightWhite Color = ansiBrightColor(7) -) - -// XTerm256Color returns a color from the xterm 256-color palette. -func XTerm256Color(i uint8) Color { return xterm256Color(i) } - -// TrueColor returns a 24-bit true color. -func TrueColor(r, g, b uint8) Color { return trueColor{r, g, b} } - -var colorNames = []string{ - "black", "red", "green", "yellow", - "blue", "magenta", "cyan", "white", -} - -var colorByName = map[string]Color{ - "black": Black, - "red": Red, - "green": Green, - "yellow": Yellow, - "blue": Blue, - "magenta": Magenta, - "cyan": Cyan, - "white": White, - - "bright-black": BrightBlack, - "bright-red": BrightRed, - "bright-green": BrightGreen, - "bright-yellow": BrightYellow, - "bright-blue": BrightBlue, - "bright-magenta": BrightMagenta, - "bright-cyan": BrightCyan, - "bright-white": BrightWhite, -} - -type ansiColor uint8 - -func (c ansiColor) fgSGR() string { return strconv.Itoa(30 + int(c)) } -func (c ansiColor) bgSGR() string { return strconv.Itoa(40 + int(c)) } -func (c ansiColor) String() string { return colorNames[c] } - -type ansiBrightColor uint8 - -func (c ansiBrightColor) fgSGR() string { return strconv.Itoa(90 + int(c)) } -func (c ansiBrightColor) bgSGR() string { return strconv.Itoa(100 + int(c)) } -func (c ansiBrightColor) String() string { return "bright-" + colorNames[c] } - -type xterm256Color uint8 - -func (c xterm256Color) fgSGR() string { return "38;5;" + strconv.Itoa(int(c)) } -func (c xterm256Color) bgSGR() string { return "48;5;" + strconv.Itoa(int(c)) } -func (c xterm256Color) String() string { return "color" + strconv.Itoa(int(c)) } - -type trueColor struct{ R, G, B uint8 } - -func (c trueColor) fgSGR() string { return "38;2;" + c.rgbSGR() } -func (c trueColor) bgSGR() string { return "48;2;" + c.rgbSGR() } - -func (c trueColor) String() string { - return fmt.Sprintf("#%02x%02x%02x", c.R, c.G, c.B) -} - -func (c trueColor) rgbSGR() string { - return fmt.Sprintf("%d;%d;%d", c.R, c.G, c.B) -} - -func parseColor(name string) Color { - if color, ok := colorByName[name]; ok { - return color - } - if strings.HasPrefix(name, "color") { - i, err := strconv.Atoi(name[5:]) - if err == nil && 0 <= i && i < 256 { - return XTerm256Color(uint8(i)) - } - } else if strings.HasPrefix(name, "#") && len(name) == 7 { - r, rErr := strconv.ParseUint(name[1:3], 16, 8) - g, gErr := strconv.ParseUint(name[3:5], 16, 8) - b, bErr := strconv.ParseUint(name[5:7], 16, 8) - if rErr == nil && gErr == nil && bErr == nil { - return TrueColor(uint8(r), uint8(g), uint8(b)) - } - } - return nil -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/parse_sgr.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/parse_sgr.go deleted file mode 100644 index 21ea697..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/parse_sgr.go +++ /dev/null @@ -1,89 +0,0 @@ -package ui - -import ( - "strconv" - "strings" -) - -const sgrPrefix = "\033[" - -var sgrStyling = map[int]Styling{ - 0: Reset, - 1: Bold, - 2: Dim, - 4: Underlined, - 5: Blink, - 7: Inverse, -} - -// StyleFromSGR builds a Style from an SGR sequence. -func StyleFromSGR(s string) Style { - var ret Style - StylingFromSGR(s).transform(&ret) - return ret -} - -// StylingFromSGR builds a Style from an SGR sequence. -func StylingFromSGR(s string) Styling { - styling := jointStyling{} - codes := getSGRCodes(s) - if len(codes) == 0 { - return Reset - } - for len(codes) > 0 { - code := codes[0] - consume := 1 - var moreStyling Styling - - switch { - case sgrStyling[code] != nil: - moreStyling = sgrStyling[code] - case 30 <= code && code <= 37: - moreStyling = Fg(ansiColor(code - 30)) - case 40 <= code && code <= 47: - moreStyling = Bg(ansiColor(code - 40)) - case 90 <= code && code <= 97: - moreStyling = Fg(ansiBrightColor(code - 90)) - case 100 <= code && code <= 107: - moreStyling = Bg(ansiBrightColor(code - 100)) - case code == 38 && len(codes) >= 3 && codes[1] == 5: - moreStyling = Fg(xterm256Color(codes[2])) - consume = 3 - case code == 48 && len(codes) >= 3 && codes[1] == 5: - moreStyling = Bg(xterm256Color(codes[2])) - consume = 3 - case code == 38 && len(codes) >= 5 && codes[1] == 2: - moreStyling = Fg(trueColor{ - uint8(codes[2]), uint8(codes[3]), uint8(codes[4]), - }) - consume = 5 - case code == 48 && len(codes) >= 5 && codes[1] == 2: - moreStyling = Bg(trueColor{ - uint8(codes[2]), uint8(codes[3]), uint8(codes[4]), - }) - consume = 5 - default: - // Do nothing; skip this code - } - codes = codes[consume:] - if moreStyling != nil { - styling = append(styling, moreStyling) - } - } - return styling -} - -func getSGRCodes(s string) []int { - var codes []int - for _, part := range strings.Split(s, ";") { - if part == "" { - codes = append(codes, 0) - } else { - code, err := strconv.Atoi(part) - if err == nil { - codes = append(codes, code) - } - } - } - return codes -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/style.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/style.go deleted file mode 100644 index c4e8c05..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/style.go +++ /dev/null @@ -1,101 +0,0 @@ -package ui - -import ( - "fmt" - "strings" -) - -// Style specifies how something (mostly a string) shall be displayed. -type Style struct { - Foreground Color - Background Color - Bold bool - Dim bool - Italic bool - Underlined bool - Blink bool - Inverse bool -} - -// SGR returns SGR sequence for the style. -func (s Style) SGR() string { - var sgr []string - - addIf := func(b bool, code string) { - if b { - sgr = append(sgr, code) - } - } - addIf(s.Bold, "1") - addIf(s.Dim, "2") - addIf(s.Italic, "3") - addIf(s.Underlined, "4") - addIf(s.Blink, "5") - addIf(s.Inverse, "7") - if s.Foreground != nil { - sgr = append(sgr, s.Foreground.fgSGR()) - } - if s.Background != nil { - sgr = append(sgr, s.Background.bgSGR()) - } - - return strings.Join(sgr, ";") -} - -// MergeFromOptions merges all recognized values from a map to the current -// Style. -func (s *Style) MergeFromOptions(options map[string]interface{}) error { - assignColor := func(val interface{}, colorField *Color) string { - if val == "default" { - *colorField = nil - return "" - } else if s, ok := val.(string); ok { - color := parseColor(s) - if color != nil { - *colorField = color - return "" - } - } - return "valid color string" - } - assignBool := func(val interface{}, attrField *bool) string { - if b, ok := val.(bool); ok { - *attrField = b - } else { - return "bool value" - } - return "" - } - - for k, v := range options { - var need string - - switch k { - case "fg-color": - need = assignColor(v, &s.Foreground) - case "bg-color": - need = assignColor(v, &s.Background) - case "bold": - need = assignBool(v, &s.Bold) - case "dim": - need = assignBool(v, &s.Dim) - case "italic": - need = assignBool(v, &s.Italic) - case "underlined": - need = assignBool(v, &s.Underlined) - case "blink": - need = assignBool(v, &s.Blink) - case "inverse": - need = assignBool(v, &s.Inverse) - - default: - return fmt.Errorf("unrecognized option '%s'", k) - } - - if need != "" { - return fmt.Errorf("value for option '%s' must be a %s", k, need) - } - } - - return nil -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/styling.go b/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/styling.go deleted file mode 100644 index 485657d..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui/styling.go +++ /dev/null @@ -1,201 +0,0 @@ -package ui - -import ( - "strings" -) - -// Styling specifies how to change a Style. It can also be applied to a Segment -// or Text. -type Styling interface{ transform(*Style) } - -// ApplyStyling returns a new Style with the given Styling's applied. -func ApplyStyling(s Style, ts ...Styling) Style { - for _, t := range ts { - if t != nil { - t.transform(&s) - } - } - return s -} - -// Stylings joins several transformers into one. -func Stylings(ts ...Styling) Styling { return jointStyling(ts) } - -// Common stylings. -var ( - Reset Styling = reset{} - - FgDefault Styling = setForeground{nil} - - FgBlack Styling = setForeground{Black} - FgRed Styling = setForeground{Red} - FgGreen Styling = setForeground{Green} - FgYellow Styling = setForeground{Yellow} - FgBlue Styling = setForeground{Blue} - FgMagenta Styling = setForeground{Magenta} - FgCyan Styling = setForeground{Cyan} - FgWhite Styling = setForeground{White} - - FgBrightBlack Styling = setForeground{BrightBlack} - FgBrightRed Styling = setForeground{BrightRed} - FgBrightGreen Styling = setForeground{BrightGreen} - FgBrightYellow Styling = setForeground{BrightYellow} - FgBrightBlue Styling = setForeground{BrightBlue} - FgBrightMagenta Styling = setForeground{BrightMagenta} - FgBrightCyan Styling = setForeground{BrightCyan} - FgBrightWhite Styling = setForeground{BrightWhite} - - BgDefault Styling = setBackground{nil} - - BgBlack Styling = setBackground{Black} - BgRed Styling = setBackground{Red} - BgGreen Styling = setBackground{Green} - BgYellow Styling = setBackground{Yellow} - BgBlue Styling = setBackground{Blue} - BgMagenta Styling = setBackground{Magenta} - BgCyan Styling = setBackground{Cyan} - BgWhite Styling = setBackground{White} - - BgBrightBlack Styling = setBackground{BrightBlack} - BgBrightRed Styling = setBackground{BrightRed} - BgBrightGreen Styling = setBackground{BrightGreen} - BgBrightYellow Styling = setBackground{BrightYellow} - BgBrightBlue Styling = setBackground{BrightBlue} - BgBrightMagenta Styling = setBackground{BrightMagenta} - BgBrightCyan Styling = setBackground{BrightCyan} - BgBrightWhite Styling = setBackground{BrightWhite} - - Bold Styling = boolOn{boldField{}} - Dim Styling = boolOn{dimField{}} - Italic Styling = boolOn{italicField{}} - Underlined Styling = boolOn{underlinedField{}} - Blink Styling = boolOn{blinkField{}} - Inverse Styling = boolOn{inverseField{}} - - NoBold Styling = boolOff{boldField{}} - NoDim Styling = boolOff{dimField{}} - NoItalic Styling = boolOff{italicField{}} - NoUnderlined Styling = boolOff{underlinedField{}} - NoBlink Styling = boolOff{blinkField{}} - NoInverse Styling = boolOff{inverseField{}} - - ToggleBold Styling = boolToggle{boldField{}} - ToggleDim Styling = boolToggle{dimField{}} - ToggleItalic Styling = boolToggle{italicField{}} - ToggleUnderlined Styling = boolToggle{underlinedField{}} - ToggleBlink Styling = boolToggle{blinkField{}} - ToggleInverse Styling = boolToggle{inverseField{}} -) - -// Fg returns a Styling that sets the foreground color. -func Fg(c Color) Styling { return setForeground{c} } - -// Bg returns a Styling that sets the background color. -func Bg(c Color) Styling { return setBackground{c} } - -type ( - reset struct{} - setForeground struct{ c Color } - setBackground struct{ c Color } - boolOn struct{ f boolField } - boolOff struct{ f boolField } - boolToggle struct{ f boolField } -) - -func (reset) transform(s *Style) { *s = Style{} } -func (t setForeground) transform(s *Style) { s.Foreground = t.c } -func (t setBackground) transform(s *Style) { s.Background = t.c } -func (t boolOn) transform(s *Style) { *t.f.get(s) = true } -func (t boolOff) transform(s *Style) { *t.f.get(s) = false } -func (t boolToggle) transform(s *Style) { p := t.f.get(s); *p = !*p } - -type boolField interface{ get(*Style) *bool } - -type ( - boldField struct{} - dimField struct{} - italicField struct{} - underlinedField struct{} - blinkField struct{} - inverseField struct{} -) - -func (boldField) get(s *Style) *bool { return &s.Bold } -func (dimField) get(s *Style) *bool { return &s.Dim } -func (italicField) get(s *Style) *bool { return &s.Italic } -func (underlinedField) get(s *Style) *bool { return &s.Underlined } -func (blinkField) get(s *Style) *bool { return &s.Blink } -func (inverseField) get(s *Style) *bool { return &s.Inverse } - -type jointStyling []Styling - -func (t jointStyling) transform(s *Style) { - for _, t := range t { - t.transform(s) - } -} - -// ParseStyling parses a text representation of Styling, which are kebab -// case counterparts to the names of the builtin Styling's. For example, -// ToggleInverse is expressed as "toggle-inverse". -// -// Multiple stylings can be joined by spaces, which is equivalent to calling -// Stylings. -// -// If the given string is invalid, ParseStyling returns nil. -func ParseStyling(s string) Styling { - if !strings.ContainsRune(s, ' ') { - return parseOneStyling(s) - } - var joint jointStyling - for _, subs := range strings.Split(s, " ") { - parsed := parseOneStyling(subs) - if parsed == nil { - return nil - } - joint = append(joint, parseOneStyling(subs)) - } - return joint -} - -var boolFields = map[string]boolField{ - "bold": boldField{}, - "dim": dimField{}, - "italic": italicField{}, - "underlined": underlinedField{}, - "blink": blinkField{}, - "inverse": inverseField{}, -} - -func parseOneStyling(name string) Styling { - switch { - case name == "default" || name == "fg-default": - return FgDefault - case strings.HasPrefix(name, "fg-"): - if color := parseColor(name[len("fg-"):]); color != nil { - return setForeground{color} - } - case name == "bg-default": - return BgDefault - case strings.HasPrefix(name, "bg-"): - if color := parseColor(name[len("bg-"):]); color != nil { - return setBackground{color} - } - case strings.HasPrefix(name, "no-"): - if f, ok := boolFields[name[len("no-"):]]; ok { - return boolOff{f} - } - case strings.HasPrefix(name, "toggle-"): - if f, ok := boolFields[name[len("toggle-"):]]; ok { - return boolToggle{f} - } - default: - if f, ok := boolFields[name]; ok { - return boolOn{f} - } - if color := parseColor(name); color != nil { - return setForeground{color} - } - } - return nil -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/LICENSE.md b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/LICENSE.md deleted file mode 100644 index 2298515..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Mitchell Hashimoto - -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/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process.go deleted file mode 100644 index 2b5e8ed..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process.go +++ /dev/null @@ -1,40 +0,0 @@ -// ps provides an API for finding and listing processes in a platform-agnostic -// way. -// -// NOTE: If you're reading these docs online via GoDocs or some other system, -// you might only see the Unix docs. This project makes heavy use of -// platform-specific implementations. We recommend reading the source if you -// are interested. -package ps - -// Process is the generic interface that is implemented on every platform -// and provides common operations for processes. -type Process interface { - // Pid is the process ID for this process. - Pid() int - - // PPid is the parent process ID for this process. - PPid() int - - // Executable name running this process. This is not a path to the - // executable. - Executable() string -} - -// Processes returns all processes. -// -// This of course will be a point-in-time snapshot of when this method was -// called. Some operating systems don't provide snapshot capability of the -// process table, in which case the process table returned might contain -// ephemeral entities that happened to be running when this was called. -func Processes() ([]Process, error) { - return processes() -} - -// FindProcess looks up a single process by pid. -// -// Process will be nil and error will be nil if a matching process is -// not found. -func FindProcess(pid int) (Process, error) { - return findProcess(pid) -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_darwin.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_darwin.go deleted file mode 100644 index 3b417a0..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_darwin.go +++ /dev/null @@ -1,139 +0,0 @@ -//go:build darwin -// +build darwin - -package ps - -import ( - "bytes" - "encoding/binary" - "syscall" - "unsafe" -) - -type DarwinProcess struct { - pid int - ppid int - binary string -} - -func (p *DarwinProcess) Pid() int { - return p.pid -} - -func (p *DarwinProcess) PPid() int { - return p.ppid -} - -func (p *DarwinProcess) Executable() string { - return p.binary -} - -func findProcess(pid int) (Process, error) { - ps, err := processes() - if err != nil { - return nil, err - } - - for _, p := range ps { - if p.Pid() == pid { - return p, nil - } - } - - return nil, nil -} - -func processes() ([]Process, error) { - buf, err := darwinSyscall() - if err != nil { - return nil, err - } - - procs := make([]*kinfoProc, 0, 50) - k := 0 - for i := _KINFO_STRUCT_SIZE; i < buf.Len(); i += _KINFO_STRUCT_SIZE { - proc := &kinfoProc{} - err = binary.Read(bytes.NewBuffer(buf.Bytes()[k:i]), binary.LittleEndian, proc) - if err != nil { - return nil, err - } - - k = i - procs = append(procs, proc) - } - - darwinProcs := make([]Process, len(procs)) - for i, p := range procs { - darwinProcs[i] = &DarwinProcess{ - pid: int(p.Pid), - ppid: int(p.PPid), - binary: darwinCstring(p.Comm), - } - } - - return darwinProcs, nil -} - -func darwinCstring(s [16]byte) string { - i := 0 - for _, b := range s { - if b != 0 { - i++ - } else { - break - } - } - - return string(s[:i]) -} - -func darwinSyscall() (*bytes.Buffer, error) { - mib := [4]int32{_CTRL_KERN, _KERN_PROC, _KERN_PROC_ALL, 0} - size := uintptr(0) - - _, _, errno := syscall.Syscall6( - syscall.SYS___SYSCTL, - uintptr(unsafe.Pointer(&mib[0])), - 4, - 0, - uintptr(unsafe.Pointer(&size)), - 0, - 0) - - if errno != 0 { - return nil, errno - } - - bs := make([]byte, size) - _, _, errno = syscall.Syscall6( - syscall.SYS___SYSCTL, - uintptr(unsafe.Pointer(&mib[0])), - 4, - uintptr(unsafe.Pointer(&bs[0])), - uintptr(unsafe.Pointer(&size)), - 0, - 0) - - if errno != 0 { - return nil, errno - } - - return bytes.NewBuffer(bs[0:size]), nil -} - -const ( - _CTRL_KERN = 1 - _KERN_PROC = 14 - _KERN_PROC_ALL = 0 - _KINFO_STRUCT_SIZE = 648 -) - -type kinfoProc struct { - _ [40]byte - Pid int32 - _ [199]byte - Comm [16]byte - _ [301]byte - PPid int32 - _ [84]byte -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_freebsd.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_freebsd.go deleted file mode 100644 index 48115a4..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_freebsd.go +++ /dev/null @@ -1,261 +0,0 @@ -//go:build freebsd -// +build freebsd - -package ps - -import ( - "bytes" - "encoding/binary" - "syscall" - "unsafe" -) - -// copied from sys/sysctl.h -const ( - CTL_KERN = 1 // "high kernel": proc, limits - KERN_PROC = 14 // struct: process entries - KERN_PROC_PID = 1 // by process id - KERN_PROC_PROC = 8 // only return procs - KERN_PROC_PATHNAME = 12 // path to executable -) - -// copied from sys/user.h -type Kinfo_proc struct { - Ki_structsize int32 - Ki_layout int32 - Ki_args int64 - Ki_paddr int64 - Ki_addr int64 - Ki_tracep int64 - Ki_textvp int64 - Ki_fd int64 - Ki_vmspace int64 - Ki_wchan int64 - Ki_pid int32 - Ki_ppid int32 - Ki_pgid int32 - Ki_tpgid int32 - Ki_sid int32 - Ki_tsid int32 - Ki_jobc [2]byte - Ki_spare_short1 [2]byte - Ki_tdev int32 - Ki_siglist [16]byte - Ki_sigmask [16]byte - Ki_sigignore [16]byte - Ki_sigcatch [16]byte - Ki_uid int32 - Ki_ruid int32 - Ki_svuid int32 - Ki_rgid int32 - Ki_svgid int32 - Ki_ngroups [2]byte - Ki_spare_short2 [2]byte - Ki_groups [64]byte - Ki_size int64 - Ki_rssize int64 - Ki_swrss int64 - Ki_tsize int64 - Ki_dsize int64 - Ki_ssize int64 - Ki_xstat [2]byte - Ki_acflag [2]byte - Ki_pctcpu int32 - Ki_estcpu int32 - Ki_slptime int32 - Ki_swtime int32 - Ki_cow int32 - Ki_runtime int64 - Ki_start [16]byte - Ki_childtime [16]byte - Ki_flag int64 - Ki_kiflag int64 - Ki_traceflag int32 - Ki_stat [1]byte - Ki_nice [1]byte - Ki_lock [1]byte - Ki_rqindex [1]byte - Ki_oncpu [1]byte - Ki_lastcpu [1]byte - Ki_ocomm [17]byte - Ki_wmesg [9]byte - Ki_login [18]byte - Ki_lockname [9]byte - Ki_comm [20]byte - Ki_emul [17]byte - Ki_sparestrings [68]byte - Ki_spareints [36]byte - Ki_cr_flags int32 - Ki_jid int32 - Ki_numthreads int32 - Ki_tid int32 - Ki_pri int32 - Ki_rusage [144]byte - Ki_rusage_ch [144]byte - Ki_pcb int64 - Ki_kstack int64 - Ki_udata int64 - Ki_tdaddr int64 - Ki_spareptrs [48]byte - Ki_spareint64s [96]byte - Ki_sflag int64 - Ki_tdflags int64 -} - -// UnixProcess is an implementation of Process that contains Unix-specific -// fields and information. -type UnixProcess struct { - pid int - ppid int - state rune - pgrp int - sid int - - binary string -} - -func (p *UnixProcess) Pid() int { - return p.pid -} - -func (p *UnixProcess) PPid() int { - return p.ppid -} - -func (p *UnixProcess) Executable() string { - return p.binary -} - -// Refresh reloads all the data associated with this process. -func (p *UnixProcess) Refresh() error { - - mib := []int32{CTL_KERN, KERN_PROC, KERN_PROC_PID, int32(p.pid)} - - buf, length, err := call_syscall(mib) - if err != nil { - return err - } - proc_k := Kinfo_proc{} - if length != uint64(unsafe.Sizeof(proc_k)) { - return err - } - - k, err := parse_kinfo_proc(buf) - if err != nil { - return err - } - - p.ppid, p.pgrp, p.sid, p.binary = copy_params(&k) - return nil -} - -func copy_params(k *Kinfo_proc) (int, int, int, string) { - n := -1 - for i, b := range k.Ki_comm { - if b == 0 { - break - } - n = i + 1 - } - comm := string(k.Ki_comm[:n]) - - return int(k.Ki_ppid), int(k.Ki_pgid), int(k.Ki_sid), comm -} - -func findProcess(pid int) (Process, error) { - mib := []int32{CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, int32(pid)} - - _, _, err := call_syscall(mib) - if err != nil { - return nil, err - } - - return newUnixProcess(pid) -} - -func processes() ([]Process, error) { - results := make([]Process, 0, 50) - - mib := []int32{CTL_KERN, KERN_PROC, KERN_PROC_PROC, 0} - buf, length, err := call_syscall(mib) - if err != nil { - return results, err - } - - // get kinfo_proc size - k := Kinfo_proc{} - procinfo_len := int(unsafe.Sizeof(k)) - count := int(length / uint64(procinfo_len)) - - // parse buf to procs - for i := 0; i < count; i++ { - b := buf[i*procinfo_len : i*procinfo_len+procinfo_len] - k, err := parse_kinfo_proc(b) - if err != nil { - continue - } - p, err := newUnixProcess(int(k.Ki_pid)) - if err != nil { - continue - } - p.ppid, p.pgrp, p.sid, p.binary = copy_params(&k) - - results = append(results, p) - } - - return results, nil -} - -func parse_kinfo_proc(buf []byte) (Kinfo_proc, error) { - var k Kinfo_proc - br := bytes.NewReader(buf) - err := binary.Read(br, binary.LittleEndian, &k) - if err != nil { - return k, err - } - - return k, nil -} - -func call_syscall(mib []int32) ([]byte, uint64, error) { - miblen := uint64(len(mib)) - - // get required buffer size - length := uint64(0) - _, _, err := syscall.RawSyscall6( - syscall.SYS___SYSCTL, - uintptr(unsafe.Pointer(&mib[0])), - uintptr(miblen), - 0, - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - b := make([]byte, 0) - return b, length, err - } - if length == 0 { - b := make([]byte, 0) - return b, length, err - } - // get proc info itself - buf := make([]byte, length) - _, _, err = syscall.RawSyscall6( - syscall.SYS___SYSCTL, - uintptr(unsafe.Pointer(&mib[0])), - uintptr(miblen), - uintptr(unsafe.Pointer(&buf[0])), - uintptr(unsafe.Pointer(&length)), - 0, - 0) - if err != 0 { - return buf, length, err - } - - return buf, length, nil -} - -func newUnixProcess(pid int) (*UnixProcess, error) { - p := &UnixProcess{pid: pid} - return p, p.Refresh() -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_linux.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_linux.go deleted file mode 100644 index 199f6ab..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_linux.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build linux -// +build linux - -package ps - -import ( - "fmt" - "os" - "strings" -) - -// Refresh reloads all the data associated with this process. -func (p *UnixProcess) Refresh() error { - statPath := fmt.Sprintf("/proc/%d/stat", p.pid) - dataBytes, err := os.ReadFile(statPath) - if err != nil { - return err - } - - // First, parse out the image name - data := string(dataBytes) - binStart := strings.IndexRune(data, '(') + 1 - binEnd := strings.IndexRune(data[binStart:], ')') - p.binary = data[binStart : binStart+binEnd] - - // Move past the image name and start parsing the rest - data = data[binStart+binEnd+2:] - _, err = fmt.Sscanf(data, - "%c %d %d %d", - &p.state, - &p.ppid, - &p.pgrp, - &p.sid) - - return err -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_solaris.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_solaris.go deleted file mode 100644 index c4a86d0..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_solaris.go +++ /dev/null @@ -1,97 +0,0 @@ -//go:build solaris -// +build solaris - -package ps - -import ( - "encoding/binary" - "fmt" - "os" -) - -type ushort_t uint16 - -type id_t int32 -type pid_t int32 -type uid_t int32 -type gid_t int32 - -type dev_t uint64 -type size_t uint64 -type uintptr_t uint64 - -type timestruc_t [16]byte - -// This is copy from /usr/include/sys/procfs.h -type psinfo_t struct { - Pr_flag int32 /* process flags (DEPRECATED; do not use) */ - Pr_nlwp int32 /* number of active lwps in the process */ - Pr_pid pid_t /* unique process id */ - Pr_ppid pid_t /* process id of parent */ - Pr_pgid pid_t /* pid of process group leader */ - Pr_sid pid_t /* session id */ - Pr_uid uid_t /* real user id */ - Pr_euid uid_t /* effective user id */ - Pr_gid gid_t /* real group id */ - Pr_egid gid_t /* effective group id */ - Pr_addr uintptr_t /* address of process */ - Pr_size size_t /* size of process image in Kbytes */ - Pr_rssize size_t /* resident set size in Kbytes */ - Pr_pad1 size_t - Pr_ttydev dev_t /* controlling tty device (or PRNODEV) */ - - // Guess this following 2 ushort_t values require a padding to properly - // align to the 64bit mark. - Pr_pctcpu ushort_t /* % of recent cpu time used by all lwps */ - Pr_pctmem ushort_t /* % of system memory used by process */ - Pr_pad64bit [4]byte - - Pr_start timestruc_t /* process start time, from the epoch */ - Pr_time timestruc_t /* usr+sys cpu time for this process */ - Pr_ctime timestruc_t /* usr+sys cpu time for reaped children */ - Pr_fname [16]byte /* name of execed file */ - Pr_psargs [80]byte /* initial characters of arg list */ - Pr_wstat int32 /* if zombie, the wait() status */ - Pr_argc int32 /* initial argument count */ - Pr_argv uintptr_t /* address of initial argument vector */ - Pr_envp uintptr_t /* address of initial environment vector */ - Pr_dmodel [1]byte /* data model of the process */ - Pr_pad2 [3]byte - Pr_taskid id_t /* task id */ - Pr_projid id_t /* project id */ - Pr_nzomb int32 /* number of zombie lwps in the process */ - Pr_poolid id_t /* pool id */ - Pr_zoneid id_t /* zone id */ - Pr_contract id_t /* process contract */ - Pr_filler int32 /* reserved for future use */ - Pr_lwp [128]byte /* information for representative lwp */ -} - -func (p *UnixProcess) Refresh() error { - var psinfo psinfo_t - - path := fmt.Sprintf("/proc/%d/psinfo", p.pid) - fh, err := os.Open(path) - if err != nil { - return err - } - defer fh.Close() - - err = binary.Read(fh, binary.LittleEndian, &psinfo) - if err != nil { - return err - } - - p.ppid = int(psinfo.Pr_ppid) - p.binary = toString(psinfo.Pr_fname[:], 16) - return nil -} - -func toString(array []byte, len int) string { - for i := 0; i < len; i++ { - if array[i] == 0 { - return string(array[:i]) - } - } - return string(array[:]) -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_unix.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_unix.go deleted file mode 100644 index faec61a..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_unix.go +++ /dev/null @@ -1,96 +0,0 @@ -//go:build linux || solaris -// +build linux solaris - -package ps - -import ( - "fmt" - "io" - "os" - "strconv" -) - -// UnixProcess is an implementation of Process that contains Unix-specific -// fields and information. -type UnixProcess struct { - pid int - ppid int - state rune - pgrp int - sid int - - binary string -} - -func (p *UnixProcess) Pid() int { - return p.pid -} - -func (p *UnixProcess) PPid() int { - return p.ppid -} - -func (p *UnixProcess) Executable() string { - return p.binary -} - -func findProcess(pid int) (Process, error) { - dir := fmt.Sprintf("/proc/%d", pid) - _, err := os.Stat(dir) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - - return nil, err - } - - return newUnixProcess(pid) -} - -func processes() ([]Process, error) { - d, err := os.Open("/proc") - if err != nil { - return nil, err - } - defer d.Close() - - results := make([]Process, 0, 50) - for { - names, err := d.Readdirnames(10) - if err == io.EOF { - break - } - if err != nil { - return nil, err - } - - for _, name := range names { - // We only care if the name starts with a numeric - if name[0] < '0' || name[0] > '9' { - continue - } - - // From this point forward, any errors we just ignore, because - // it might simply be that the process doesn't exist anymore. - pid, err := strconv.ParseInt(name, 10, 0) - if err != nil { - continue - } - - p, err := newUnixProcess(int(pid)) - if err != nil { - continue - } - - results = append(results, p) - } - } - - return results, nil -} - -func newUnixProcess(pid int) (*UnixProcess, error) { - p := &UnixProcess{pid: pid} - return p, p.Refresh() -} diff --git a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_windows.go b/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_windows.go deleted file mode 100644 index a930f90..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps/process_windows.go +++ /dev/null @@ -1,120 +0,0 @@ -//go:build windows -// +build windows - -package ps - -import ( - "fmt" - "syscall" - "unsafe" -) - -// Windows API functions -var ( - modKernel32 = syscall.NewLazyDLL("kernel32.dll") - procCloseHandle = modKernel32.NewProc("CloseHandle") - procCreateToolhelp32Snapshot = modKernel32.NewProc("CreateToolhelp32Snapshot") - procProcess32First = modKernel32.NewProc("Process32FirstW") - procProcess32Next = modKernel32.NewProc("Process32NextW") -) - -// Some constants from the Windows API -const ( - ERROR_NO_MORE_FILES = 0x12 - MAX_PATH = 260 -) - -// PROCESSENTRY32 is the Windows API structure that contains a process's -// information. -type PROCESSENTRY32 struct { - Size uint32 - CntUsage uint32 - ProcessID uint32 - DefaultHeapID uintptr - ModuleID uint32 - CntThreads uint32 - ParentProcessID uint32 - PriorityClassBase int32 - Flags uint32 - ExeFile [MAX_PATH]uint16 -} - -// WindowsProcess is an implementation of Process for Windows. -type WindowsProcess struct { - pid int - ppid int - exe string -} - -func (p *WindowsProcess) Pid() int { - return p.pid -} - -func (p *WindowsProcess) PPid() int { - return p.ppid -} - -func (p *WindowsProcess) Executable() string { - return p.exe -} - -func newWindowsProcess(e *PROCESSENTRY32) *WindowsProcess { - // Find when the string ends for decoding - end := 0 - for { - if e.ExeFile[end] == 0 { - break - } - end++ - } - - return &WindowsProcess{ - pid: int(e.ProcessID), - ppid: int(e.ParentProcessID), - exe: syscall.UTF16ToString(e.ExeFile[:end]), - } -} - -func findProcess(pid int) (Process, error) { - ps, err := processes() - if err != nil { - return nil, err - } - - for _, p := range ps { - if p.Pid() == pid { - return p, nil - } - } - - return nil, nil -} - -func processes() ([]Process, error) { - handle, _, _ := procCreateToolhelp32Snapshot.Call( - 0x00000002, - 0) - if handle < 0 { - return nil, syscall.GetLastError() - } - defer procCloseHandle.Call(handle) - - var entry PROCESSENTRY32 - entry.Size = uint32(unsafe.Sizeof(entry)) - ret, _, _ := procProcess32First.Call(handle, uintptr(unsafe.Pointer(&entry))) - if ret == 0 { - return nil, fmt.Errorf("Error retrieving process info.") - } - - results := make([]Process, 0, 50) - for { - results = append(results, newWindowsProcess(&entry)) - - ret, _, _ := procProcess32Next.Call(handle, uintptr(unsafe.Pointer(&entry))) - if ret == 0 { - break - } - } - - return results, nil -} diff --git a/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/LICENSE b/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/LICENSE deleted file mode 100644 index 6a66aea..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 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/rsteube/carapace/third_party/golang.org/x/sys/PATENTS b/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/PATENTS deleted file mode 100644 index 7330990..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs/execabs.go b/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs/execabs.go deleted file mode 100644 index 7819249..0000000 --- a/vendor/github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs/execabs.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2020 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 execabs is a drop-in replacement for os/exec -// that requires PATH lookups to find absolute paths. -// That is, execabs.Command("cmd") runs the same PATH lookup -// as exec.Command("cmd"), but if the result is a path -// which is relative, the Run and Start methods will report -// an error instead of running the executable. -// -// See https://blog.golang.org/path-security for more information -// about when it may be necessary or appropriate to use this package. -package execabs - -import ( - "context" - "fmt" - "os/exec" - "path/filepath" - "reflect" - "unsafe" -) - -// ErrNotFound is the error resulting if a path search failed to find an executable file. -// It is an alias for exec.ErrNotFound. -var ErrNotFound = exec.ErrNotFound - -// Cmd represents an external command being prepared or run. -// It is an alias for exec.Cmd. -type Cmd = exec.Cmd - -// Error is returned by LookPath when it fails to classify a file as an executable. -// It is an alias for exec.Error. -type Error = exec.Error - -// An ExitError reports an unsuccessful exit by a command. -// It is an alias for exec.ExitError. -type ExitError = exec.ExitError - -func relError(file, path string) error { - return fmt.Errorf("%s resolves to executable in current directory (.%c%s)", file, filepath.Separator, path) -} - -// LookPath searches for an executable named file in the directories -// named by the PATH environment variable. If file contains a slash, -// it is tried directly and the PATH is not consulted. The result will be -// an absolute path. -// -// LookPath differs from exec.LookPath in its handling of PATH lookups, -// which are used for file names without slashes. If exec.LookPath's -// PATH lookup would have returned an executable from the current directory, -// LookPath instead returns an error. -func LookPath(file string) (string, error) { - path, err := exec.LookPath(file) - if err != nil { - return "", err - } - if filepath.Base(file) == file && !filepath.IsAbs(path) { - return "", relError(file, path) - } - return path, nil -} - -func fixCmd(name string, cmd *exec.Cmd) { - if filepath.Base(name) == name && !filepath.IsAbs(cmd.Path) { - // exec.Command was called with a bare binary name and - // exec.LookPath returned a path which is not absolute. - // Set cmd.lookPathErr and clear cmd.Path so that it - // cannot be run. - lookPathErr := (*error)(unsafe.Pointer(reflect.ValueOf(cmd).Elem().FieldByName("lookPathErr").Addr().Pointer())) - if *lookPathErr == nil { - *lookPathErr = relError(name, cmd.Path) - } - cmd.Path = "" - } -} - -// CommandContext is like Command but includes a context. -// -// The provided context is used to kill the process (by calling os.Process.Kill) -// if the context becomes done before the command completes on its own. -func CommandContext(ctx context.Context, name string, arg ...string) *exec.Cmd { - cmd := exec.CommandContext(ctx, name, arg...) - fixCmd(name, cmd) - return cmd - -} - -// Command returns the Cmd struct to execute the named program with the given arguments. -// See exec.Command for most details. -// -// Command differs from exec.Command in its handling of PATH lookups, -// which are used when the program name contains no slashes. -// If exec.Command would have returned an exec.Cmd configured to run an -// executable from the current directory, Command instead -// returns an exec.Cmd that will return an error from Start or Run. -func Command(name string, arg ...string) *exec.Cmd { - cmd := exec.Command(name, arg...) - fixCmd(name, cmd) - return cmd -} diff --git a/vendor/github.com/rsteube/carapace/traverse.go b/vendor/github.com/rsteube/carapace/traverse.go deleted file mode 100644 index 2aa4a9f..0000000 --- a/vendor/github.com/rsteube/carapace/traverse.go +++ /dev/null @@ -1,192 +0,0 @@ -package carapace - -import ( - "strings" - - "github.com/rsteube/carapace/internal/common" - "github.com/rsteube/carapace/internal/config" - "github.com/rsteube/carapace/internal/pflagfork" - "github.com/rsteube/carapace/pkg/style" - "github.com/spf13/cobra" -) - -type _inFlag struct { // TODO rename or integrate into pflagfork.Flag? - *pflagfork.Flag - // currently consumed args since encountered flag - Args []string -} - -func (f _inFlag) Consumes(arg string) bool { - switch { - case f.Flag == nil: - return false - case !f.TakesValue(): - return false - case f.IsOptarg(): - return false - case len(f.Args) == 0: - return true - case f.Nargs() > 1 && len(f.Args) < f.Nargs(): - return true - case f.Nargs() < 0 && !strings.HasPrefix(arg, "-"): - return true - default: - return false - } -} - -func traverse(c *cobra.Command, args []string) (Action, Context) { - LOG.Printf("traverse called for %#v with args %#v\n", c.Name(), args) - storage.preRun(c, args) - - if config.IsLenient() { - LOG.Printf("allowing unknown flags") - c.FParseErrWhitelist.UnknownFlags = true - } - - inArgs := []string{} // args consumed by current command - var inFlag *_inFlag // last encountered flag that still expects arguments - c.LocalFlags() // TODO force c.mergePersistentFlags() which is missing from c.Flags() - fs := pflagfork.FlagSet{FlagSet: c.Flags()} - - context := NewContext(args...) -loop: - for i, arg := range context.Args { - switch { - // flag argument - case inFlag != nil && inFlag.Consumes(arg): - LOG.Printf("arg %#v is a flag argument\n", arg) - inArgs = append(inArgs, arg) - inFlag.Args = append(inFlag.Args, arg) - - if !inFlag.Consumes("") { - inFlag = nil // no more args expected - } - continue - - // dash - case arg == "--": - LOG.Printf("arg %#v is dash\n", arg) - inArgs = append(inArgs, context.Args[i:]...) - break loop - - // flag - case !c.DisableFlagParsing && strings.HasPrefix(arg, "-"): - LOG.Printf("arg %#v is a flag\n", arg) - inArgs = append(inArgs, arg) - inFlag = &_inFlag{ - Flag: fs.LookupArg(arg), - Args: []string{}, - } - - if inFlag.Flag == nil { - LOG.Printf("flag %#v is unknown", arg) - } - continue - - // subcommand - case subcommand(c, arg) != nil: - LOG.Printf("arg %#v is a subcommand\n", arg) - - switch { - case c.DisableFlagParsing: - LOG.Printf("flag parsing disabled for %#v\n", c.Name()) - - default: - LOG.Printf("parsing flags for %#v with args %#v\n", c.Name(), inArgs) - if err := c.ParseFlags(inArgs); err != nil { - return ActionMessage(err.Error()), context - } - context.Args = c.Flags().Args() - } - - return traverse(subcommand(c, arg), args[i+1:]) - - // positional - default: - LOG.Printf("arg %#v is a positional\n", arg) - inArgs = append(inArgs, arg) - } - } - - toParse := inArgs - if inFlag != nil && len(inFlag.Args) == 0 && inFlag.Consumes("") { - LOG.Printf("removing arg %#v since it is a flag missing its argument\n", toParse[len(toParse)-1]) - toParse = toParse[:len(toParse)-1] - } else if fs.IsShorthandSeries(context.Value) { - LOG.Printf("arg %#v is a shorthand flag series", context.Value) - localInFlag := &_inFlag{ - Flag: fs.LookupArg(context.Value), - Args: []string{}, - } - if localInFlag.Consumes("") && len(context.Value) > 2 { - LOG.Printf("removing shorthand %#v from flag series since it is missing its argument\n", localInFlag.Shorthand) - toParse = append(toParse, strings.TrimSuffix(context.Value, localInFlag.Shorthand)) - } else { - toParse = append(toParse, context.Value) - } - - } - - // TODO duplicated code - switch { - case c.DisableFlagParsing: - LOG.Printf("flag parsing is disabled for %#v\n", c.Name()) - - default: - LOG.Printf("parsing flags for %#v with args %#v\n", c.Name(), toParse) - if err := c.ParseFlags(toParse); err != nil { - return ActionMessage(err.Error()), context - } - context.Args = c.Flags().Args() - } - - switch { - // dash argument - case common.IsDash(c): - LOG.Printf("completing dash for arg %#v\n", context.Value) - context.Args = c.Flags().Args()[c.ArgsLenAtDash():] - LOG.Printf("context: %#v\n", context.Args) - - return storage.getPositional(c, len(context.Args)), context - - // flag argument - case inFlag != nil && inFlag.Consumes(context.Value): - LOG.Printf("completing flag argument of %#v for arg %#v\n", inFlag.Name, context.Value) - context.Parts = inFlag.Args - return storage.getFlag(c, inFlag.Name), context - - // flag - case !c.DisableFlagParsing && strings.HasPrefix(context.Value, "-"): - if f := fs.LookupArg(context.Value); f != nil && f.IsOptarg() && strings.Contains(context.Value, string(f.OptargDelimiter())) { - LOG.Printf("completing optional flag argument for arg %#v\n", context.Value) - prefix, optarg := f.Split(context.Value) - context.Value = optarg - - switch f.Value.Type() { - case "bool": - return ActionValues("true", "false").StyleF(style.ForKeyword).Prefix(prefix), context - default: - return storage.getFlag(c, f.Name).Prefix(prefix), context - } - } - LOG.Printf("completing flags for arg %#v\n", context.Value) - return actionFlags(c), context - - // positional or subcommand - default: - LOG.Printf("completing positionals and subcommands for arg %#v\n", context.Value) - batch := Batch(storage.getPositional(c, len(context.Args))) - if c.HasAvailableSubCommands() && len(context.Args) == 0 { - batch = append(batch, actionSubcommands(c)) - } - return batch.ToA(), context - } -} - -func subcommand(cmd *cobra.Command, arg string) *cobra.Command { - if subcommand, _, _ := cmd.Find([]string{arg}); subcommand != cmd { - return subcommand - } - return nil -} diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore deleted file mode 100644 index c7b459e..0000000 --- a/vendor/github.com/spf13/cobra/.gitignore +++ /dev/null @@ -1,39 +0,0 @@ -# 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 deleted file mode 100644 index 2578d94..0000000 --- a/vendor/github.com/spf13/cobra/.golangci.yml +++ /dev/null @@ -1,62 +0,0 @@ -# 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. - -run: - deadline: 5m - -linters: - disable-all: true - enable: - #- bodyclose - - deadcode - #- depguard - #- dogsled - #- dupl - - errcheck - #- exhaustive - #- funlen - - gas - #- gochecknoinits - - goconst - #- gocritic - #- gocyclo - #- gofmt - - goimports - - golint - #- gomnd - #- goprintffuncname - #- gosec - #- gosimple - - govet - - ineffassign - - interfacer - #- lll - - maligned - - megacheck - #- misspell - #- nakedret - #- noctx - #- nolintlint - #- rowserrcheck - #- scopelint - #- staticcheck - - structcheck - #- stylecheck - #- typecheck - - unconvert - #- unparam - #- unused - - varcheck - #- whitespace - fast: false diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap deleted file mode 100644 index 94ec530..0000000 --- a/vendor/github.com/spf13/cobra/.mailmap +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index 9d16f88..0000000 --- a/vendor/github.com/spf13/cobra/CONDUCT.md +++ /dev/null @@ -1,37 +0,0 @@ -## 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 deleted file mode 100644 index 6f356e6..0000000 --- a/vendor/github.com/spf13/cobra/CONTRIBUTING.md +++ /dev/null @@ -1,50 +0,0 @@ -# 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 deleted file mode 100644 index 298f0e2..0000000 --- a/vendor/github.com/spf13/cobra/LICENSE.txt +++ /dev/null @@ -1,174 +0,0 @@ - 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 deleted file mode 100644 index 4c5ac3d..0000000 --- a/vendor/github.com/spf13/cobra/MAINTAINERS +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 0da8d7a..0000000 --- a/vendor/github.com/spf13/cobra/Makefile +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 592c0b8..0000000 --- a/vendor/github.com/spf13/cobra/README.md +++ /dev/null @@ -1,112 +0,0 @@ -![cobra logo](assets/CobraMain.png) - -Cobra is a library for creating powerful modern CLI applications. - -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](./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) - -# 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 [The Cobra User Guide](user_guide.md). - -# License - -Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go deleted file mode 100644 index 2d02394..0000000 --- a/vendor/github.com/spf13/cobra/active_help.go +++ /dev/null @@ -1,63 +0,0 @@ -// 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" - "strings" -) - -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 = "COBRA_ACTIVE_HELP" - 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 []string, activeHelpStr string) []string { - 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 - 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 - replaced by _. -func activeHelpEnvVar(name string) string { - // This format should not be changed: users will be using it explicitly. - activeHelpEnvVar := strings.ToUpper(fmt.Sprintf("%s%s", name, activeHelpEnvVarSuffix)) - return strings.ReplaceAll(activeHelpEnvVar, "-", "_") -} diff --git a/vendor/github.com/spf13/cobra/active_help.md b/vendor/github.com/spf13/cobra/active_help.md deleted file mode 100644 index 5e7f59a..0000000 --- a/vendor/github.com/spf13/cobra/active_help.md +++ /dev/null @@ -1,157 +0,0 @@ -# Active Help - -Active Help is a framework provided by Cobra which allows a program to define messages (hints, warnings, etc) that will be printed during program usage. It aims to make it easier for your users to learn how to use your program. If configured by the program, Active Help is printed when the user triggers shell completion. - -For example, -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding. - -bash-5.1$ bin/helm package [tab] -Please specify the path to the chart to package - -bash-5.1$ bin/helm package [tab][tab] -bin/ internal/ scripts/ pkg/ testdata/ -``` - -**Hint**: A good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions to guide the user in knowing what is expected by the program. -## Supported shells - -Active Help is currently only supported for the following shells: -- Bash (using [bash completion V2](shell_completions.md#bash-completion-v2) only). Note that bash 4.4 or higher is required for the prompt to appear when an Active Help message is printed. -- Zsh - -## Adding Active Help messages - -As Active Help uses the shell completion system, the implementation of Active Help messages is done by enhancing custom dynamic completions. If you are not familiar with dynamic completions, please refer to [Shell Completions](shell_completions.md). - -Adding Active Help is done through the use of the `cobra.AppendActiveHelp(...)` function, where the program repeatedly adds Active Help messages to the list of completions. Keep reading for details. - -### Active Help for nouns - -Adding Active Help when completing a noun is done within the `ValidArgsFunction(...)` of a command. Please notice the use of `cobra.AppendActiveHelp(...)` in the following example: - -```go -cmd := &cobra.Command{ - Use: "add [NAME] [URL]", - Short: "add a chart repository", - Args: require.ExactArgs(2), - RunE: func(cmd *cobra.Command, args []string) error { - return addRepo(args) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - var comps []string - if len(args) == 0 { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } else if len(args) == 1 { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } else { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - return comps, cobra.ShellCompDirectiveNoFileComp - }, -} -``` -The example above defines the completions (none, in this specific example) as well as the Active Help messages for the `helm repo add` command. It yields the following behavior: -``` -bash-5.1$ helm repo add [tab] -You must choose a name for the repo you are adding - -bash-5.1$ helm repo add grafana [tab] -You must specify the URL for the repo you are adding - -bash-5.1$ helm repo add grafana https://grafana.github.io/helm-charts [tab] -This command does not take any more arguments -``` -**Hint**: As can be seen in the above example, a good place to use Active Help messages is when the normal completion system does not provide any suggestions. In such cases, Active Help nicely supplements the normal shell completions. - -### Active Help for flags - -Providing Active Help for flags is done in the same fashion as for nouns, but using the completion function registered for the flag. For example: -```go -_ = cmd.RegisterFlagCompletionFunc("version", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 2 { - return cobra.AppendActiveHelp(nil, "You must first specify the chart to install before the --version flag can be completed"), cobra.ShellCompDirectiveNoFileComp - } - return compVersionFlag(args[1], toComplete) - }) -``` -The example above prints an Active Help message when not enough information was given by the user to complete the `--version` flag. -``` -bash-5.1$ bin/helm install myrelease --version 2.0.[tab] -You must first specify the chart to install before the --version flag can be completed - -bash-5.1$ bin/helm install myrelease bitnami/solr --version 2.0.[tab][tab] -2.0.1 2.0.2 2.0.3 -``` - -## User control of Active Help - -You may want to allow your users to disable Active Help or choose between different levels of Active Help. It is entirely up to the program to define the type of configurability of Active Help that it wants to offer, if any. -Allowing to configure Active Help is entirely optional; you can use Active Help in your program without doing anything about Active Help configuration. - -The way to configure Active Help is to use the program's Active Help environment -variable. That variable is named `_ACTIVE_HELP` where `` is the name of your -program in uppercase with any `-` replaced by an `_`. The variable should be set by the user to whatever -Active Help configuration values are supported by the program. - -For example, say `helm` has chosen to support three levels for Active Help: `on`, `off`, `local`. Then a user -would set the desired behavior to `local` by doing `export HELM_ACTIVE_HELP=local` in their shell. - -For simplicity, when in `cmd.ValidArgsFunction(...)` or a flag's completion function, the program should read the -Active Help configuration using the `cobra.GetActiveHelpConfig(cmd)` function and select what Active Help messages -should or should not be added (instead of reading the environment variable directly). - -For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - activeHelpLevel := cobra.GetActiveHelpConfig(cmd) - - var comps []string - if len(args) == 0 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must choose a name for the repo you are adding") - } - } else if len(args) == 1 { - if activeHelpLevel != "off" { - comps = cobra.AppendActiveHelp(comps, "You must specify the URL for the repo you are adding") - } - } else { - if activeHelpLevel == "local" { - comps = cobra.AppendActiveHelp(comps, "This command does not take any more arguments") - } - } - return comps, cobra.ShellCompDirectiveNoFileComp -}, -``` -**Note 1**: If the `_ACTIVE_HELP` environment variable is set to the string "0", Cobra will automatically disable all Active Help output (even if some output was specified by the program using the `cobra.AppendActiveHelp(...)` function). Using "0" can simplify your code in situations where you want to blindly disable Active Help without having to call `cobra.GetActiveHelpConfig(cmd)` explicitly. - -**Note 2**: If a user wants to disable Active Help for every single program based on Cobra, she can set the environment variable `COBRA_ACTIVE_HELP` to "0". In this case `cobra.GetActiveHelpConfig(cmd)` will return "0" no matter what the variable `_ACTIVE_HELP` is set to. - -**Note 3**: If the user does not set `_ACTIVE_HELP` or `COBRA_ACTIVE_HELP` (which will be a common case), the default value for the Active Help configuration returned by `cobra.GetActiveHelpConfig(cmd)` will be the empty string. -## Active Help with Cobra's default completion command - -Cobra provides a default `completion` command for programs that wish to use it. -When using the default `completion` command, Active Help is configurable in the same -fashion as described above using environment variables. You may wish to document this in more -details for your users. - -## Debugging Active Help - -Debugging your Active Help code is done in the same way as debugging your dynamic completion code, which is with Cobra's hidden `__complete` command. Please refer to [debugging shell completion](shell_completions.md#debugging) for details. - -When debugging with the `__complete` command, if you want to specify different Active Help configurations, you should use the active help environment variable. That variable is named `_ACTIVE_HELP` where any `-` is replaced by an `_`. For example, we can test deactivating some Active Help as shown below: -``` -$ HELM_ACTIVE_HELP=1 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -_activeHelp_ WARNING: cannot re-use a name that is still in use -:0 -Completion ended with directive: ShellCompDirectiveDefault - -$ HELM_ACTIVE_HELP=0 bin/helm __complete install wordpress bitnami/h -bitnami/haproxy -bitnami/harbor -:0 -Completion ended with directive: ShellCompDirectiveDefault -``` diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go deleted file mode 100644 index e79ec33..0000000 --- a/vendor/github.com/spf13/cobra/args.go +++ /dev/null @@ -1,131 +0,0 @@ -// 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. - var validArgs []string - for _, v := range cmd.ValidArgs { - validArgs = append(validArgs, strings.Split(v, "\t")[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 deleted file mode 100644 index 10c7884..0000000 --- a/vendor/github.com/spf13/cobra/bash_completions.go +++ /dev/null @@ -1,712 +0,0 @@ -// 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 to handle 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 - } - for key := range flag.Annotations { - switch key { - case BashCompOneRequiredFlag: - 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.Split(value, "\t")[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_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md deleted file mode 100644 index 52919b2..0000000 --- a/vendor/github.com/spf13/cobra/bash_completions.md +++ /dev/null @@ -1,93 +0,0 @@ -# Generating Bash Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution. - -**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own. - -The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions. - -Some code that works in kubernetes: - -```bash -const ( - bash_completion_func = `__kubectl_parse_get() -{ - local kubectl_output out - if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then - out=($(echo "${kubectl_output}" | awk '{print $1}')) - COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) ) - fi -} - -__kubectl_get_resource() -{ - if [[ ${#nouns[@]} -eq 0 ]]; then - return 1 - fi - __kubectl_parse_get ${nouns[${#nouns[@]} -1]} - if [[ $? -eq 0 ]]; then - return 0 - fi -} - -__kubectl_custom_func() { - case ${last_command} in - kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop) - __kubectl_get_resource - return - ;; - *) - ;; - esac -} -`) -``` - -And then I set that in my command definition: - -```go -cmds := &cobra.Command{ - Use: "kubectl", - Short: "kubectl controls the Kubernetes cluster manager", - Long: `kubectl controls the Kubernetes cluster manager. - -Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`, - Run: runHelp, - BashCompletionFunction: bash_completion_func, -} -``` - -The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`___custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods! - -Similarly, for flags: - -```go - annotation := make(map[string][]string) - annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"} - - flag := &pflag.Flag{ - Name: "namespace", - Usage: usage, - Annotations: annotation, - } - cmd.Flags().AddFlag(flag) -``` - -In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction` -value, e.g.: - -```bash -__kubectl_get_namespaces() -{ - local template - template="{{ range .items }}{{ .metadata.name }} {{ end }}" - local kubectl_out - if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then - COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) ) - fi -} -``` diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go deleted file mode 100644 index 19b0956..0000000 --- a/vendor/github.com/spf13/cobra/bash_completionsV2.go +++ /dev/null @@ -1,396 +0,0 @@ -// 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 to handle 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 - if ((${#activeHelp[*]} != 0)); then - printf "\n"; - printf "%%s\n" "${activeHelp[@]}" - printf "\n" - - # 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 - 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 - 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 - local tab=$'\t' comp - while IFS='' read -r comp; do - [[ -z $comp ]] && continue - # Strip any description - comp=${comp%%%%$tab*} - # Only consider the completions that match - if [[ $comp == "$cur"* ]]; then - COMPREPLY+=("$comp") - fi - done < <(printf "%%s\n" "${completions[@]}") - ;; - - *) - # Type: complete (normal completion) - __%[1]s_handle_standard_completion_case - ;; - esac -} - -__%[1]s_handle_standard_completion_case() { - local tab=$'\t' comp - - # Short circuit to optimize if we don't have descriptions - if [[ "${completions[*]}" != *$tab* ]]; then - IFS=$'\n' read -ra COMPREPLY -d '' < <(compgen -W "${completions[*]}" -- "$cur") - 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 - # Strip any description before checking the length - comp=${compline%%%%$tab*} - # Only consider the completions that match - [[ $comp == "$cur"* ]] || continue - COMPREPLY+=("$compline") - if ((${#comp}>longest)); then - longest=${#comp} - fi - done < <(printf "%%s\n" "${completions[@]}") - - # If there is a single completion left, remove the description text - if ((${#COMPREPLY[*]} == 1)); then - __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" - comp="${COMPREPLY[0]%%%%$tab*}" - __%[1]s_debug "Removed description from single completion, which is now: ${comp}" - COMPREPLY[0]=$comp - 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 deleted file mode 100644 index b07b44a..0000000 --- a/vendor/github.com/spf13/cobra/cobra.go +++ /dev/null @@ -1,239 +0,0 @@ -// 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 -) - -// EnablePrefixMatching allows to set 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 - -// 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) -} - -// tmpl executes the given template text on data, writing the result to w. -func tmpl(w io.Writer, text string, 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) - } - for i := range d { - 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 deleted file mode 100644 index 01f7c6f..0000000 --- a/vendor/github.com/spf13/cobra/command.go +++ /dev/null @@ -1,1834 +0,0 @@ -// 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" - -// FParseErrWhitelist configures Flag parse errors to be ignored -type FParseErrWhitelist flag.ParseErrorsWhitelist - -// 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 []string - // 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 func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - - // 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. - 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. - // - // 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. - lflags *flag.FlagSet - // iflags contains inherited flags. - 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 string - // 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 string - // 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 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) { - c.usageTemplate = 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) { - c.helpTemplate = s -} - -// SetVersionTemplate sets version template to be used. Application can use it to set custom template. -func (c *Command) SetVersionTemplate(s string) { - c.versionTemplate = 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() - err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - return err - } -} - -// 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() - // The help should be sent to stdout - // See https://github.com/spf13/cobra/issues/1002 - err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c) - if err != nil { - c.PrintErrln(err) - } - } -} - -// 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 - } -} - -var 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 -} - -var 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 -} - -var 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. -func (c *Command) UsageTemplate() string { - if c.usageTemplate != "" { - return c.usageTemplate - } - - if c.HasParent() { - return c.parent.UsageTemplate() - } - return `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}} -` -} - -// HelpTemplate return help template for the command. -func (c *Command) HelpTemplate() string { - if c.helpTemplate != "" { - return c.helpTemplate - } - - if c.HasParent() { - return c.parent.HelpTemplate() - } - return `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} - -{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// VersionTemplate return version template for the command. -func (c *Command) VersionTemplate() string { - if c.versionTemplate != "" { - return c.versionTemplate - } - - if c.HasParent() { - return c.parent.VersionTemplate() - } - return `{{with .Name}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} -` -} - -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 := []string{} - 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 - } - suggestionsString := "" - if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { - suggestionsString += "\n\nDid you mean this?\n" - for _, s := range suggestions { - suggestionsString += fmt.Sprintf("\t%v\n", s) - } - } - return suggestionsString -} - -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 { - return matches[0] - } - - 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("help") - 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 { - err := tmpl(c.OutOrStdout(), c.VersionTemplate(), 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 - } - - for p := c; p != nil; p = p.Parent() { - if p.PersistentPreRunE != nil { - if err := p.PersistentPreRunE(c, argWoFlags); err != nil { - return err - } - break - } else if p.PersistentPreRun != nil { - p.PersistentPreRun(c, argWoFlags) - 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 - } - break - } else if p.PersistentPostRun != nil { - p.PersistentPostRun(c, argWoFlags) - 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() - // initialize completion at the last point to allow for user overriding - c.InitDefaultCompletionCmd() - - // Now that all commands have been created, let's make sure all groups - // are properly created also - c.checkCommandGroups() - - 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 hidden command to be used for shell completion - c.initCompleteCmd(args) - - 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("Error:", 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("Error:", 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("help") == nil { - usage := "help for " - if c.Name() == "" { - usage += "this command" - } else { - usage += c.Name() - } - c.Flags().BoolP("help", "h", false, usage) - _ = c.Flags().SetAnnotation("help", 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.Name() - } - 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.Name() + ` help [path to command] for full details.`, - ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - var completions []string - 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, fmt.Sprintf("%s\t%s", 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 { - 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.Name() -} - -// UseLine puts out the full usage for a given command (including parents). -func (c *Command) UseLine() string { - var useline string - if c.HasParent() { - useline = c.parent.CommandPath() + " " + c.Use - } else { - useline = c.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.Name(), 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. -func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { - persistentFlags := c.PersistentFlags() - - out := flag.NewFlagSet(c.Name(), 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. -func (c *Command) LocalFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.lflags == nil { - c.lflags = flag.NewFlagSet(c.Name(), 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. -func (c *Command) InheritedFlags() *flag.FlagSet { - c.mergePersistentFlags() - - if c.iflags == nil { - c.iflags = flag.NewFlagSet(c.Name(), 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. -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.Name(), 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.Name(), flag.ContinueOnError) - c.flags.SetOutput(c.flagErrorBuf) - c.pflags = flag.NewFlagSet(c.Name(), 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().ParseErrorsWhitelist = flag.ParseErrorsWhitelist(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.Name(), 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 -} diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go deleted file mode 100644 index 307f0c1..0000000 --- a/vendor/github.com/spf13/cobra/command_notwin.go +++ /dev/null @@ -1,20 +0,0 @@ -// 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 deleted file mode 100644 index adbef39..0000000 --- a/vendor/github.com/spf13/cobra/command_win.go +++ /dev/null @@ -1,41 +0,0 @@ -// 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 deleted file mode 100644 index ee38c4d..0000000 --- a/vendor/github.com/spf13/cobra/completions.go +++ /dev/null @@ -1,878 +0,0 @@ -// 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" - "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]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} - -// 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 -} - -// NoFileCompletions can be used to disable file completion for commands that should -// not trigger file completions. -func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return nil, ShellCompDirectiveNoFileComp -} - -// FixedCompletions can be used to create a completion function which always -// returns the same results. -func FixedCompletions(choices []string, directive ShellCompDirective) func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) { - return choices, directive - } -} - -// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. -func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) 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 -} - -// 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) - for _, comp := range completions { - if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable { - // Remove all activeHelp entries in this case - if strings.HasPrefix(comp, activeHelpMarker) { - continue - } - } - if noDescriptions { - // Remove any description that may be included following a tab character. - comp = strings.Split(comp, "\t")[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.Split(comp, "\n")[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 stdout for the completion script to consume. - fmt.Fprintln(finalCmd.OutOrStdout(), 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(finalCmd.OutOrStdout(), ":%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) - } -} - -func (c *Command) getCompletions(args []string) (*Command, []string, 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, []string{}, 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. - 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, []string{}, 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, []string{}, ShellCompDirectiveDefault, flagErr - } - } - - // Look for the --help or --version flags. If they are present, - // there should be no further completions. - if helpOrVersionFlagPresent(finalCmd) { - return finalCmd, []string{}, 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, []string{}, ShellCompDirectiveFilterDirs, nil - } - } - - var completions []string - 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) { - if !flag.Changed || - strings.Contains(flag.Value.Type(), "Slice") || - strings.Contains(flag.Value.Type(), "Array") { - // If the flag is not already present, or if it can be specified multiple times (Array or Slice) - // 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) - }) - 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 - 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, fmt.Sprintf("%s\t%s", 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 func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) - 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 []string - 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("help"); helpFlag != nil && - len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { - return true - } - return false -} - -func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { - if nonCompletableFlag(flag) { - return []string{} - } - - var completions []string - flagName := "--" + flag.Name - if strings.HasPrefix(flagName, toComplete) { - // Flag without the = - completions = append(completions, fmt.Sprintf("%s\t%s", 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, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - // } - } - - flagName = "-" + flag.Shorthand - if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { - completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) - } - - return completions -} - -func completeRequireFlags(finalCmd *Command, toComplete string) []string { - var completions []string - - 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() { - if c.CompletionOptions.DisableDefaultCmd || !c.HasSubCommands() { - 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 - - 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) - - 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)) -} diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go deleted file mode 100644 index 12ca0d2..0000000 --- a/vendor/github.com/spf13/cobra/fish_completions.go +++ /dev/null @@ -1,292 +0,0 @@ -// 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 "Succesfully 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/fish_completions.md b/vendor/github.com/spf13/cobra/fish_completions.md deleted file mode 100644 index 19b2ed1..0000000 --- a/vendor/github.com/spf13/cobra/fish_completions.md +++ /dev/null @@ -1,4 +0,0 @@ -## Generating Fish Completions For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go deleted file mode 100644 index b35fde1..0000000 --- a/vendor/github.com/spf13/cobra/flag_groups.go +++ /dev/null @@ -1,224 +0,0 @@ -// 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 ( - requiredAsGroup = "cobra_annotation_required_if_others_set" - mutuallyExclusive = "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, requiredAsGroup, append(f.Annotations[requiredAsGroup], 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, mutuallyExclusive, append(f.Annotations[mutuallyExclusive], strings.Join(flagNames, " "))); err != nil { - panic(err) - } - } -} - -// ValidateFlagGroups validates the mutuallyExclusive/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{} - mutuallyExclusiveGroupStatus := map[string]map[string]bool{} - flags.VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, mutuallyExclusiveGroupStatus) - }) - - if err := validateRequiredFlagGroups(groupStatus); 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] = map[string]bool{} - 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 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 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{} - mutuallyExclusiveGroupStatus := map[string]map[string]bool{} - c.Flags().VisitAll(func(pflag *flag.Flag) { - processFlagForGroupAnnotation(flags, pflag, requiredAsGroup, groupStatus) - processFlagForGroupAnnotation(flags, pflag, mutuallyExclusive, 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 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 deleted file mode 100644 index 177d275..0000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.go +++ /dev/null @@ -1,325 +0,0 @@ -// 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.Replace(nameForVar, "-", "_", -1) - nameForVar = strings.Replace(nameForVar, ":", "_", -1) - - 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 = " " - } - @{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 - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - - } 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))" - } - - [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") - } - } - - # zsh like - "MenuComplete" { - # insert space after value - # MenuComplete will automatically show the ToolTip of - # the highlighted value at the bottom of the suggestions. - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - - # 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 - [System.Management.Automation.CompletionResult]::new($($comp.Name | __%[1]s_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)") - } - } - - } -} - -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/powershell_completions.md b/vendor/github.com/spf13/cobra/powershell_completions.md deleted file mode 100644 index c449f1e..0000000 --- a/vendor/github.com/spf13/cobra/powershell_completions.md +++ /dev/null @@ -1,3 +0,0 @@ -# Generating PowerShell Completions For Your Own cobra.Command - -Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details. diff --git a/vendor/github.com/spf13/cobra/projects_using_cobra.md b/vendor/github.com/spf13/cobra/projects_using_cobra.md deleted file mode 100644 index 8a291eb..0000000 --- a/vendor/github.com/spf13/cobra/projects_using_cobra.md +++ /dev/null @@ -1,64 +0,0 @@ -## Projects using Cobra - -- [Allero](https://github.com/allero-io/allero) -- [Arewefastyet](https://benchmark.vitess.io) -- [Arduino CLI](https://github.com/arduino/arduino-cli) -- [Bleve](https://blevesearch.com/) -- [Cilium](https://cilium.io/) -- [CloudQuery](https://github.com/cloudquery/cloudquery) -- [CockroachDB](https://www.cockroachlabs.com/) -- [Constellation](https://github.com/edgelesssys/constellation) -- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk) -- [Datree](https://github.com/datreeio/datree) -- [Delve](https://github.com/derekparker/delve) -- [Docker (distribution)](https://github.com/docker/distribution) -- [Etcd](https://etcd.io/) -- [Gardener](https://github.com/gardener/gardenctl) -- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl) -- [Git Bump](https://github.com/erdaltsksn/git-bump) -- [GitHub CLI](https://github.com/cli/cli) -- [GitHub Labeler](https://github.com/erdaltsksn/gh-label) -- [Golangci-lint](https://golangci-lint.run) -- [GopherJS](https://github.com/gopherjs/gopherjs) -- [GoReleaser](https://goreleaser.com) -- [Helm](https://helm.sh) -- [Hugo](https://gohugo.io) -- [Infracost](https://github.com/infracost/infracost) -- [Istio](https://istio.io) -- [Kool](https://github.com/kool-dev/kool) -- [Kubernetes](https://kubernetes.io/) -- [Kubescape](https://github.com/kubescape/kubescape) -- [KubeVirt](https://github.com/kubevirt/kubevirt) -- [Linkerd](https://linkerd.io/) -- [Mattermost-server](https://github.com/mattermost/mattermost-server) -- [Mercure](https://mercure.rocks/) -- [Meroxa CLI](https://github.com/meroxa/cli) -- [Metal Stack CLI](https://github.com/metal-stack/metalctl) -- [Moby (former Docker)](https://github.com/moby/moby) -- [Moldy](https://github.com/Moldy-Community/moldy) -- [Multi-gitter](https://github.com/lindell/multi-gitter) -- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack) -- [nFPM](https://nfpm.goreleaser.com) -- [Okteto](https://github.com/okteto/okteto) -- [OpenShift](https://www.openshift.com/) -- [Ory Hydra](https://github.com/ory/hydra) -- [Ory Kratos](https://github.com/ory/kratos) -- [Pixie](https://github.com/pixie-io/pixie) -- [Polygon Edge](https://github.com/0xPolygon/polygon-edge) -- [Pouch](https://github.com/alibaba/pouch) -- [ProjectAtomic (enterprise)](https://www.projectatomic.io/) -- [Prototool](https://github.com/uber/prototool) -- [Pulumi](https://www.pulumi.com) -- [QRcp](https://github.com/claudiodangelis/qrcp) -- [Random](https://github.com/erdaltsksn/random) -- [Rclone](https://rclone.org/) -- [Scaleway CLI](https://github.com/scaleway/scaleway-cli) -- [Sia](https://github.com/SiaFoundation/siad) -- [Skaffold](https://skaffold.dev/) -- [Tendermint](https://github.com/tendermint/tendermint) -- [Twitch CLI](https://github.com/twitchdev/twitch-cli) -- [UpCloud CLI (`upctl`)](https://github.com/UpCloudLtd/upcloud-cli) -- [Vitess](https://vitess.io) -- VMware's [Tanzu Community Edition](https://github.com/vmware-tanzu/community-edition) & [Tanzu Framework](https://github.com/vmware-tanzu/tanzu-framework) -- [Werf](https://werf.io/) -- [ZITADEL](https://github.com/zitadel/zitadel) diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go deleted file mode 100644 index b035742..0000000 --- a/vendor/github.com/spf13/cobra/shell_completions.go +++ /dev/null @@ -1,98 +0,0 @@ -// 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/shell_completions.md b/vendor/github.com/spf13/cobra/shell_completions.md deleted file mode 100644 index 065c062..0000000 --- a/vendor/github.com/spf13/cobra/shell_completions.md +++ /dev/null @@ -1,576 +0,0 @@ -# Generating shell completions - -Cobra can generate shell completions for multiple shells. -The currently supported shells are: -- Bash -- Zsh -- fish -- PowerShell - -Cobra will automatically provide your program with a fully functional `completion` command, -similarly to how it provides the `help` command. - -## Creating your own completion command - -If you do not wish to use the default `completion` command, you can choose to -provide your own, which will take precedence over the default one. (This also provides -backwards-compatibility with programs that already have their own `completion` command.) - -If you are using the `cobra-cli` generator, -which can be found at [spf13/cobra-cli](https://github.com/spf13/cobra-cli), -you can create a completion command by running - -```bash -cobra-cli add completion -``` -and then modifying the generated `cmd/completion.go` file to look something like this -(writing the shell script to stdout allows the most flexible use): - -```go -var completionCmd = &cobra.Command{ - Use: "completion [bash|zsh|fish|powershell]", - Short: "Generate completion script", - Long: fmt.Sprintf(`To load completions: - -Bash: - - $ source <(%[1]s completion bash) - - # To load completions for each 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 - -Zsh: - - # 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 for each session, execute once: - $ %[1]s completion zsh > "${fpath[1]}/_%[1]s" - - # You will need to start a new shell for this setup to take effect. - -fish: - - $ %[1]s completion fish | source - - # To load completions for each session, execute once: - $ %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish - -PowerShell: - - PS> %[1]s completion powershell | Out-String | Invoke-Expression - - # To load completions for every new session, run: - PS> %[1]s completion powershell > %[1]s.ps1 - # and source this file from your PowerShell profile. -`,cmd.Root().Name()), - DisableFlagsInUseLine: true, - ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, - Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - switch args[0] { - case "bash": - cmd.Root().GenBashCompletion(os.Stdout) - case "zsh": - cmd.Root().GenZshCompletion(os.Stdout) - case "fish": - cmd.Root().GenFishCompletion(os.Stdout, true) - case "powershell": - cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout) - } - }, -} -``` - -**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed. - -## Adapting the default completion command - -Cobra provides a few options for the default `completion` command. To configure such options you must set -the `CompletionOptions` field on the *root* command. - -To tell Cobra *not* to provide the default `completion` command: -``` -rootCmd.CompletionOptions.DisableDefaultCmd = true -``` - -To tell Cobra to mark the default `completion` command as *hidden*: -``` -rootCmd.CompletionOptions.HiddenDefaultCmd = true -``` - -To tell Cobra *not* to provide the user with the `--no-descriptions` flag to the completion sub-commands: -``` -rootCmd.CompletionOptions.DisableNoDescFlag = true -``` - -To tell Cobra to completely disable descriptions for completions: -``` -rootCmd.CompletionOptions.DisableDescriptions = true -``` - -# Customizing completions - -The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values. - -## Completion of nouns - -### Static completion of nouns - -Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field. -For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. -Some simplified code from `kubectl get` looks like: - -```go -validArgs = []string{ "pod", "node", "service", "replicationcontroller" } - -cmd := &cobra.Command{ - Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)", - Short: "Display one or many resources", - Long: get_long, - Example: get_example, - Run: func(cmd *cobra.Command, args []string) { - cobra.CheckErr(RunGet(f, out, cmd, args)) - }, - ValidArgs: validArgs, -} -``` - -Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like: - -```bash -$ kubectl get [tab][tab] -node pod replicationcontroller service -``` - -#### Aliases for nouns - -If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`: - -```go -argAliases = []string { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" } - -cmd := &cobra.Command{ - ... - ValidArgs: validArgs, - ArgAliases: argAliases -} -``` - -The aliases are shown to the user on tab completion only if no completions were found within sub-commands or `ValidArgs`. - -### Dynamic completion of nouns - -In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both. -Simplified code from `helm status` looks like: - -```go -cmd := &cobra.Command{ - Use: "status RELEASE_NAME", - Short: "Display the status of the named release", - Long: status_long, - RunE: func(cmd *cobra.Command, args []string) { - RunGet(args[0]) - }, - ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - if len(args) != 0 { - return nil, cobra.ShellCompDirectiveNoFileComp - } - return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp - }, -} -``` -Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster. -Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like: - -```bash -$ helm status [tab][tab] -harbor notary rook thanos -``` -You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp` -```go -// Indicates that the shell will perform its default behavior after completions -// have been provided (this implies none of the other directives). -ShellCompDirectiveDefault - -// Indicates an error occurred and completions should be ignored. -ShellCompDirectiveError - -// Indicates that the shell should not add a space after the completion, -// even if there is a single completion provided. -ShellCompDirectiveNoSpace - -// Indicates that the shell should not provide file completion even when -// no completion is provided. -ShellCompDirectiveNoFileComp - -// Indicates that the returned completions should be used as file extension filters. -// For example, to complete only files of the form *.json or *.yaml: -// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt -// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename() -// is a shortcut to using this directive explicitly. -// -ShellCompDirectiveFilterFileExt - -// Indicates that only directory names should be provided in file completion. -// For example: -// return nil, ShellCompDirectiveFilterDirs -// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly. -// -// To request directory names within another directory, the returned completions -// should specify a single directory name within which to search. For example, -// to complete directories within "themes/": -// return []string{"themes"}, ShellCompDirectiveFilterDirs -// -ShellCompDirectiveFilterDirs - -// ShellCompDirectiveKeepOrder indicates that the shell should preserve the order -// in which the completions are provided -ShellCompDirectiveKeepOrder -``` - -***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function. - -#### Debugging - -Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly: -```bash -$ helm __complete status har -harbor -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command: -```bash -$ helm __complete status "" -harbor -notary -rook -thanos -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code: -```go -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and optionally prints to stderr. -cobra.CompDebug(msg string, printToStdErr bool) { -cobra.CompDebugln(msg string, printToStdErr bool) - -// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE -// is set to a file path) and to stderr. -cobra.CompError(msg string) -cobra.CompErrorln(msg string) -``` -***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above. - -## Completions for flags - -### Mark flags as required - -Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so: - -```go -cmd.MarkFlagRequired("pod") -cmd.MarkFlagRequired("container") -``` - -and you'll get something like - -```bash -$ kubectl exec [tab][tab] --c --container= -p --pod= -``` - -### Specify dynamic flag completion - -As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function. - -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault -}) -``` -Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so: - -```bash -$ helm status --output [tab][tab] -json table yaml -``` - -#### Debugging - -You can also easily debug your Go completion code for flags: -```bash -$ helm __complete status --output "" -json -table -yaml -:4 -Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr -``` -***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above. - -### Specify valid filename extensions for flags that take a filename - -To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so: -```go -flagName := "output" -cmd.MarkFlagFilename(flagName, "yaml", "json") -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt}) -``` - -### Limit flag completions to directory names - -To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so: -```go -flagName := "output" -cmd.MarkFlagDirname(flagName) -``` -or -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return nil, cobra.ShellCompDirectiveFilterDirs -}) -``` -To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so: -```go -flagName := "output" -cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs -}) -``` -### Descriptions for completions - -Cobra provides support for completion descriptions. Such descriptions are supported for each shell -(however, for bash, it is only available in the [completion V2 version](#bash-completion-v2)). -For commands and flags, Cobra will provide the descriptions automatically, based on usage information. -For example, using zsh: -``` -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release -``` -while using fish: -``` -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) -``` - -Cobra allows you to add descriptions to your own completions. Simply add the description text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example: -```go -ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { - return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp -}} -``` -or -```go -ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"} -``` - -If you don't want to show descriptions in the completions, you can add `--no-descriptions` to the default `completion` command to disable them, like: - -```bash -$ source <(helm completion bash) -$ helm completion [tab][tab] -bash (generate autocompletion script for bash) powershell (generate autocompletion script for powershell) -fish (generate autocompletion script for fish) zsh (generate autocompletion script for zsh) - -$ source <(helm completion bash --no-descriptions) -$ helm completion [tab][tab] -bash fish powershell zsh -``` -## Bash completions - -### Dependencies - -The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)) - -### Aliases - -You can also configure `bash` aliases for your program and they will also support completions. - -```bash -alias aliasname=origcommand -complete -o default -F __start_origcommand aliasname - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -### Bash legacy dynamic completions - -For backward compatibility, Cobra still supports its bash legacy dynamic completion solution. -Please refer to [Bash Completions](bash_completions.md) for details. - -### Bash completion V2 - -Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling -`GenBashCompletion()` or `GenBashCompletionFile()`. - -A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or -`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion -(see [Bash Completions](bash_completions.md)) but instead works only with the Go dynamic completion -solution described in this document. -Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash -completion V2 solution which provides the following extra features: -- Supports completion descriptions (like the other shells) -- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines) -- Streamlined user experience thanks to a completion behavior aligned with the other shells - -`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()` -you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra -will provide the description automatically based on usage information. You can choose to make this option configurable by -your users. - -``` -# With descriptions -$ helm s[tab][tab] -search (search for a keyword in charts) status (display the status of the named release) -show (show information of a chart) - -# Without descriptions -$ helm s[tab][tab] -search show status -``` -**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. -## Zsh completions - -Cobra supports native zsh completion generated from the root `cobra.Command`. -The generated completion script should be put somewhere in your `$fpath` and be named -`_`. You will need to start a new shell for the completions to become available. - -Zsh supports descriptions for completions. Cobra will provide the description automatically, -based on usage information. Cobra provides a way to completely disable such descriptions by -using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make -this a configurable option to your users. -``` -# With descriptions -$ helm s[tab] -search -- search for a keyword in charts -show -- show information of a chart -status -- displays the status of the named release - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`. - * You should instead use `RegisterFlagCompletionFunc()`. - -### Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced. -Please refer to [Zsh Completions](zsh_completions.md) for details. - -## fish completions - -Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. -``` -# With descriptions -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# Without descriptions -$ helm s[tab] -search show status -``` -*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `fish`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `fish`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) - -## PowerShell completions - -Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users. - -The script is designed to support all three PowerShell 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 `. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode. - -Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles. - -``` -# With descriptions and Mode 'Complete' -$ helm s[tab] -search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release) - -# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions. -$ helm s[tab] -search show status - -search for a keyword in charts - -# Without descriptions -$ helm s[tab] -search show status -``` -### Aliases - -You can also configure `powershell` aliases for your program and they will also support completions. - -``` -$ sal aliasname origcommand -$ Register-ArgumentCompleter -CommandName 'aliasname' -ScriptBlock $__origcommandCompleterBlock - -# and now when you run `aliasname` completion will make -# suggestions as it did for `origcommand`. - -$ aliasname -completion firstcommand secondcommand -``` -The name of the completer block variable is of the form `$__CompleterBlock` where every `-` and `:` in the program name have been replaced with `_`, to respect powershell naming syntax. - -### Limitations - -* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation). - * You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`). -* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`. - * You should instead use `RegisterFlagCompletionFunc()`. -* The following flag completion annotations are not supported and will be ignored for `powershell`: - * `BashCompFilenameExt` (filtering by file extension) - * `BashCompSubdirsInDir` (filtering by directory) -* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`: - * `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension) - * `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory) -* Similarly, the following completion directives are not supported and will be ignored for `powershell`: - * `ShellCompDirectiveFilterFileExt` (filtering by file extension) - * `ShellCompDirectiveFilterDirs` (filtering by directory) diff --git a/vendor/github.com/spf13/cobra/user_guide.md b/vendor/github.com/spf13/cobra/user_guide.md deleted file mode 100644 index 85201d8..0000000 --- a/vendor/github.com/spf13/cobra/user_guide.md +++ /dev/null @@ -1,726 +0,0 @@ -# User Guide - -While you are welcome to provide your own organization, typically a Cobra-based -application will follow the following organizational structure: - -``` - ▾ appName/ - ▾ cmd/ - add.go - your.go - commands.go - here.go - main.go -``` - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -## Using the Cobra Generator - -Cobra-CLI is its own program that will create your application and add any -commands you want. It's the easiest way to incorporate Cobra into your application. - -For complete details on using the Cobra generator, please refer to [The Cobra-CLI Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) - -## Using the Cobra Library - -To manually implement Cobra you need to create a bare main.go file and a rootCmd file. -You will optionally provide additional commands as you see fit. - -### Create rootCmd - -Cobra doesn't require any special constructors. Simply create your commands. - -Ideally you place this in app/cmd/root.go: - -```go -var rootCmd = &cobra.Command{ - Use: "hugo", - Short: "Hugo is a very fast static site generator", - Long: `A Fast and Flexible Static Site Generator built with - love by spf13 and friends in Go. - Complete documentation is available at https://gohugo.io/documentation/`, - Run: func(cmd *cobra.Command, args []string) { - // Do Stuff Here - }, -} - -func Execute() { - if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} -``` - -You will additionally define flags and handle configuration in your init() function. - -For example cmd/root.go: - -```go -package cmd - -import ( - "fmt" - "os" - - "github.com/spf13/cobra" - "github.com/spf13/viper" -) - -var ( - // Used for flags. - cfgFile string - userLicense string - - rootCmd = &cobra.Command{ - Use: "cobra-cli", - Short: "A generator for Cobra based Applications", - Long: `Cobra is a CLI library for Go that empowers applications. -This application is a tool to generate the needed files -to quickly create a Cobra application.`, - } -) - -// Execute executes the root command. -func Execute() error { - return rootCmd.Execute() -} - -func init() { - cobra.OnInitialize(initConfig) - - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)") - rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution") - rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project") - rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) - viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")) - viper.SetDefault("author", "NAME HERE ") - viper.SetDefault("license", "apache") - - rootCmd.AddCommand(addCmd) - rootCmd.AddCommand(initCmd) -} - -func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".cobra" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".cobra") - } - - viper.AutomaticEnv() - - if err := viper.ReadInConfig(); err == nil { - fmt.Println("Using config file:", viper.ConfigFileUsed()) - } -} -``` - -### Create your main.go - -With the root command you need to have your main function execute it. -Execute should be run on the root for clarity, though it can be called on any command. - -In a Cobra app, typically the main.go file is very bare. It serves one purpose: to initialize Cobra. - -```go -package main - -import ( - "{pathToYourApp}/cmd" -) - -func main() { - cmd.Execute() -} -``` - -### Create additional commands - -Additional commands can be defined and typically are each given their own file -inside of the cmd/ directory. - -If you wanted to create a version command you would create cmd/version.go and -populate it with the following: - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(versionCmd) -} - -var versionCmd = &cobra.Command{ - Use: "version", - Short: "Print the version number of Hugo", - Long: `All software has versions. This is Hugo's`, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hugo Static Site Generator v0.9 -- HEAD") - }, -} -``` - -### Organizing subcommands - -A command may have subcommands which in turn may have other subcommands. This is achieved by using -`AddCommand`. In some cases, especially in larger applications, each subcommand may be defined in -its own go package. - -The suggested approach is for the parent command to use `AddCommand` to add its most immediate -subcommands. For example, consider the following directory structure: - -```text -├── cmd -│   ├── root.go -│   └── sub1 -│   ├── sub1.go -│   └── sub2 -│   ├── leafA.go -│   ├── leafB.go -│   └── sub2.go -└── main.go -``` - -In this case: - -* The `init` function of `root.go` adds the command defined in `sub1.go` to the root command. -* The `init` function of `sub1.go` adds the command defined in `sub2.go` to the sub1 command. -* The `init` function of `sub2.go` adds the commands defined in `leafA.go` and `leafB.go` to the - sub2 command. - -This approach ensures the subcommands are always included at compile time while avoiding cyclic -references. - -### Returning and handling errors - -If you wish to return an error to the caller of a command, `RunE` can be used. - -```go -package cmd - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func init() { - rootCmd.AddCommand(tryCmd) -} - -var tryCmd = &cobra.Command{ - Use: "try", - Short: "Try and possibly fail at something", - RunE: func(cmd *cobra.Command, args []string) error { - if err := someFunc(); err != nil { - return err - } - return nil - }, -} -``` - -The error can then be caught at the execute function call. - -## Working with Flags - -Flags provide modifiers to control how the action command operates. - -### Assign flags to a command - -Since the flags are defined and used in different locations, we need to -define a variable outside with the correct scope to assign the flag to -work with. - -```go -var Verbose bool -var Source string -``` - -There are two different approaches to assign a flag. - -### Persistent Flags - -A flag can be 'persistent', meaning that this flag will be available to the -command it's assigned to as well as every command under that command. For -global flags, assign a flag as a persistent flag on the root. - -```go -rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output") -``` - -### Local Flags - -A flag can also be assigned locally, which will only apply to that specific command. - -```go -localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from") -``` - -### Local Flag on Parent Commands - -By default, Cobra only parses local flags on the target command, and any local flags on -parent commands are ignored. By enabling `Command.TraverseChildren`, Cobra will -parse local flags on each command before executing the target command. - -```go -command := cobra.Command{ - Use: "print [OPTIONS] [COMMANDS]", - TraverseChildren: true, -} -``` - -### Bind Flags with Config - -You can also bind your flags with [viper](https://github.com/spf13/viper): -```go -var author string - -func init() { - rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution") - viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")) -} -``` - -In this example, the persistent flag `author` is bound with `viper`. -**Note**: the variable `author` will not be set to the value from config, -when the `--author` flag is provided by user. - -More in [viper documentation](https://github.com/spf13/viper#working-with-flags). - -### Required flags - -Flags are optional by default. If instead you wish your command to report an error -when a flag has not been set, mark it as required: -```go -rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkFlagRequired("region") -``` - -Or, for persistent flags: -```go -rootCmd.PersistentFlags().StringVarP(&Region, "region", "r", "", "AWS region (required)") -rootCmd.MarkPersistentFlagRequired("region") -``` - -### Flag Groups - -If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then -Cobra can enforce that requirement: -```go -rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)") -rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)") -rootCmd.MarkFlagsRequiredTogether("username", "password") -``` - -You can also prevent different flags from being provided together if they represent mutually -exclusive options such as specifying an output format as either `--json` or `--yaml` but never both: -```go -rootCmd.Flags().BoolVar(&ofJson, "json", false, "Output in JSON") -rootCmd.Flags().BoolVar(&ofYaml, "yaml", false, "Output in YAML") -rootCmd.MarkFlagsMutuallyExclusive("json", "yaml") -``` - -In both of these cases: - - both local and persistent flags can be used - - **NOTE:** the group is only enforced on commands where every flag is defined - - a flag may appear in multiple groups - - a group may contain any number of flags - -## Positional and Custom Arguments - -Validation of positional arguments can be specified using the `Args` field of `Command`. -The following validators are built in: - -- Number of arguments: - - `NoArgs` - report an error if there are any positional args. - - `ArbitraryArgs` - accept any number of args. - - `MinimumNArgs(int)` - report an error if less than N positional args are provided. - - `MaximumNArgs(int)` - report an error if more than N positional args are provided. - - `ExactArgs(int)` - report an error if there are not exactly N positional args. - - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`. -- Content of the arguments: - - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args. - -If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`. - -Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks. -For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional -args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as -shown below: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`. -For example: - -```go -var cmd = &cobra.Command{ - Short: "hello", - Args: func(cmd *cobra.Command, args []string) error { - // Optionally run one of the validators provided by cobra - if err := cobra.MinimumNArgs(1)(cmd, args); err != nil { - return err - } - // Run the custom validation logic - if myapp.IsValidColor(args[0]) { - return nil - } - return fmt.Errorf("invalid color specified: %s", args[0]) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Hello, World!") - }, -} -``` - -## Example - -In the example below, we have defined three commands. Two are at the top level -and one (cmdTimes) is a child of one of the top commands. In this case the root -is not executable, meaning that a subcommand is required. This is accomplished -by not providing a 'Run' for the 'rootCmd'. - -We have only defined one flag for a single command. - -More documentation about flags is available at https://github.com/spf13/pflag - -```go -package main - -import ( - "fmt" - "strings" - - "github.com/spf13/cobra" -) - -func main() { - var echoTimes int - - var cmdPrint = &cobra.Command{ - Use: "print [string to print]", - Short: "Print anything to the screen", - Long: `print is for printing anything back to the screen. -For many years people have printed back to the screen.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Print: " + strings.Join(args, " ")) - }, - } - - var cmdEcho = &cobra.Command{ - Use: "echo [string to echo]", - Short: "Echo anything to the screen", - Long: `echo is for echoing anything back. -Echo works a lot like print, except it has a child command.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - fmt.Println("Echo: " + strings.Join(args, " ")) - }, - } - - var cmdTimes = &cobra.Command{ - Use: "times [string to echo]", - Short: "Echo anything to the screen more times", - Long: `echo things multiple times back to the user by providing -a count and a string.`, - Args: cobra.MinimumNArgs(1), - Run: func(cmd *cobra.Command, args []string) { - for i := 0; i < echoTimes; i++ { - fmt.Println("Echo: " + strings.Join(args, " ")) - } - }, - } - - cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input") - - var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(cmdPrint, cmdEcho) - cmdEcho.AddCommand(cmdTimes) - rootCmd.Execute() -} -``` - -For a more complete example of a larger application, please checkout [Hugo](https://gohugo.io/). - -## Help Command - -Cobra automatically adds a help command to your application when you have subcommands. -This will be called when a user runs 'app help'. Additionally, help will also -support all other commands as input. Say, for instance, you have a command called -'create' without any additional configuration; Cobra will work when 'app help -create' is called. Every command will automatically have the '--help' flag added. - -### Example - -The following output is automatically generated by Cobra. Nothing beyond the -command and flag definitions are needed. - - $ cobra-cli help - - Cobra is a CLI library for Go that empowers applications. - This application is a tool to generate the needed files - to quickly create a Cobra application. - - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra-cli [command] --help" for more information about a command. - - -Help is just a command like any other. There is no special logic or behavior -around it. In fact, you can provide your own if you want. - -### Grouping commands in help - -Cobra supports grouping of available commands in the help output. To group commands, each group must be explicitly -defined using `AddGroup()` on the parent command. Then a subcommand can be added to a group using the `GroupID` element -of that subcommand. The groups will appear in the help output in the same order as they are defined using different -calls to `AddGroup()`. If you use the generated `help` or `completion` commands, you can set their group ids using -`SetHelpCommandGroupId()` and `SetCompletionCommandGroupId()` on the root command, respectively. - -### Defining your own help - -You can provide your own Help command or your own template for the default command to use -with the following functions: - -```go -cmd.SetHelpCommand(cmd *Command) -cmd.SetHelpFunc(f func(*Command, []string)) -cmd.SetHelpTemplate(s string) -``` - -The latter two will also apply to any children commands. - -## Usage Message - -When the user provides an invalid flag or invalid command, Cobra responds by -showing the user the 'usage'. - -### Example -You may recognize this from the help above. That's because the default help -embeds the usage as part of its output. - - $ cobra-cli --invalid - Error: unknown flag: --invalid - Usage: - cobra-cli [command] - - Available Commands: - add Add a command to a Cobra Application - completion Generate the autocompletion script for the specified shell - help Help about any command - init Initialize a Cobra Application - - Flags: - -a, --author string author name for copyright attribution (default "YOUR NAME") - --config string config file (default is $HOME/.cobra.yaml) - -h, --help help for cobra-cli - -l, --license string name of license for the project - --viper use Viper for configuration - - Use "cobra [command] --help" for more information about a command. - -### Defining your own usage -You can provide your own usage function or template for Cobra to use. -Like help, the function and template are overridable through public methods: - -```go -cmd.SetUsageFunc(f func(*Command) error) -cmd.SetUsageTemplate(s string) -``` - -## Version Flag - -Cobra adds a top-level '--version' flag if the Version field is set on the root command. -Running an application with the '--version' flag will print the version to stdout using -the version template. The template can be customized using the -`cmd.SetVersionTemplate(s string)` function. - -## PreRun and PostRun Hooks - -It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order: - -- `PersistentPreRun` -- `PreRun` -- `Run` -- `PostRun` -- `PersistentPostRun` - -An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`: - -```go -package main - -import ( - "fmt" - - "github.com/spf13/cobra" -) - -func main() { - - var rootCmd = &cobra.Command{ - Use: "root [sub]", - Short: "My root command", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args) - }, - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args) - }, - } - - var subCmd = &cobra.Command{ - Use: "sub [no options!]", - Short: "My subcommand", - PreRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PreRun with args: %v\n", args) - }, - Run: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd Run with args: %v\n", args) - }, - PostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PostRun with args: %v\n", args) - }, - PersistentPostRun: func(cmd *cobra.Command, args []string) { - fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args) - }, - } - - rootCmd.AddCommand(subCmd) - - rootCmd.SetArgs([]string{""}) - rootCmd.Execute() - fmt.Println() - rootCmd.SetArgs([]string{"sub", "arg1", "arg2"}) - rootCmd.Execute() -} -``` - -Output: -``` -Inside rootCmd PersistentPreRun with args: [] -Inside rootCmd PreRun with args: [] -Inside rootCmd Run with args: [] -Inside rootCmd PostRun with args: [] -Inside rootCmd PersistentPostRun with args: [] - -Inside rootCmd PersistentPreRun with args: [arg1 arg2] -Inside subCmd PreRun with args: [arg1 arg2] -Inside subCmd Run with args: [arg1 arg2] -Inside subCmd PostRun with args: [arg1 arg2] -Inside subCmd PersistentPostRun with args: [arg1 arg2] -``` - -## Suggestions when "unknown command" happens - -Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example: - -``` -$ hugo srever -Error: unknown command "srever" for "hugo" - -Did you mean this? - server - -Run 'hugo --help' for usage. -``` - -Suggestions are automatically generated based on existing subcommands and use an implementation of [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion. - -If you need to disable suggestions or tweak the string distance in your command, use: - -```go -command.DisableSuggestions = true -``` - -or - -```go -command.SuggestionsMinimumDistance = 1 -``` - -You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but make sense in your set of commands but for which -you don't want aliases. Example: - -``` -$ kubectl remove -Error: unknown command "remove" for "kubectl" - -Did you mean this? - delete - -Run 'kubectl help' for usage. -``` - -## Generating documentation for your command - -Cobra can generate documentation based on subcommands, flags, etc. Read more about it in the [docs generation documentation](doc/README.md). - -## Generating shell completions - -Cobra can generate a shell-completion file for the following shells: bash, zsh, fish, PowerShell. If you add more information to your commands, these completions can be amazingly powerful and flexible. Read more about it in [Shell Completions](shell_completions.md). - -## Providing Active Help - -Cobra makes use of the shell-completion system to define a framework allowing you to provide Active Help to your users. Active Help are messages (hints, warnings, etc) printed as the program is being used. Read more about it in [Active Help](active_help.md). diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go deleted file mode 100644 index 1856e4c..0000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.go +++ /dev/null @@ -1,308 +0,0 @@ -// 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/cobra/zsh_completions.md b/vendor/github.com/spf13/cobra/zsh_completions.md deleted file mode 100644 index 7cff617..0000000 --- a/vendor/github.com/spf13/cobra/zsh_completions.md +++ /dev/null @@ -1,48 +0,0 @@ -## Generating Zsh Completion For Your cobra.Command - -Please refer to [Shell Completions](shell_completions.md) for details. - -## Zsh completions standardization - -Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced. - -### Deprecation summary - -See further below for more details on these deprecations. - -* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored. -* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`. -* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored. - * Instead use `ValidArgsFunction`. - -### Behavioral changes - -**Noun completion** -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis| -|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`| -`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored| -|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)| -|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior| - -**Flag-value completion** - -|Old behavior|New behavior| -|---|---| -|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion| -|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored| -|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)| -|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells| -|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`| -|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`| - -**Improvements** - -* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`) -* File completion by default if no other completions found -* Handling of required flags -* File extension filtering no longer mutually exclusive with bash usage -* Completion of directory names *within* another directory -* Support for `=` form of flags diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore deleted file mode 100644 index c3da290..0000000 --- a/vendor/github.com/spf13/pflag/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.idea/* - diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml deleted file mode 100644 index 00d04cb..0000000 --- a/vendor/github.com/spf13/pflag/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index 63ed1cf..0000000 --- a/vendor/github.com/spf13/pflag/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index 7eacc5b..0000000 --- a/vendor/github.com/spf13/pflag/README.md +++ /dev/null @@ -1,296 +0,0 @@ -[![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() -} -``` - -## 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 deleted file mode 100644 index c4c5c0b..0000000 --- a/vendor/github.com/spf13/pflag/bool.go +++ /dev/null @@ -1,94 +0,0 @@ -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_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go deleted file mode 100644 index 3731370..0000000 --- a/vendor/github.com/spf13/pflag/bool_slice.go +++ /dev/null @@ -1,185 +0,0 @@ -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 deleted file mode 100644 index 67d5304..0000000 --- a/vendor/github.com/spf13/pflag/bytes.go +++ /dev/null @@ -1,209 +0,0 @@ -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 deleted file mode 100644 index a0b2679..0000000 --- a/vendor/github.com/spf13/pflag/count.go +++ /dev/null @@ -1,96 +0,0 @@ -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 evey 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 deleted file mode 100644 index e9debef..0000000 --- a/vendor/github.com/spf13/pflag/duration.go +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index badadda..0000000 --- a/vendor/github.com/spf13/pflag/duration_slice.go +++ /dev/null @@ -1,166 +0,0 @@ -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/flag.go b/vendor/github.com/spf13/pflag/flag.go deleted file mode 100644 index 24a5036..0000000 --- a/vendor/github.com/spf13/pflag/flag.go +++ /dev/null @@ -1,1239 +0,0 @@ -// 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 -) - -// ParseErrorsWhitelist defines the parsing errors that can be ignored -type ParseErrorsWhitelist struct { - // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags - UnknownFlags bool -} - -// 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 - - // ParseErrorsWhitelist is used to configure a whitelist of errors - ParseErrorsWhitelist ParseErrorsWhitelist - - 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 out() 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) -} - -func (f *FlagSet) out() io.Writer { - if f.output == nil { - return os.Stderr - } - return f.output -} - -// 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.out(), 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 := fmt.Errorf("flag accessed but not defined: %s", name) - 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 fmt.Errorf("flag %q does not exist", name) - } - 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 fmt.Errorf("flag %q does not exist", name) - } - 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 fmt.Errorf("flag %q does not exist", name) - } - 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 fmt.Errorf("no such flag -%v", name) - } - - err := flag.Value.Set(value) - if err != nil { - 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.Errorf("invalid argument %q for %q flag: %v", value, flagName, 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.out(), "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 fmt.Errorf("no such flag -%v", name) - } - 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.out(), 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" - 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.Value.String() { - 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": - name = "" - 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": - 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.out(), "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.out(), 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.out(), 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.out(), 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) -} - -// failf prints to standard error a formatted error and usage message and -// returns the error. -func (f *FlagSet) failf(format string, a ...interface{}) error { - err := fmt.Errorf(format, a...) - if f.errorHandling != ContinueOnError { - fmt.Fprintln(f.out(), err) - 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.failf("bad flag syntax: %s", 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: - // --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.failf("unknown flag: --%s", name) - 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.failf("flag needs an argument: %s", s) - return - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } - return -} - -func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { - outArgs = args - - if strings.HasPrefix(shorthands, "test.") { - 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: - // '-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.failf("unknown shorthand flag: %q in -%s", c, shorthands) - 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.failf("flag needs an argument: %q in -%s", c, shorthands) - return - } - - if flag.ShorthandDeprecated != "" { - fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) - } - - err = fn(flag, value) - if err != nil { - f.failf(err.Error()) - } - 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 - - if len(arguments) < 0 { - return nil - } - - f.args = make([]string, 0, len(arguments)) - - 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: - fmt.Println(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: - 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 deleted file mode 100644 index a243f81..0000000 --- a/vendor/github.com/spf13/pflag/float32.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index caa3527..0000000 --- a/vendor/github.com/spf13/pflag/float32_slice.go +++ /dev/null @@ -1,174 +0,0 @@ -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 deleted file mode 100644 index 04b5492..0000000 --- a/vendor/github.com/spf13/pflag/float64.go +++ /dev/null @@ -1,84 +0,0 @@ -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 deleted file mode 100644 index 85bf307..0000000 --- a/vendor/github.com/spf13/pflag/float64_slice.go +++ /dev/null @@ -1,166 +0,0 @@ -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/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go deleted file mode 100644 index d3dd72b..0000000 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ /dev/null @@ -1,105 +0,0 @@ -// 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" -) - -// 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) -} diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go deleted file mode 100644 index 1474b89..0000000 --- a/vendor/github.com/spf13/pflag/int.go +++ /dev/null @@ -1,84 +0,0 @@ -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 deleted file mode 100644 index f1a01d0..0000000 --- a/vendor/github.com/spf13/pflag/int16.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index 9b95944..0000000 --- a/vendor/github.com/spf13/pflag/int32.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index ff128ff..0000000 --- a/vendor/github.com/spf13/pflag/int32_slice.go +++ /dev/null @@ -1,174 +0,0 @@ -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 deleted file mode 100644 index 0026d78..0000000 --- a/vendor/github.com/spf13/pflag/int64.go +++ /dev/null @@ -1,84 +0,0 @@ -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 deleted file mode 100644 index 2546463..0000000 --- a/vendor/github.com/spf13/pflag/int64_slice.go +++ /dev/null @@ -1,166 +0,0 @@ -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 deleted file mode 100644 index 4da9222..0000000 --- a/vendor/github.com/spf13/pflag/int8.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index e71c39d..0000000 --- a/vendor/github.com/spf13/pflag/int_slice.go +++ /dev/null @@ -1,158 +0,0 @@ -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 deleted file mode 100644 index 3d414ba..0000000 --- a/vendor/github.com/spf13/pflag/ip.go +++ /dev/null @@ -1,94 +0,0 @@ -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 { - 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 deleted file mode 100644 index 775faae..0000000 --- a/vendor/github.com/spf13/pflag/ip_slice.go +++ /dev/null @@ -1,186 +0,0 @@ -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 deleted file mode 100644 index 5bd44bd..0000000 --- a/vendor/github.com/spf13/pflag/ipmask.go +++ /dev/null @@ -1,122 +0,0 @@ -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 deleted file mode 100644 index e2c1b8b..0000000 --- a/vendor/github.com/spf13/pflag/ipnet.go +++ /dev/null @@ -1,98 +0,0 @@ -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/string.go b/vendor/github.com/spf13/pflag/string.go deleted file mode 100644 index 04e0a26..0000000 --- a/vendor/github.com/spf13/pflag/string.go +++ /dev/null @@ -1,80 +0,0 @@ -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 deleted file mode 100644 index 4894af8..0000000 --- a/vendor/github.com/spf13/pflag/string_array.go +++ /dev/null @@ -1,129 +0,0 @@ -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 { - var err error - out[i] = d - if err != nil { - return err - } - } - *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 deleted file mode 100644 index 3cb2e69..0000000 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ /dev/null @@ -1,163 +0,0 @@ -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 deleted file mode 100644 index 5ceda39..0000000 --- a/vendor/github.com/spf13/pflag/string_to_int.go +++ /dev/null @@ -1,149 +0,0 @@ -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 deleted file mode 100644 index a807a04..0000000 --- a/vendor/github.com/spf13/pflag/string_to_int64.go +++ /dev/null @@ -1,149 +0,0 @@ -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 deleted file mode 100644 index 890a01a..0000000 --- a/vendor/github.com/spf13/pflag/string_to_string.go +++ /dev/null @@ -1,160 +0,0 @@ -package pflag - -import ( - "bytes" - "encoding/csv" - "fmt" - "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 { - records := make([]string, 0, len(*s.value)>>1) - for k, v := range *s.value { - 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/uint.go b/vendor/github.com/spf13/pflag/uint.go deleted file mode 100644 index dcbc2b7..0000000 --- a/vendor/github.com/spf13/pflag/uint.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index 7e9914e..0000000 --- a/vendor/github.com/spf13/pflag/uint16.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index d802453..0000000 --- a/vendor/github.com/spf13/pflag/uint32.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index f62240f..0000000 --- a/vendor/github.com/spf13/pflag/uint64.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index bb0e83c..0000000 --- a/vendor/github.com/spf13/pflag/uint8.go +++ /dev/null @@ -1,88 +0,0 @@ -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 deleted file mode 100644 index 5fa9248..0000000 --- a/vendor/github.com/spf13/pflag/uint_slice.go +++ /dev/null @@ -1,168 +0,0 @@ -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/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE deleted file mode 100644 index 4b0421c..0000000 --- a/vendor/github.com/stretchr/testify/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2012-2020 Mat Ryer, Tyler Bunnell and contributors. - -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/stretchr/testify/assert/assertion_compare.go b/vendor/github.com/stretchr/testify/assert/assertion_compare.go deleted file mode 100644 index 95d8e59..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare.go +++ /dev/null @@ -1,458 +0,0 @@ -package assert - -import ( - "bytes" - "fmt" - "reflect" - "time" -) - -type CompareType int - -const ( - compareLess CompareType = iota - 1 - compareEqual - compareGreater -) - -var ( - intType = reflect.TypeOf(int(1)) - int8Type = reflect.TypeOf(int8(1)) - int16Type = reflect.TypeOf(int16(1)) - int32Type = reflect.TypeOf(int32(1)) - int64Type = reflect.TypeOf(int64(1)) - - uintType = reflect.TypeOf(uint(1)) - uint8Type = reflect.TypeOf(uint8(1)) - uint16Type = reflect.TypeOf(uint16(1)) - uint32Type = reflect.TypeOf(uint32(1)) - uint64Type = reflect.TypeOf(uint64(1)) - - float32Type = reflect.TypeOf(float32(1)) - float64Type = reflect.TypeOf(float64(1)) - - stringType = reflect.TypeOf("") - - timeType = reflect.TypeOf(time.Time{}) - bytesType = reflect.TypeOf([]byte{}) -) - -func compare(obj1, obj2 interface{}, kind reflect.Kind) (CompareType, bool) { - obj1Value := reflect.ValueOf(obj1) - obj2Value := reflect.ValueOf(obj2) - - // throughout this switch we try and avoid calling .Convert() if possible, - // as this has a pretty big performance impact - switch kind { - case reflect.Int: - { - intobj1, ok := obj1.(int) - if !ok { - intobj1 = obj1Value.Convert(intType).Interface().(int) - } - intobj2, ok := obj2.(int) - if !ok { - intobj2 = obj2Value.Convert(intType).Interface().(int) - } - if intobj1 > intobj2 { - return compareGreater, true - } - if intobj1 == intobj2 { - return compareEqual, true - } - if intobj1 < intobj2 { - return compareLess, true - } - } - case reflect.Int8: - { - int8obj1, ok := obj1.(int8) - if !ok { - int8obj1 = obj1Value.Convert(int8Type).Interface().(int8) - } - int8obj2, ok := obj2.(int8) - if !ok { - int8obj2 = obj2Value.Convert(int8Type).Interface().(int8) - } - if int8obj1 > int8obj2 { - return compareGreater, true - } - if int8obj1 == int8obj2 { - return compareEqual, true - } - if int8obj1 < int8obj2 { - return compareLess, true - } - } - case reflect.Int16: - { - int16obj1, ok := obj1.(int16) - if !ok { - int16obj1 = obj1Value.Convert(int16Type).Interface().(int16) - } - int16obj2, ok := obj2.(int16) - if !ok { - int16obj2 = obj2Value.Convert(int16Type).Interface().(int16) - } - if int16obj1 > int16obj2 { - return compareGreater, true - } - if int16obj1 == int16obj2 { - return compareEqual, true - } - if int16obj1 < int16obj2 { - return compareLess, true - } - } - case reflect.Int32: - { - int32obj1, ok := obj1.(int32) - if !ok { - int32obj1 = obj1Value.Convert(int32Type).Interface().(int32) - } - int32obj2, ok := obj2.(int32) - if !ok { - int32obj2 = obj2Value.Convert(int32Type).Interface().(int32) - } - if int32obj1 > int32obj2 { - return compareGreater, true - } - if int32obj1 == int32obj2 { - return compareEqual, true - } - if int32obj1 < int32obj2 { - return compareLess, true - } - } - case reflect.Int64: - { - int64obj1, ok := obj1.(int64) - if !ok { - int64obj1 = obj1Value.Convert(int64Type).Interface().(int64) - } - int64obj2, ok := obj2.(int64) - if !ok { - int64obj2 = obj2Value.Convert(int64Type).Interface().(int64) - } - if int64obj1 > int64obj2 { - return compareGreater, true - } - if int64obj1 == int64obj2 { - return compareEqual, true - } - if int64obj1 < int64obj2 { - return compareLess, true - } - } - case reflect.Uint: - { - uintobj1, ok := obj1.(uint) - if !ok { - uintobj1 = obj1Value.Convert(uintType).Interface().(uint) - } - uintobj2, ok := obj2.(uint) - if !ok { - uintobj2 = obj2Value.Convert(uintType).Interface().(uint) - } - if uintobj1 > uintobj2 { - return compareGreater, true - } - if uintobj1 == uintobj2 { - return compareEqual, true - } - if uintobj1 < uintobj2 { - return compareLess, true - } - } - case reflect.Uint8: - { - uint8obj1, ok := obj1.(uint8) - if !ok { - uint8obj1 = obj1Value.Convert(uint8Type).Interface().(uint8) - } - uint8obj2, ok := obj2.(uint8) - if !ok { - uint8obj2 = obj2Value.Convert(uint8Type).Interface().(uint8) - } - if uint8obj1 > uint8obj2 { - return compareGreater, true - } - if uint8obj1 == uint8obj2 { - return compareEqual, true - } - if uint8obj1 < uint8obj2 { - return compareLess, true - } - } - case reflect.Uint16: - { - uint16obj1, ok := obj1.(uint16) - if !ok { - uint16obj1 = obj1Value.Convert(uint16Type).Interface().(uint16) - } - uint16obj2, ok := obj2.(uint16) - if !ok { - uint16obj2 = obj2Value.Convert(uint16Type).Interface().(uint16) - } - if uint16obj1 > uint16obj2 { - return compareGreater, true - } - if uint16obj1 == uint16obj2 { - return compareEqual, true - } - if uint16obj1 < uint16obj2 { - return compareLess, true - } - } - case reflect.Uint32: - { - uint32obj1, ok := obj1.(uint32) - if !ok { - uint32obj1 = obj1Value.Convert(uint32Type).Interface().(uint32) - } - uint32obj2, ok := obj2.(uint32) - if !ok { - uint32obj2 = obj2Value.Convert(uint32Type).Interface().(uint32) - } - if uint32obj1 > uint32obj2 { - return compareGreater, true - } - if uint32obj1 == uint32obj2 { - return compareEqual, true - } - if uint32obj1 < uint32obj2 { - return compareLess, true - } - } - case reflect.Uint64: - { - uint64obj1, ok := obj1.(uint64) - if !ok { - uint64obj1 = obj1Value.Convert(uint64Type).Interface().(uint64) - } - uint64obj2, ok := obj2.(uint64) - if !ok { - uint64obj2 = obj2Value.Convert(uint64Type).Interface().(uint64) - } - if uint64obj1 > uint64obj2 { - return compareGreater, true - } - if uint64obj1 == uint64obj2 { - return compareEqual, true - } - if uint64obj1 < uint64obj2 { - return compareLess, true - } - } - case reflect.Float32: - { - float32obj1, ok := obj1.(float32) - if !ok { - float32obj1 = obj1Value.Convert(float32Type).Interface().(float32) - } - float32obj2, ok := obj2.(float32) - if !ok { - float32obj2 = obj2Value.Convert(float32Type).Interface().(float32) - } - if float32obj1 > float32obj2 { - return compareGreater, true - } - if float32obj1 == float32obj2 { - return compareEqual, true - } - if float32obj1 < float32obj2 { - return compareLess, true - } - } - case reflect.Float64: - { - float64obj1, ok := obj1.(float64) - if !ok { - float64obj1 = obj1Value.Convert(float64Type).Interface().(float64) - } - float64obj2, ok := obj2.(float64) - if !ok { - float64obj2 = obj2Value.Convert(float64Type).Interface().(float64) - } - if float64obj1 > float64obj2 { - return compareGreater, true - } - if float64obj1 == float64obj2 { - return compareEqual, true - } - if float64obj1 < float64obj2 { - return compareLess, true - } - } - case reflect.String: - { - stringobj1, ok := obj1.(string) - if !ok { - stringobj1 = obj1Value.Convert(stringType).Interface().(string) - } - stringobj2, ok := obj2.(string) - if !ok { - stringobj2 = obj2Value.Convert(stringType).Interface().(string) - } - if stringobj1 > stringobj2 { - return compareGreater, true - } - if stringobj1 == stringobj2 { - return compareEqual, true - } - if stringobj1 < stringobj2 { - return compareLess, true - } - } - // Check for known struct types we can check for compare results. - case reflect.Struct: - { - // All structs enter here. We're not interested in most types. - if !canConvert(obj1Value, timeType) { - break - } - - // time.Time can compared! - timeObj1, ok := obj1.(time.Time) - if !ok { - timeObj1 = obj1Value.Convert(timeType).Interface().(time.Time) - } - - timeObj2, ok := obj2.(time.Time) - if !ok { - timeObj2 = obj2Value.Convert(timeType).Interface().(time.Time) - } - - return compare(timeObj1.UnixNano(), timeObj2.UnixNano(), reflect.Int64) - } - case reflect.Slice: - { - // We only care about the []byte type. - if !canConvert(obj1Value, bytesType) { - break - } - - // []byte can be compared! - bytesObj1, ok := obj1.([]byte) - if !ok { - bytesObj1 = obj1Value.Convert(bytesType).Interface().([]byte) - - } - bytesObj2, ok := obj2.([]byte) - if !ok { - bytesObj2 = obj2Value.Convert(bytesType).Interface().([]byte) - } - - return CompareType(bytes.Compare(bytesObj1, bytesObj2)), true - } - } - - return compareEqual, false -} - -// Greater asserts that the first element is greater than the second -// -// assert.Greater(t, 2, 1) -// assert.Greater(t, float64(2), float64(1)) -// assert.Greater(t, "b", "a") -func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return compareTwoValues(t, e1, e2, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) -} - -// GreaterOrEqual asserts that the first element is greater than or equal to the second -// -// assert.GreaterOrEqual(t, 2, 1) -// assert.GreaterOrEqual(t, 2, 2) -// assert.GreaterOrEqual(t, "b", "a") -// assert.GreaterOrEqual(t, "b", "b") -func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return compareTwoValues(t, e1, e2, []CompareType{compareGreater, compareEqual}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) -} - -// Less asserts that the first element is less than the second -// -// assert.Less(t, 1, 2) -// assert.Less(t, float64(1), float64(2)) -// assert.Less(t, "a", "b") -func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return compareTwoValues(t, e1, e2, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) -} - -// LessOrEqual asserts that the first element is less than or equal to the second -// -// assert.LessOrEqual(t, 1, 2) -// assert.LessOrEqual(t, 2, 2) -// assert.LessOrEqual(t, "a", "b") -// assert.LessOrEqual(t, "b", "b") -func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return compareTwoValues(t, e1, e2, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) -} - -// Positive asserts that the specified element is positive -// -// assert.Positive(t, 1) -// assert.Positive(t, 1.23) -func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - zero := reflect.Zero(reflect.TypeOf(e)) - return compareTwoValues(t, e, zero.Interface(), []CompareType{compareGreater}, "\"%v\" is not positive", msgAndArgs...) -} - -// Negative asserts that the specified element is negative -// -// assert.Negative(t, -1) -// assert.Negative(t, -1.23) -func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - zero := reflect.Zero(reflect.TypeOf(e)) - return compareTwoValues(t, e, zero.Interface(), []CompareType{compareLess}, "\"%v\" is not negative", msgAndArgs...) -} - -func compareTwoValues(t TestingT, e1 interface{}, e2 interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - e1Kind := reflect.ValueOf(e1).Kind() - e2Kind := reflect.ValueOf(e2).Kind() - if e1Kind != e2Kind { - return Fail(t, "Elements should be the same type", msgAndArgs...) - } - - compareResult, isComparable := compare(e1, e2, e1Kind) - if !isComparable { - return Fail(t, fmt.Sprintf("Can not compare type \"%s\"", reflect.TypeOf(e1)), msgAndArgs...) - } - - if !containsValue(allowedComparesResults, compareResult) { - return Fail(t, fmt.Sprintf(failMessage, e1, e2), msgAndArgs...) - } - - return true -} - -func containsValue(values []CompareType, value CompareType) bool { - for _, v := range values { - if v == value { - return true - } - } - - return false -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go b/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go deleted file mode 100644 index da86790..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare_can_convert.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build go1.17 -// +build go1.17 - -// TODO: once support for Go 1.16 is dropped, this file can be -// merged/removed with assertion_compare_go1.17_test.go and -// assertion_compare_legacy.go - -package assert - -import "reflect" - -// Wrapper around reflect.Value.CanConvert, for compatibility -// reasons. -func canConvert(value reflect.Value, to reflect.Type) bool { - return value.CanConvert(to) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go b/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go deleted file mode 100644 index 1701af2..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_compare_legacy.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !go1.17 -// +build !go1.17 - -// TODO: once support for Go 1.16 is dropped, this file can be -// merged/removed with assertion_compare_go1.17_test.go and -// assertion_compare_can_convert.go - -package assert - -import "reflect" - -// Older versions of Go does not have the reflect.Value.CanConvert -// method. -func canConvert(value reflect.Value, to reflect.Type) bool { - return false -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go b/vendor/github.com/stretchr/testify/assert/assertion_format.go deleted file mode 100644 index 7880b8f..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go +++ /dev/null @@ -1,763 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package assert - -import ( - http "net/http" - url "net/url" - time "time" -) - -// Conditionf uses a Comparison to assert a complex condition. -func Conditionf(t TestingT, comp Comparison, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Condition(t, comp, append([]interface{}{msg}, args...)...) -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") -func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Contains(t, s, contains, append([]interface{}{msg}, args...)...) -} - -// DirExistsf checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return DirExists(t, path, append([]interface{}{msg}, args...)...) -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return ElementsMatch(t, listA, listB, append([]interface{}{msg}, args...)...) -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Emptyf(t, obj, "error message %s", "formatted") -func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Empty(t, object, append([]interface{}{msg}, args...)...) -} - -// Equalf asserts that two objects are equal. -// -// assert.Equalf(t, 123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Equal(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") -func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return EqualError(t, theError, errString, append([]interface{}{msg}, args...)...) -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") -func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func Errorf(t TestingT, err error, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Error(t, err, append([]interface{}{msg}, args...)...) -} - -// ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return ErrorAs(t, err, target, append([]interface{}{msg}, args...)...) -} - -// ErrorContainsf asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") -func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return ErrorContains(t, theError, contains, append([]interface{}{msg}, args...)...) -} - -// ErrorIsf asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return ErrorIs(t, err, target, append([]interface{}{msg}, args...)...) -} - -// Eventuallyf asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Eventually(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") -func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Exactly(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Failf reports a failure through -func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, failureMessage, append([]interface{}{msg}, args...)...) -} - -// FailNowf fails test -func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return FailNow(t, failureMessage, append([]interface{}{msg}, args...)...) -} - -// Falsef asserts that the specified value is false. -// -// assert.Falsef(t, myBool, "error message %s", "formatted") -func Falsef(t TestingT, value bool, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return False(t, value, append([]interface{}{msg}, args...)...) -} - -// FileExistsf checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func FileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return FileExists(t, path, append([]interface{}{msg}, args...)...) -} - -// Greaterf asserts that the first element is greater than the second -// -// assert.Greaterf(t, 2, 1, "error message %s", "formatted") -// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") -// assert.Greaterf(t, "b", "a", "error message %s", "formatted") -func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Greater(t, e1, e2, append([]interface{}{msg}, args...)...) -} - -// GreaterOrEqualf asserts that the first element is greater than or equal to the second -// -// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") -func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return GreaterOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...) -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPBodyContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPBodyNotContains(t, handler, method, url, values, str, append([]interface{}{msg}, args...)...) -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPError(t, handler, method, url, values, append([]interface{}{msg}, args...)...) -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPRedirect(t, handler, method, url, values, append([]interface{}{msg}, args...)...) -} - -// HTTPStatusCodef asserts that a specified handler returns a specified status code. -// -// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPStatusCode(t, handler, method, url, values, statuscode, append([]interface{}{msg}, args...)...) -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return HTTPSuccess(t, handler, method, url, values, append([]interface{}{msg}, args...)...) -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") -func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Implements(t, interfaceObject, object, append([]interface{}{msg}, args...)...) -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") -func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InDelta(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InDeltaMapValues(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InDeltaSlice(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InEpsilon(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return InEpsilonSlice(t, expected, actual, epsilon, append([]interface{}{msg}, args...)...) -} - -// IsDecreasingf asserts that the collection is decreasing -// -// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") -func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return IsDecreasing(t, object, append([]interface{}{msg}, args...)...) -} - -// IsIncreasingf asserts that the collection is increasing -// -// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") -func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return IsIncreasing(t, object, append([]interface{}{msg}, args...)...) -} - -// IsNonDecreasingf asserts that the collection is not decreasing -// -// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") -func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return IsNonDecreasing(t, object, append([]interface{}{msg}, args...)...) -} - -// IsNonIncreasingf asserts that the collection is not increasing -// -// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") -func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return IsNonIncreasing(t, object, append([]interface{}{msg}, args...)...) -} - -// IsTypef asserts that the specified objects are of the same type. -func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return IsType(t, expectedType, object, append([]interface{}{msg}, args...)...) -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return JSONEq(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") -func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Len(t, object, length, append([]interface{}{msg}, args...)...) -} - -// Lessf asserts that the first element is less than the second -// -// assert.Lessf(t, 1, 2, "error message %s", "formatted") -// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") -// assert.Lessf(t, "a", "b", "error message %s", "formatted") -func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Less(t, e1, e2, append([]interface{}{msg}, args...)...) -} - -// LessOrEqualf asserts that the first element is less than or equal to the second -// -// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") -// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") -func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return LessOrEqual(t, e1, e2, append([]interface{}{msg}, args...)...) -} - -// Negativef asserts that the specified element is negative -// -// assert.Negativef(t, -1, "error message %s", "formatted") -// assert.Negativef(t, -1.23, "error message %s", "formatted") -func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Negative(t, e, append([]interface{}{msg}, args...)...) -} - -// Neverf asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Never(t, condition, waitFor, tick, append([]interface{}{msg}, args...)...) -} - -// Nilf asserts that the specified object is nil. -// -// assert.Nilf(t, err, "error message %s", "formatted") -func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Nil(t, object, append([]interface{}{msg}, args...)...) -} - -// NoDirExistsf checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NoDirExists(t, path, append([]interface{}{msg}, args...)...) -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoErrorf(t TestingT, err error, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NoError(t, err, append([]interface{}{msg}, args...)...) -} - -// NoFileExistsf checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NoFileExists(t, path, append([]interface{}{msg}, args...)...) -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") -func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotContains(t, s, contains, append([]interface{}{msg}, args...)...) -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotEmpty(t, object, append([]interface{}{msg}, args...)...) -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotEqual(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// NotEqualValuesf asserts that two objects are not equal even when converted to the same type -// -// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") -func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotEqualValues(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// NotErrorIsf asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotErrorIs(t, err, target, append([]interface{}{msg}, args...)...) -} - -// NotNilf asserts that the specified object is not nil. -// -// assert.NotNilf(t, err, "error message %s", "formatted") -func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotNil(t, object, append([]interface{}{msg}, args...)...) -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") -func NotPanicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotPanics(t, f, append([]interface{}{msg}, args...)...) -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") -func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotRegexp(t, rx, str, append([]interface{}{msg}, args...)...) -} - -// NotSamef asserts that two pointers do not reference the same object. -// -// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotSame(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotSubset(t, list, subset, append([]interface{}{msg}, args...)...) -} - -// NotZerof asserts that i is not the zero value for its type. -func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return NotZero(t, i, append([]interface{}{msg}, args...)...) -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") -func Panicsf(t TestingT, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Panics(t, f, append([]interface{}{msg}, args...)...) -} - -// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func PanicsWithErrorf(t TestingT, errString string, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return PanicsWithError(t, errString, f, append([]interface{}{msg}, args...)...) -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func PanicsWithValuef(t TestingT, expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return PanicsWithValue(t, expected, f, append([]interface{}{msg}, args...)...) -} - -// Positivef asserts that the specified element is positive -// -// assert.Positivef(t, 1, "error message %s", "formatted") -// assert.Positivef(t, 1.23, "error message %s", "formatted") -func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Positive(t, e, append([]interface{}{msg}, args...)...) -} - -// Regexpf asserts that a specified regexp matches a string. -// -// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") -func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Regexp(t, rx, str, append([]interface{}{msg}, args...)...) -} - -// Samef asserts that two pointers reference the same object. -// -// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Same(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Subset(t, list, subset, append([]interface{}{msg}, args...)...) -} - -// Truef asserts that the specified value is true. -// -// assert.Truef(t, myBool, "error message %s", "formatted") -func Truef(t TestingT, value bool, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return True(t, value, append([]interface{}{msg}, args...)...) -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return WithinDuration(t, expected, actual, delta, append([]interface{}{msg}, args...)...) -} - -// WithinRangef asserts that a time is within a time range (inclusive). -// -// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") -func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return WithinRange(t, actual, start, end, append([]interface{}{msg}, args...)...) -} - -// YAMLEqf asserts that two YAML strings are equivalent. -func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return YAMLEq(t, expected, actual, append([]interface{}{msg}, args...)...) -} - -// Zerof asserts that i is the zero value for its type. -func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Zero(t, i, append([]interface{}{msg}, args...)...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl deleted file mode 100644 index d2bb0b8..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_format.go.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -{{.CommentFormat}} -func {{.DocInfo.Name}}f(t TestingT, {{.ParamsFormat}}) bool { - if h, ok := t.(tHelper); ok { h.Helper() } - return {{.DocInfo.Name}}(t, {{.ForwardedParamsFormat}}) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go deleted file mode 100644 index 339515b..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ /dev/null @@ -1,1514 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package assert - -import ( - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Condition(a.t, comp, msgAndArgs...) -} - -// Conditionf uses a Comparison to assert a complex condition. -func (a *Assertions) Conditionf(comp Comparison, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Conditionf(a.t, comp, msg, args...) -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World") -// a.Contains(["Hello", "World"], "World") -// a.Contains({"Hello": "World"}, "Hello") -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Contains(a.t, s, contains, msgAndArgs...) -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Containsf("Hello World", "World", "error message %s", "formatted") -// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") -// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") -func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Containsf(a.t, s, contains, msg, args...) -} - -// DirExists checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return DirExists(a.t, path, msgAndArgs...) -} - -// DirExistsf checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return DirExistsf(a.t, path, msg, args...) -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) -func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ElementsMatch(a.t, listA, listB, msgAndArgs...) -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ElementsMatchf(a.t, listA, listB, msg, args...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Empty(a.t, object, msgAndArgs...) -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Emptyf(obj, "error message %s", "formatted") -func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Emptyf(a.t, object, msg, args...) -} - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString) -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualError(a.t, theError, errString, msgAndArgs...) -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") -func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualErrorf(a.t, theError, errString, msg, args...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123)) -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") -func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return EqualValuesf(a.t, expected, actual, msg, args...) -} - -// Equalf asserts that two objects are equal. -// -// a.Equalf(123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Equalf(a.t, expected, actual, msg, args...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err) { -// assert.Equal(t, expectedError, err) -// } -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Error(a.t, err, msgAndArgs...) -} - -// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func (a *Assertions) ErrorAs(err error, target interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ErrorAs(a.t, err, target, msgAndArgs...) -} - -// ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ErrorAsf(a.t, err, target, msg, args...) -} - -// ErrorContains asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// a.ErrorContains(err, expectedErrorSubString) -func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ErrorContains(a.t, theError, contains, msgAndArgs...) -} - -// ErrorContainsf asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") -func (a *Assertions) ErrorContainsf(theError error, contains string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ErrorContainsf(a.t, theError, contains, msg, args...) -} - -// ErrorIs asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) ErrorIs(err error, target error, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ErrorIs(a.t, err, target, msgAndArgs...) -} - -// ErrorIsf asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return ErrorIsf(a.t, err, target, msg, args...) -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Errorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func (a *Assertions) Errorf(err error, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Errorf(a.t, err, msg, args...) -} - -// Eventually asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) -func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Eventually(a.t, condition, waitFor, tick, msgAndArgs...) -} - -// Eventuallyf asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Eventuallyf(a.t, condition, waitFor, tick, msg, args...) -} - -// Exactly asserts that two objects are equal in value and type. -// -// a.Exactly(int32(123), int64(123)) -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Exactly(a.t, expected, actual, msgAndArgs...) -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") -func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Exactlyf(a.t, expected, actual, msg, args...) -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Fail(a.t, failureMessage, msgAndArgs...) -} - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FailNow(a.t, failureMessage, msgAndArgs...) -} - -// FailNowf fails test -func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FailNowf(a.t, failureMessage, msg, args...) -} - -// Failf reports a failure through -func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Failf(a.t, failureMessage, msg, args...) -} - -// False asserts that the specified value is false. -// -// a.False(myBool) -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return False(a.t, value, msgAndArgs...) -} - -// Falsef asserts that the specified value is false. -// -// a.Falsef(myBool, "error message %s", "formatted") -func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Falsef(a.t, value, msg, args...) -} - -// FileExists checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FileExists(a.t, path, msgAndArgs...) -} - -// FileExistsf checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return FileExistsf(a.t, path, msg, args...) -} - -// Greater asserts that the first element is greater than the second -// -// a.Greater(2, 1) -// a.Greater(float64(2), float64(1)) -// a.Greater("b", "a") -func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Greater(a.t, e1, e2, msgAndArgs...) -} - -// GreaterOrEqual asserts that the first element is greater than or equal to the second -// -// a.GreaterOrEqual(2, 1) -// a.GreaterOrEqual(2, 2) -// a.GreaterOrEqual("b", "a") -// a.GreaterOrEqual("b", "b") -func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return GreaterOrEqual(a.t, e1, e2, msgAndArgs...) -} - -// GreaterOrEqualf asserts that the first element is greater than or equal to the second -// -// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") -// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") -// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") -// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") -func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return GreaterOrEqualf(a.t, e1, e2, msg, args...) -} - -// Greaterf asserts that the first element is greater than the second -// -// a.Greaterf(2, 1, "error message %s", "formatted") -// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") -// a.Greaterf("b", "a", "error message %s", "formatted") -func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Greaterf(a.t, e1, e2, msg, args...) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPError(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPErrorf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPRedirectf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPStatusCode asserts that a specified handler returns a specified status code. -// -// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...) -} - -// HTTPStatusCodef asserts that a specified handler returns a specified status code. -// -// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...) -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return HTTPSuccessf(a.t, handler, method, url, values, msg, args...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject)) -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") -func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Implementsf(a.t, interfaceObject, object, msg, args...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, 22/7.0, 0.01) -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaSlicef(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") -func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InDeltaf(a.t, expected, actual, delta, msg, args...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return InEpsilonf(a.t, expected, actual, epsilon, msg, args...) -} - -// IsDecreasing asserts that the collection is decreasing -// -// a.IsDecreasing([]int{2, 1, 0}) -// a.IsDecreasing([]float{2, 1}) -// a.IsDecreasing([]string{"b", "a"}) -func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsDecreasing(a.t, object, msgAndArgs...) -} - -// IsDecreasingf asserts that the collection is decreasing -// -// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") -// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") -func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsDecreasingf(a.t, object, msg, args...) -} - -// IsIncreasing asserts that the collection is increasing -// -// a.IsIncreasing([]int{1, 2, 3}) -// a.IsIncreasing([]float{1, 2}) -// a.IsIncreasing([]string{"a", "b"}) -func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsIncreasing(a.t, object, msgAndArgs...) -} - -// IsIncreasingf asserts that the collection is increasing -// -// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") -// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") -func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsIncreasingf(a.t, object, msg, args...) -} - -// IsNonDecreasing asserts that the collection is not decreasing -// -// a.IsNonDecreasing([]int{1, 1, 2}) -// a.IsNonDecreasing([]float{1, 2}) -// a.IsNonDecreasing([]string{"a", "b"}) -func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsNonDecreasing(a.t, object, msgAndArgs...) -} - -// IsNonDecreasingf asserts that the collection is not decreasing -// -// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") -func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsNonDecreasingf(a.t, object, msg, args...) -} - -// IsNonIncreasing asserts that the collection is not increasing -// -// a.IsNonIncreasing([]int{2, 1, 1}) -// a.IsNonIncreasing([]float{2, 1}) -// a.IsNonIncreasing([]string{"b", "a"}) -func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsNonIncreasing(a.t, object, msgAndArgs...) -} - -// IsNonIncreasingf asserts that the collection is not increasing -// -// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") -func (a *Assertions) IsNonIncreasingf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsNonIncreasingf(a.t, object, msg, args...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsType(a.t, expectedType, object, msgAndArgs...) -} - -// IsTypef asserts that the specified objects are of the same type. -func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return IsTypef(a.t, expectedType, object, msg, args...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return JSONEq(a.t, expected, actual, msgAndArgs...) -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return JSONEqf(a.t, expected, actual, msg, args...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3) -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Len(a.t, object, length, msgAndArgs...) -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// a.Lenf(mySlice, 3, "error message %s", "formatted") -func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Lenf(a.t, object, length, msg, args...) -} - -// Less asserts that the first element is less than the second -// -// a.Less(1, 2) -// a.Less(float64(1), float64(2)) -// a.Less("a", "b") -func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Less(a.t, e1, e2, msgAndArgs...) -} - -// LessOrEqual asserts that the first element is less than or equal to the second -// -// a.LessOrEqual(1, 2) -// a.LessOrEqual(2, 2) -// a.LessOrEqual("a", "b") -// a.LessOrEqual("b", "b") -func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return LessOrEqual(a.t, e1, e2, msgAndArgs...) -} - -// LessOrEqualf asserts that the first element is less than or equal to the second -// -// a.LessOrEqualf(1, 2, "error message %s", "formatted") -// a.LessOrEqualf(2, 2, "error message %s", "formatted") -// a.LessOrEqualf("a", "b", "error message %s", "formatted") -// a.LessOrEqualf("b", "b", "error message %s", "formatted") -func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return LessOrEqualf(a.t, e1, e2, msg, args...) -} - -// Lessf asserts that the first element is less than the second -// -// a.Lessf(1, 2, "error message %s", "formatted") -// a.Lessf(float64(1), float64(2), "error message %s", "formatted") -// a.Lessf("a", "b", "error message %s", "formatted") -func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Lessf(a.t, e1, e2, msg, args...) -} - -// Negative asserts that the specified element is negative -// -// a.Negative(-1) -// a.Negative(-1.23) -func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Negative(a.t, e, msgAndArgs...) -} - -// Negativef asserts that the specified element is negative -// -// a.Negativef(-1, "error message %s", "formatted") -// a.Negativef(-1.23, "error message %s", "formatted") -func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Negativef(a.t, e, msg, args...) -} - -// Never asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) -func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Never(a.t, condition, waitFor, tick, msgAndArgs...) -} - -// Neverf asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Neverf(a.t, condition, waitFor, tick, msg, args...) -} - -// Nil asserts that the specified object is nil. -// -// a.Nil(err) -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Nil(a.t, object, msgAndArgs...) -} - -// Nilf asserts that the specified object is nil. -// -// a.Nilf(err, "error message %s", "formatted") -func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Nilf(a.t, object, msg, args...) -} - -// NoDirExists checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoDirExists(a.t, path, msgAndArgs...) -} - -// NoDirExistsf checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoDirExistsf(a.t, path, msg, args...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoError(a.t, err, msgAndArgs...) -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoErrorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoErrorf(a.t, err, msg, args...) -} - -// NoFileExists checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func (a *Assertions) NoFileExists(path string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoFileExists(a.t, path, msgAndArgs...) -} - -// NoFileExistsf checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NoFileExistsf(a.t, path, msg, args...) -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth") -// a.NotContains(["Hello", "World"], "Earth") -// a.NotContains({"Hello": "World"}, "Earth") -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotContains(a.t, s, contains, msgAndArgs...) -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") -// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") -// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") -func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotContainsf(a.t, s, contains, msg, args...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEmpty(a.t, object, msgAndArgs...) -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmptyf(obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEmptyf(a.t, object, msg, args...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// NotEqualValues asserts that two objects are not equal even when converted to the same type -// -// a.NotEqualValues(obj1, obj2) -func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEqualValues(a.t, expected, actual, msgAndArgs...) -} - -// NotEqualValuesf asserts that two objects are not equal even when converted to the same type -// -// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") -func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEqualValuesf(a.t, expected, actual, msg, args...) -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// a.NotEqualf(obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotEqualf(a.t, expected, actual, msg, args...) -} - -// NotErrorIs asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotErrorIs(a.t, err, target, msgAndArgs...) -} - -// NotErrorIsf asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotErrorIsf(a.t, err, target, msg, args...) -} - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err) -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotNil(a.t, object, msgAndArgs...) -} - -// NotNilf asserts that the specified object is not nil. -// -// a.NotNilf(err, "error message %s", "formatted") -func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotNilf(a.t, object, msg, args...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ RemainCalm() }) -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotPanics(a.t, f, msgAndArgs...) -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") -func (a *Assertions) NotPanicsf(f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotPanicsf(a.t, f, msg, args...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") -func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotRegexpf(a.t, rx, str, msg, args...) -} - -// NotSame asserts that two pointers do not reference the same object. -// -// a.NotSame(ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotSame(a.t, expected, actual, msgAndArgs...) -} - -// NotSamef asserts that two pointers do not reference the same object. -// -// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotSamef(a.t, expected, actual, msg, args...) -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotSubset(a.t, list, subset, msgAndArgs...) -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotSubsetf(a.t, list, subset, msg, args...) -} - -// NotZero asserts that i is not the zero value for its type. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotZero(a.t, i, msgAndArgs...) -} - -// NotZerof asserts that i is not the zero value for its type. -func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return NotZerof(a.t, i, msg, args...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ GoCrazy() }) -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Panics(a.t, f, msgAndArgs...) -} - -// PanicsWithError asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// a.PanicsWithError("crazy error", func(){ GoCrazy() }) -func (a *Assertions) PanicsWithError(errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return PanicsWithError(a.t, errString, f, msgAndArgs...) -} - -// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) PanicsWithErrorf(errString string, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return PanicsWithErrorf(a.t, errString, f, msg, args...) -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) -func (a *Assertions) PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return PanicsWithValue(a.t, expected, f, msgAndArgs...) -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return PanicsWithValuef(a.t, expected, f, msg, args...) -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) Panicsf(f PanicTestFunc, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Panicsf(a.t, f, msg, args...) -} - -// Positive asserts that the specified element is positive -// -// a.Positive(1) -// a.Positive(1.23) -func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Positive(a.t, e, msgAndArgs...) -} - -// Positivef asserts that the specified element is positive -// -// a.Positivef(1, "error message %s", "formatted") -// a.Positivef(1.23, "error message %s", "formatted") -func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Positivef(a.t, e, msg, args...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Regexp(a.t, rx, str, msgAndArgs...) -} - -// Regexpf asserts that a specified regexp matches a string. -// -// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") -func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Regexpf(a.t, rx, str, msg, args...) -} - -// Same asserts that two pointers reference the same object. -// -// a.Same(ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Same(a.t, expected, actual, msgAndArgs...) -} - -// Samef asserts that two pointers reference the same object. -// -// a.Samef(ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Samef(a.t, expected, actual, msg, args...) -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Subset(a.t, list, subset, msgAndArgs...) -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Subsetf(a.t, list, subset, msg, args...) -} - -// True asserts that the specified value is true. -// -// a.True(myBool) -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return True(a.t, value, msgAndArgs...) -} - -// Truef asserts that the specified value is true. -// -// a.Truef(myBool, "error message %s", "formatted") -func (a *Assertions) Truef(value bool, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Truef(a.t, value, msg, args...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return WithinDurationf(a.t, expected, actual, delta, msg, args...) -} - -// WithinRange asserts that a time is within a time range (inclusive). -// -// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) -func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return WithinRange(a.t, actual, start, end, msgAndArgs...) -} - -// WithinRangef asserts that a time is within a time range (inclusive). -// -// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") -func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return WithinRangef(a.t, actual, start, end, msg, args...) -} - -// YAMLEq asserts that two YAML strings are equivalent. -func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return YAMLEq(a.t, expected, actual, msgAndArgs...) -} - -// YAMLEqf asserts that two YAML strings are equivalent. -func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return YAMLEqf(a.t, expected, actual, msg, args...) -} - -// Zero asserts that i is the zero value for its type. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Zero(a.t, i, msgAndArgs...) -} - -// Zerof asserts that i is the zero value for its type. -func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) bool { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - return Zerof(a.t, i, msg, args...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl b/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl deleted file mode 100644 index 188bb9e..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -{{.CommentWithoutT "a"}} -func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) bool { - if h, ok := a.t.(tHelper); ok { h.Helper() } - return {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertion_order.go b/vendor/github.com/stretchr/testify/assert/assertion_order.go deleted file mode 100644 index 7594487..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_order.go +++ /dev/null @@ -1,81 +0,0 @@ -package assert - -import ( - "fmt" - "reflect" -) - -// isOrdered checks that collection contains orderable elements. -func isOrdered(t TestingT, object interface{}, allowedComparesResults []CompareType, failMessage string, msgAndArgs ...interface{}) bool { - objKind := reflect.TypeOf(object).Kind() - if objKind != reflect.Slice && objKind != reflect.Array { - return false - } - - objValue := reflect.ValueOf(object) - objLen := objValue.Len() - - if objLen <= 1 { - return true - } - - value := objValue.Index(0) - valueInterface := value.Interface() - firstValueKind := value.Kind() - - for i := 1; i < objLen; i++ { - prevValue := value - prevValueInterface := valueInterface - - value = objValue.Index(i) - valueInterface = value.Interface() - - compareResult, isComparable := compare(prevValueInterface, valueInterface, firstValueKind) - - if !isComparable { - return Fail(t, fmt.Sprintf("Can not compare type \"%s\" and \"%s\"", reflect.TypeOf(value), reflect.TypeOf(prevValue)), msgAndArgs...) - } - - if !containsValue(allowedComparesResults, compareResult) { - return Fail(t, fmt.Sprintf(failMessage, prevValue, value), msgAndArgs...) - } - } - - return true -} - -// IsIncreasing asserts that the collection is increasing -// -// assert.IsIncreasing(t, []int{1, 2, 3}) -// assert.IsIncreasing(t, []float{1, 2}) -// assert.IsIncreasing(t, []string{"a", "b"}) -func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...) -} - -// IsNonIncreasing asserts that the collection is not increasing -// -// assert.IsNonIncreasing(t, []int{2, 1, 1}) -// assert.IsNonIncreasing(t, []float{2, 1}) -// assert.IsNonIncreasing(t, []string{"b", "a"}) -func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...) -} - -// IsDecreasing asserts that the collection is decreasing -// -// assert.IsDecreasing(t, []int{2, 1, 0}) -// assert.IsDecreasing(t, []float{2, 1}) -// assert.IsDecreasing(t, []string{"b", "a"}) -func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...) -} - -// IsNonDecreasing asserts that the collection is not decreasing -// -// assert.IsNonDecreasing(t, []int{1, 1, 2}) -// assert.IsNonDecreasing(t, []float{1, 2}) -// assert.IsNonDecreasing(t, []string{"a", "b"}) -func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - return isOrdered(t, object, []CompareType{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go deleted file mode 100644 index fa1245b..0000000 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ /dev/null @@ -1,1868 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "os" - "path/filepath" - "reflect" - "regexp" - "runtime" - "runtime/debug" - "strings" - "time" - "unicode" - "unicode/utf8" - - "github.com/davecgh/go-spew/spew" - "github.com/pmezard/go-difflib/difflib" - yaml "gopkg.in/yaml.v3" -) - -//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl" - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful -// for table driven tests. -type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool - -// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful -// for table driven tests. -type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool - -// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful -// for table driven tests. -type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool - -// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful -// for table driven tests. -type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool - -// Comparison is a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - if expected == nil || actual == nil { - return expected == actual - } - - exp, ok := expected.([]byte) - if !ok { - return reflect.DeepEqual(expected, actual) - } - - act, ok := actual.([]byte) - if !ok { - return false - } - if exp == nil || act == nil { - return exp == nil && act == nil - } - return bytes.Equal(exp, act) -} - -// ObjectsAreEqualValues gets whether two objects are equal, or if their -// values are equal. -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - if actualType == nil { - return false - } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occurred in calling code.*/ - -// CallerInfo returns an array of strings containing the file and line number -// of each stack frame leading from the current test to the assert call that -// failed. -func CallerInfo() []string { - - var pc uintptr - var ok bool - var file string - var line int - var name string - - callers := []string{} - for i := 0; ; i++ { - pc, file, line, ok = runtime.Caller(i) - if !ok { - // The breaks below failed to terminate the loop, and we ran off the - // end of the call stack. - break - } - - // This is a huge edge case, but it will panic if this is the case, see #180 - if file == "" { - break - } - - f := runtime.FuncForPC(pc) - if f == nil { - break - } - name = f.Name() - - // testing.tRunner is the standard library function that calls - // tests. Subtests are called directly by tRunner, without going through - // the Test/Benchmark/Example function that contains the t.Run calls, so - // with subtests we should break when we hit tRunner, without adding it - // to the list of callers. - if name == "testing.tRunner" { - break - } - - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - if len(parts) > 1 { - dir := parts[len(parts)-2] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - path, _ := filepath.Abs(file) - callers = append(callers, fmt.Sprintf("%s:%d", path, line)) - } - } - - // Drop the package - segments := strings.Split(name, ".") - name = segments[len(segments)-1] - if isTest(name, "Test") || - isTest(name, "Benchmark") || - isTest(name, "Example") { - break - } - } - - return callers -} - -// Stolen from the `go test` tool. -// isTest tells whether name looks like a test (or benchmark, according to prefix). -// It is a Test (say) if there is a character after Test that is not a lower-case letter. -// We don't want TesticularCancer. -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - r, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(r) -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - msg := msgAndArgs[0] - if msgAsStr, ok := msg.(string); ok { - return msgAsStr - } - return fmt.Sprintf("%+v", msg) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Aligns the provided message so that all lines after the first line start at the same location as the first line. -// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). -// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the -// basis on which the alignment occurs). -func indentMessageLines(message string, longestLabelLen int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - // no need to align first line because it starts at the correct location (after the label) - if i != 0 { - // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab - outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t") - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -type failNower interface { - FailNow() -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - Fail(t, failureMessage, msgAndArgs...) - - // We cannot extend TestingT with FailNow() and - // maintain backwards compatibility, so we fallback - // to panicking when FailNow is not available in - // TestingT. - // See issue #263 - - if t, ok := t.(failNower); ok { - t.FailNow() - } else { - panic("test failed and t is missing `FailNow()`") - } - return false -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - content := []labeledContent{ - {"Error Trace", strings.Join(CallerInfo(), "\n\t\t\t")}, - {"Error", failureMessage}, - } - - // Add test name if the Go version supports it - if n, ok := t.(interface { - Name() string - }); ok { - content = append(content, labeledContent{"Test", n.Name()}) - } - - message := messageFromMsgAndArgs(msgAndArgs...) - if len(message) > 0 { - content = append(content, labeledContent{"Messages", message}) - } - - t.Errorf("\n%s", ""+labeledOutput(content...)) - - return false -} - -type labeledContent struct { - label string - content string -} - -// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: -// -// \t{{label}}:{{align_spaces}}\t{{content}}\n -// -// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. -// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this -// alignment is achieved, "\t{{content}}\n" is added for the output. -// -// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. -func labeledOutput(content ...labeledContent) string { - longestLabel := 0 - for _, v := range content { - if len(v.label) > longestLabel { - longestLabel = len(v.label) - } - } - var output string - for _, v := range content { - output += "\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" - } - return output -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if object == nil { - return Fail(t, fmt.Sprintf("Cannot check if nil implements %v", interfaceType), msgAndArgs...) - } - if !reflect.TypeOf(object).Implements(interfaceType) { - return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) - } - - return true -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } - - return true -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if err := validateEqualArgs(expected, actual); err != nil { - return Fail(t, fmt.Sprintf("Invalid operation: %#v == %#v (%s)", - expected, actual, err), msgAndArgs...) - } - - if !ObjectsAreEqual(expected, actual) { - diff := diff(expected, actual) - expected, actual = formatUnequalValues(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: \n"+ - "expected: %s\n"+ - "actual : %s%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// validateEqualArgs checks whether provided arguments can be safely used in the -// Equal/NotEqual functions. -func validateEqualArgs(expected, actual interface{}) error { - if expected == nil && actual == nil { - return nil - } - - if isFunction(expected) || isFunction(actual) { - return errors.New("cannot take func type as argument") - } - return nil -} - -// Same asserts that two pointers reference the same object. -// -// assert.Same(t, ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if !samePointers(expected, actual) { - return Fail(t, fmt.Sprintf("Not same: \n"+ - "expected: %p %#v\n"+ - "actual : %p %#v", expected, expected, actual, actual), msgAndArgs...) - } - - return true -} - -// NotSame asserts that two pointers do not reference the same object. -// -// assert.NotSame(t, ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if samePointers(expected, actual) { - return Fail(t, fmt.Sprintf( - "Expected and actual point to the same object: %p %#v", - expected, expected), msgAndArgs...) - } - return true -} - -// samePointers compares two generic interface objects and returns whether -// they point to the same object -func samePointers(first, second interface{}) bool { - firstPtr, secondPtr := reflect.ValueOf(first), reflect.ValueOf(second) - if firstPtr.Kind() != reflect.Ptr || secondPtr.Kind() != reflect.Ptr { - return false - } - - firstType, secondType := reflect.TypeOf(first), reflect.TypeOf(second) - if firstType != secondType { - return false - } - - // compare pointer addresses - return first == second -} - -// formatUnequalValues takes two values of arbitrary types and returns string -// representations appropriate to be presented to the user. -// -// If the values are not of like type, the returned strings will be prefixed -// with the type name, and the value will be enclosed in parenthesis similar -// to a type conversion in the Go grammar. -func formatUnequalValues(expected, actual interface{}) (e string, a string) { - if reflect.TypeOf(expected) != reflect.TypeOf(actual) { - return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)), - fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual)) - } - switch expected.(type) { - case time.Duration: - return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual) - } - return truncatingFormat(expected), truncatingFormat(actual) -} - -// truncatingFormat formats the data and truncates it if it's too long. -// -// This helps keep formatted error messages lines from exceeding the -// bufio.MaxScanTokenSize max line length that the go testing framework imposes. -func truncatingFormat(data interface{}) string { - value := fmt.Sprintf("%#v", data) - max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed. - if len(value) > max { - value = value[0:max] + "<... truncated>" - } - return value -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123)) -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if !ObjectsAreEqualValues(expected, actual) { - diff := diff(expected, actual) - expected, actual = formatUnequalValues(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: \n"+ - "expected: %s\n"+ - "actual : %s%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// Exactly asserts that two objects are equal in value and type. -// -// assert.Exactly(t, int32(123), int64(123)) -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - return Fail(t, fmt.Sprintf("Types expected to match exactly\n\t%v != %v", aType, bType), msgAndArgs...) - } - - return Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err) -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if !isNil(object) { - return true - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, "Expected value not to be nil.", msgAndArgs...) -} - -// containsKind checks if a specified kind in the slice of kinds. -func containsKind(kinds []reflect.Kind, kind reflect.Kind) bool { - for i := 0; i < len(kinds); i++ { - if kind == kinds[i] { - return true - } - } - - return false -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - isNilableKind := containsKind( - []reflect.Kind{ - reflect.Chan, reflect.Func, - reflect.Interface, reflect.Map, - reflect.Ptr, reflect.Slice}, - kind) - - if isNilableKind && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err) -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if isNil(object) { - return true - } - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - // get nil case out of the way - if object == nil { - return true - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - // collection types are empty when they have no element - case reflect.Chan, reflect.Map, reflect.Slice: - return objValue.Len() == 0 - // pointers are empty if nil or if the value they point to is empty - case reflect.Ptr: - if objValue.IsNil() { - return true - } - deref := objValue.Elem().Interface() - return isEmpty(deref) - // for all other types, compare against the zero value - // array types are empty when they match their zero-initialized state - default: - zero := reflect.Zero(objValue.Type()) - return reflect.DeepEqual(object, zero.Interface()) - } -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - pass := isEmpty(object) - if !pass { - if h, ok := t.(tHelper); ok { - h.Helper() - } - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - pass := !isEmpty(object) - if !pass { - if h, ok := t.(tHelper); ok { - h.Helper() - } - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3) -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - ok, l := getLen(object) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } - return true -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool) -func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - if !value { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, "Should be true", msgAndArgs...) - } - - return true - -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool) -func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - if value { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, "Should be false", msgAndArgs...) - } - - return true - -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if err := validateEqualArgs(expected, actual); err != nil { - return Fail(t, fmt.Sprintf("Invalid operation: %#v != %#v (%s)", - expected, actual, err), msgAndArgs...) - } - - if ObjectsAreEqual(expected, actual) { - return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) - } - - return true - -} - -// NotEqualValues asserts that two objects are not equal even when converted to the same type -// -// assert.NotEqualValues(t, obj1, obj2) -func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if ObjectsAreEqualValues(expected, actual) { - return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) - } - - return true -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func containsElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - listType := reflect.TypeOf(list) - if listType == nil { - return false, false - } - listKind := listType.Kind() - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if listKind == reflect.String { - elementValue := reflect.ValueOf(element) - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - if listKind == reflect.Map { - mapKeys := listValue.MapKeys() - for i := 0; i < len(mapKeys); i++ { - if ObjectsAreEqual(mapKeys[i].Interface(), element) { - return true, true - } - } - return true, false - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - ok, found := containsElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...) - } - - return true - -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - ok, found := containsElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if subset == nil { - return true // we consider nil to be equal to the nil set - } - - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - - listKind := reflect.TypeOf(list).Kind() - subsetKind := reflect.TypeOf(subset).Kind() - - if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) - } - - if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) - } - - subsetValue := reflect.ValueOf(subset) - if subsetKind == reflect.Map && listKind == reflect.Map { - listValue := reflect.ValueOf(list) - subsetKeys := subsetValue.MapKeys() - - for i := 0; i < len(subsetKeys); i++ { - subsetKey := subsetKeys[i] - subsetElement := subsetValue.MapIndex(subsetKey).Interface() - listElement := listValue.MapIndex(subsetKey).Interface() - - if !ObjectsAreEqual(subsetElement, listElement) { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, subsetElement), msgAndArgs...) - } - } - - return true - } - - for i := 0; i < subsetValue.Len(); i++ { - element := subsetValue.Index(i).Interface() - ok, found := containsElement(list, element) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", list, element), msgAndArgs...) - } - } - - return true -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok bool) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if subset == nil { - return Fail(t, "nil is the empty set which is a subset of every set", msgAndArgs...) - } - - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - - listKind := reflect.TypeOf(list).Kind() - subsetKind := reflect.TypeOf(subset).Kind() - - if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...) - } - - if subsetKind != reflect.Array && subsetKind != reflect.Slice && listKind != reflect.Map { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...) - } - - subsetValue := reflect.ValueOf(subset) - if subsetKind == reflect.Map && listKind == reflect.Map { - listValue := reflect.ValueOf(list) - subsetKeys := subsetValue.MapKeys() - - for i := 0; i < len(subsetKeys); i++ { - subsetKey := subsetKeys[i] - subsetElement := subsetValue.MapIndex(subsetKey).Interface() - listElement := listValue.MapIndex(subsetKey).Interface() - - if !ObjectsAreEqual(subsetElement, listElement) { - return true - } - } - - return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) - } - - for i := 0; i < subsetValue.Len(); i++ { - element := subsetValue.Index(i).Interface() - ok, found := containsElement(list, element) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", list), msgAndArgs...) - } - if !found { - return true - } - } - - return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...) -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) -func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) (ok bool) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if isEmpty(listA) && isEmpty(listB) { - return true - } - - if !isList(t, listA, msgAndArgs...) || !isList(t, listB, msgAndArgs...) { - return false - } - - extraA, extraB := diffLists(listA, listB) - - if len(extraA) == 0 && len(extraB) == 0 { - return true - } - - return Fail(t, formatListDiff(listA, listB, extraA, extraB), msgAndArgs...) -} - -// isList checks that the provided value is array or slice. -func isList(t TestingT, list interface{}, msgAndArgs ...interface{}) (ok bool) { - kind := reflect.TypeOf(list).Kind() - if kind != reflect.Array && kind != reflect.Slice { - return Fail(t, fmt.Sprintf("%q has an unsupported type %s, expecting array or slice", list, kind), - msgAndArgs...) - } - return true -} - -// diffLists diffs two arrays/slices and returns slices of elements that are only in A and only in B. -// If some element is present multiple times, each instance is counted separately (e.g. if something is 2x in A and -// 5x in B, it will be 0x in extraA and 3x in extraB). The order of items in both lists is ignored. -func diffLists(listA, listB interface{}) (extraA, extraB []interface{}) { - aValue := reflect.ValueOf(listA) - bValue := reflect.ValueOf(listB) - - aLen := aValue.Len() - bLen := bValue.Len() - - // Mark indexes in bValue that we already used - visited := make([]bool, bLen) - for i := 0; i < aLen; i++ { - element := aValue.Index(i).Interface() - found := false - for j := 0; j < bLen; j++ { - if visited[j] { - continue - } - if ObjectsAreEqual(bValue.Index(j).Interface(), element) { - visited[j] = true - found = true - break - } - } - if !found { - extraA = append(extraA, element) - } - } - - for j := 0; j < bLen; j++ { - if visited[j] { - continue - } - extraB = append(extraB, bValue.Index(j).Interface()) - } - - return -} - -func formatListDiff(listA, listB interface{}, extraA, extraB []interface{}) string { - var msg bytes.Buffer - - msg.WriteString("elements differ") - if len(extraA) > 0 { - msg.WriteString("\n\nextra elements in list A:\n") - msg.WriteString(spewConfig.Sdump(extraA)) - } - if len(extraB) > 0 { - msg.WriteString("\n\nextra elements in list B:\n") - msg.WriteString(spewConfig.Sdump(extraB)) - } - msg.WriteString("\n\nlistA:\n") - msg.WriteString(spewConfig.Sdump(listA)) - msg.WriteString("\n\nlistB:\n") - msg.WriteString(spewConfig.Sdump(listB)) - - return msg.String() -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } - return result -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (didPanic bool, message interface{}, stack string) { - didPanic = true - - defer func() { - message = recover() - if didPanic { - stack = string(debug.Stack()) - } - }() - - // call the target function - f() - didPanic = false - - return -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ GoCrazy() }) -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if funcDidPanic, panicValue, _ := didPanic(f); !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) - } - - return true -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) -func PanicsWithValue(t TestingT, expected interface{}, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - funcDidPanic, panicValue, panickedStack := didPanic(f) - if !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) - } - if panicValue != expected { - return Fail(t, fmt.Sprintf("func %#v should panic with value:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, expected, panicValue, panickedStack), msgAndArgs...) - } - - return true -} - -// PanicsWithError asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) -func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - funcDidPanic, panicValue, panickedStack := didPanic(f) - if !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...) - } - panicErr, ok := panicValue.(error) - if !ok || panicErr.Error() != errString { - return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...) - } - - return true -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ RemainCalm() }) -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if funcDidPanic, panicValue, panickedStack := didPanic(f); funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should not panic\n\tPanic value:\t%v\n\tPanic stack:\t%s", f, panicValue, panickedStack), msgAndArgs...) - } - - return true -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// WithinRange asserts that a time is within a time range (inclusive). -// -// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) -func WithinRange(t TestingT, actual, start, end time.Time, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - if end.Before(start) { - return Fail(t, "Start should be before end", msgAndArgs...) - } - - if actual.Before(start) { - return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is before the range", actual, start, end), msgAndArgs...) - } else if actual.After(end) { - return Fail(t, fmt.Sprintf("Time %v expected to be in time range %v to %v, but is after the range", actual, start, end), msgAndArgs...) - } - - return true -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint: - xf = float64(xn) - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = xn - case time.Duration: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, 22/7.0, 0.01) -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - return Fail(t, "Parameters must be numerical", msgAndArgs...) - } - - if math.IsNaN(af) && math.IsNaN(bf) { - return true - } - - if math.IsNaN(af) { - return Fail(t, "Expected must not be NaN", msgAndArgs...) - } - - if math.IsNaN(bf) { - return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, "Parameters must be slice", msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta, msgAndArgs...) - if !result { - return result - } - } - - return true -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Map || - reflect.TypeOf(expected).Kind() != reflect.Map { - return Fail(t, "Arguments must be maps", msgAndArgs...) - } - - expectedMap := reflect.ValueOf(expected) - actualMap := reflect.ValueOf(actual) - - if expectedMap.Len() != actualMap.Len() { - return Fail(t, "Arguments must have the same number of keys", msgAndArgs...) - } - - for _, k := range expectedMap.MapKeys() { - ev := expectedMap.MapIndex(k) - av := actualMap.MapIndex(k) - - if !ev.IsValid() { - return Fail(t, fmt.Sprintf("missing key %q in expected map", k), msgAndArgs...) - } - - if !av.IsValid() { - return Fail(t, fmt.Sprintf("missing key %q in actual map", k), msgAndArgs...) - } - - if !InDelta( - t, - ev.Interface(), - av.Interface(), - delta, - msgAndArgs..., - ) { - return false - } - } - - return true -} - -func calcRelativeError(expected, actual interface{}) (float64, error) { - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - if !aok || !bok { - return 0, fmt.Errorf("Parameters must be numerical") - } - if math.IsNaN(af) && math.IsNaN(bf) { - return 0, nil - } - if math.IsNaN(af) { - return 0, errors.New("expected value must not be NaN") - } - if af == 0 { - return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") - } - if math.IsNaN(bf) { - return 0, errors.New("actual value must not be NaN") - } - - return math.Abs(af-bf) / math.Abs(af), nil -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if math.IsNaN(epsilon) { - return Fail(t, "epsilon must not be NaN") - } - actualEpsilon, err := calcRelativeError(expected, actual) - if err != nil { - return Fail(t, err.Error(), msgAndArgs...) - } - if actualEpsilon > epsilon { - return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ - " < %#v (actual)", epsilon, actualEpsilon), msgAndArgs...) - } - - return true -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, "Parameters must be slice", msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) - if !result { - return result - } - } - - return true -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if err != nil { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) - } - - return true -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) -// } -func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - if err == nil { - if h, ok := t.(tHelper); ok { - h.Helper() - } - return Fail(t, "An error is expected but got nil.", msgAndArgs...) - } - - return true -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if !Error(t, theError, msgAndArgs...) { - return false - } - expected := errString - actual := theError.Error() - // don't need to use deep equals here, we know they are both strings - if expected != actual { - return Fail(t, fmt.Sprintf("Error message not equal:\n"+ - "expected: %q\n"+ - "actual : %q", expected, actual), msgAndArgs...) - } - return true -} - -// ErrorContains asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// assert.ErrorContains(t, err, expectedErrorSubString) -func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if !Error(t, theError, msgAndArgs...) { - return false - } - - actual := theError.Error() - if !strings.Contains(actual, contains) { - return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...) - } - - return true -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - match := matchRegexp(rx, str) - - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } - - return match -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - match := matchRegexp(rx, str) - - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } - - return !match - -} - -// Zero asserts that i is the zero value for its type. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// NotZero asserts that i is not the zero value for its type. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// FileExists checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func FileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - info, err := os.Lstat(path) - if err != nil { - if os.IsNotExist(err) { - return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) - } - return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) - } - if info.IsDir() { - return Fail(t, fmt.Sprintf("%q is a directory", path), msgAndArgs...) - } - return true -} - -// NoFileExists checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - info, err := os.Lstat(path) - if err != nil { - return true - } - if info.IsDir() { - return true - } - return Fail(t, fmt.Sprintf("file %q exists", path), msgAndArgs...) -} - -// DirExists checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - info, err := os.Lstat(path) - if err != nil { - if os.IsNotExist(err) { - return Fail(t, fmt.Sprintf("unable to find file %q", path), msgAndArgs...) - } - return Fail(t, fmt.Sprintf("error when running os.Lstat(%q): %s", path, err), msgAndArgs...) - } - if !info.IsDir() { - return Fail(t, fmt.Sprintf("%q is a file", path), msgAndArgs...) - } - return true -} - -// NoDirExists checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - info, err := os.Lstat(path) - if err != nil { - if os.IsNotExist(err) { - return true - } - return true - } - if !info.IsDir() { - return true - } - return Fail(t, fmt.Sprintf("directory %q exists", path), msgAndArgs...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - var expectedJSONAsInterface, actualJSONAsInterface interface{} - - if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) - } - - if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) - } - - return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) -} - -// YAMLEq asserts that two YAML strings are equivalent. -func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - var expectedYAMLAsInterface, actualYAMLAsInterface interface{} - - if err := yaml.Unmarshal([]byte(expected), &expectedYAMLAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid yaml.\nYAML parsing error: '%s'", expected, err.Error()), msgAndArgs...) - } - - if err := yaml.Unmarshal([]byte(actual), &actualYAMLAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid yaml.\nYAML error: '%s'", actual, err.Error()), msgAndArgs...) - } - - return Equal(t, expectedYAMLAsInterface, actualYAMLAsInterface, msgAndArgs...) -} - -func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { - t := reflect.TypeOf(v) - k := t.Kind() - - if k == reflect.Ptr { - t = t.Elem() - k = t.Kind() - } - return t, k -} - -// diff returns a diff of both values as long as both are of the same type and -// are a struct, map, slice, array or string. Otherwise it returns an empty string. -func diff(expected interface{}, actual interface{}) string { - if expected == nil || actual == nil { - return "" - } - - et, ek := typeAndKind(expected) - at, _ := typeAndKind(actual) - - if et != at { - return "" - } - - if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array && ek != reflect.String { - return "" - } - - var e, a string - - switch et { - case reflect.TypeOf(""): - e = reflect.ValueOf(expected).String() - a = reflect.ValueOf(actual).String() - case reflect.TypeOf(time.Time{}): - e = spewConfigStringerEnabled.Sdump(expected) - a = spewConfigStringerEnabled.Sdump(actual) - default: - e = spewConfig.Sdump(expected) - a = spewConfig.Sdump(actual) - } - - diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: difflib.SplitLines(e), - B: difflib.SplitLines(a), - FromFile: "Expected", - FromDate: "", - ToFile: "Actual", - ToDate: "", - Context: 1, - }) - - return "\n\nDiff:\n" + diff -} - -func isFunction(arg interface{}) bool { - if arg == nil { - return false - } - return reflect.TypeOf(arg).Kind() == reflect.Func -} - -var spewConfig = spew.ConfigState{ - Indent: " ", - DisablePointerAddresses: true, - DisableCapacities: true, - SortKeys: true, - DisableMethods: true, - MaxDepth: 10, -} - -var spewConfigStringerEnabled = spew.ConfigState{ - Indent: " ", - DisablePointerAddresses: true, - DisableCapacities: true, - SortKeys: true, - MaxDepth: 10, -} - -type tHelper interface { - Helper() -} - -// Eventually asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) -func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - ch := make(chan bool, 1) - - timer := time.NewTimer(waitFor) - defer timer.Stop() - - ticker := time.NewTicker(tick) - defer ticker.Stop() - - for tick := ticker.C; ; { - select { - case <-timer.C: - return Fail(t, "Condition never satisfied", msgAndArgs...) - case <-tick: - tick = nil - go func() { ch <- condition() }() - case v := <-ch: - if v { - return true - } - tick = ticker.C - } - } -} - -// Never asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) -func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - - ch := make(chan bool, 1) - - timer := time.NewTimer(waitFor) - defer timer.Stop() - - ticker := time.NewTicker(tick) - defer ticker.Stop() - - for tick := ticker.C; ; { - select { - case <-timer.C: - return true - case <-tick: - tick = nil - go func() { ch <- condition() }() - case v := <-ch: - if v { - return Fail(t, "Condition satisfied", msgAndArgs...) - } - tick = ticker.C - } - } -} - -// ErrorIs asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if errors.Is(err, target) { - return true - } - - var expectedText string - if target != nil { - expectedText = target.Error() - } - - chain := buildErrorChainString(err) - - return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+ - "expected: %q\n"+ - "in chain: %s", expectedText, chain, - ), msgAndArgs...) -} - -// NotErrorIs asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if !errors.Is(err, target) { - return true - } - - var expectedText string - if target != nil { - expectedText = target.Error() - } - - chain := buildErrorChainString(err) - - return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+ - "found: %q\n"+ - "in chain: %s", expectedText, chain, - ), msgAndArgs...) -} - -// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if errors.As(err, target) { - return true - } - - chain := buildErrorChainString(err) - - return Fail(t, fmt.Sprintf("Should be in error chain:\n"+ - "expected: %q\n"+ - "in chain: %s", target, chain, - ), msgAndArgs...) -} - -func buildErrorChainString(err error) string { - if err == nil { - return "" - } - - e := errors.Unwrap(err) - chain := fmt.Sprintf("%q", err.Error()) - for e != nil { - chain += fmt.Sprintf("\n\t%q", e.Error()) - e = errors.Unwrap(e) - } - return chain -} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go deleted file mode 100644 index c9dccc4..0000000 --- a/vendor/github.com/stretchr/testify/assert/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the format below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go deleted file mode 100644 index ac9dc9d..0000000 --- a/vendor/github.com/stretchr/testify/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go deleted file mode 100644 index df189d2..0000000 --- a/vendor/github.com/stretchr/testify/assert/forward_assertions.go +++ /dev/null @@ -1,16 +0,0 @@ -package assert - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_forward.go.tmpl -include-format-funcs" diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go deleted file mode 100644 index 4ed341d..0000000 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ /dev/null @@ -1,162 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 and -// an error if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) (int, error) { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url, nil) - if err != nil { - return -1, err - } - req.URL.RawQuery = values.Encode() - handler(w, req) - return w.Code, nil -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - } - - isSuccessCode := code >= http.StatusOK && code <= http.StatusPartialContent - if !isSuccessCode { - Fail(t, fmt.Sprintf("Expected HTTP success status code for %q but received %d", url+"?"+values.Encode(), code)) - } - - return isSuccessCode -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - } - - isRedirectCode := code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect - if !isRedirectCode { - Fail(t, fmt.Sprintf("Expected HTTP redirect status code for %q but received %d", url+"?"+values.Encode(), code)) - } - - return isRedirectCode -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - } - - isErrorCode := code >= http.StatusBadRequest - if !isErrorCode { - Fail(t, fmt.Sprintf("Expected HTTP error status code for %q but received %d", url+"?"+values.Encode(), code)) - } - - return isErrorCode -} - -// HTTPStatusCode asserts that a specified handler returns a specified status code. -// -// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - code, err := httpCode(handler, method, url, values) - if err != nil { - Fail(t, fmt.Sprintf("Failed to build test request, got error: %s", err)) - } - - successful := code == statuscode - if !successful { - Fail(t, fmt.Sprintf("Expected HTTP status code %d for %q but received %d", statuscode, url+"?"+values.Encode(), code)) - } - - return successful -} - -// HTTPBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool { - if h, ok := t.(tHelper); ok { - h.Helper() - } - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return !contains -} diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go deleted file mode 100644 index 169de39..0000000 --- a/vendor/github.com/stretchr/testify/require/doc.go +++ /dev/null @@ -1,28 +0,0 @@ -// Package require implements the same assertions as the `assert` package but -// stops test execution when a test fails. -// -// Example Usage -// -// The following is a complete example using require in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/require" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// require.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// Assertions -// -// The `require` package have same global functions as in the `assert` package, -// but instead of returning a boolean result they call `t.FailNow()`. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package require diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go deleted file mode 100644 index 1dcb233..0000000 --- a/vendor/github.com/stretchr/testify/require/forward_requirements.go +++ /dev/null @@ -1,16 +0,0 @@ -package require - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require_forward.go.tmpl -include-format-funcs" diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go deleted file mode 100644 index 880853f..0000000 --- a/vendor/github.com/stretchr/testify/require/require.go +++ /dev/null @@ -1,1935 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package require - -import ( - assert "github.com/stretchr/testify/assert" - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Condition(t, comp, msgAndArgs...) { - return - } - t.FailNow() -} - -// Conditionf uses a Comparison to assert a complex condition. -func Conditionf(t TestingT, comp assert.Comparison, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Conditionf(t, comp, msg, args...) { - return - } - t.FailNow() -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World") -// assert.Contains(t, ["Hello", "World"], "World") -// assert.Contains(t, {"Hello": "World"}, "Hello") -func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Contains(t, s, contains, msgAndArgs...) { - return - } - t.FailNow() -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Containsf(t, "Hello World", "World", "error message %s", "formatted") -// assert.Containsf(t, ["Hello", "World"], "World", "error message %s", "formatted") -// assert.Containsf(t, {"Hello": "World"}, "Hello", "error message %s", "formatted") -func Containsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Containsf(t, s, contains, msg, args...) { - return - } - t.FailNow() -} - -// DirExists checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func DirExists(t TestingT, path string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.DirExists(t, path, msgAndArgs...) { - return - } - t.FailNow() -} - -// DirExistsf checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func DirExistsf(t TestingT, path string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.DirExistsf(t, path, msg, args...) { - return - } - t.FailNow() -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatch(t, [1, 3, 2, 3], [1, 3, 3, 2]) -func ElementsMatch(t TestingT, listA interface{}, listB interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ElementsMatch(t, listA, listB, msgAndArgs...) { - return - } - t.FailNow() -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// assert.ElementsMatchf(t, [1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func ElementsMatchf(t TestingT, listA interface{}, listB interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ElementsMatchf(t, listA, listB, msg, args...) { - return - } - t.FailNow() -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Empty(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Emptyf(t, obj, "error message %s", "formatted") -func Emptyf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Emptyf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Equal(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString) -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.EqualError(t, theError, errString, msgAndArgs...) { - return - } - t.FailNow() -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualErrorf(t, err, expectedErrorString, "error message %s", "formatted") -func EqualErrorf(t TestingT, theError error, errString string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.EqualErrorf(t, theError, errString, msg, args...) { - return - } - t.FailNow() -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123)) -func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.EqualValues(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValuesf(t, uint32(123), int32(123), "error message %s", "formatted") -func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.EqualValuesf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// Equalf asserts that two objects are equal. -// -// assert.Equalf(t, 123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Equalf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err) { -// assert.Equal(t, expectedError, err) -// } -func Error(t TestingT, err error, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Error(t, err, msgAndArgs...) { - return - } - t.FailNow() -} - -// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ErrorAs(t, err, target, msgAndArgs...) { - return - } - t.FailNow() -} - -// ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ErrorAsf(t, err, target, msg, args...) { - return - } - t.FailNow() -} - -// ErrorContains asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// assert.ErrorContains(t, err, expectedErrorSubString) -func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ErrorContains(t, theError, contains, msgAndArgs...) { - return - } - t.FailNow() -} - -// ErrorContainsf asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted") -func ErrorContainsf(t TestingT, theError error, contains string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ErrorContainsf(t, theError, contains, msg, args...) { - return - } - t.FailNow() -} - -// ErrorIs asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func ErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ErrorIs(t, err, target, msgAndArgs...) { - return - } - t.FailNow() -} - -// ErrorIsf asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func ErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.ErrorIsf(t, err, target, msg, args...) { - return - } - t.FailNow() -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Errorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func Errorf(t TestingT, err error, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Errorf(t, err, msg, args...) { - return - } - t.FailNow() -} - -// Eventually asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// assert.Eventually(t, func() bool { return true; }, time.Second, 10*time.Millisecond) -func Eventually(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Eventually(t, condition, waitFor, tick, msgAndArgs...) { - return - } - t.FailNow() -} - -// Eventuallyf asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// assert.Eventuallyf(t, func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Eventuallyf(t, condition, waitFor, tick, msg, args...) { - return - } - t.FailNow() -} - -// Exactly asserts that two objects are equal in value and type. -// -// assert.Exactly(t, int32(123), int64(123)) -func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Exactly(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// assert.Exactlyf(t, int32(123), int64(123), "error message %s", "formatted") -func Exactlyf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Exactlyf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Fail(t, failureMessage, msgAndArgs...) { - return - } - t.FailNow() -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.FailNow(t, failureMessage, msgAndArgs...) { - return - } - t.FailNow() -} - -// FailNowf fails test -func FailNowf(t TestingT, failureMessage string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.FailNowf(t, failureMessage, msg, args...) { - return - } - t.FailNow() -} - -// Failf reports a failure through -func Failf(t TestingT, failureMessage string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Failf(t, failureMessage, msg, args...) { - return - } - t.FailNow() -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool) -func False(t TestingT, value bool, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.False(t, value, msgAndArgs...) { - return - } - t.FailNow() -} - -// Falsef asserts that the specified value is false. -// -// assert.Falsef(t, myBool, "error message %s", "formatted") -func Falsef(t TestingT, value bool, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Falsef(t, value, msg, args...) { - return - } - t.FailNow() -} - -// FileExists checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func FileExists(t TestingT, path string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.FileExists(t, path, msgAndArgs...) { - return - } - t.FailNow() -} - -// FileExistsf checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func FileExistsf(t TestingT, path string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.FileExistsf(t, path, msg, args...) { - return - } - t.FailNow() -} - -// Greater asserts that the first element is greater than the second -// -// assert.Greater(t, 2, 1) -// assert.Greater(t, float64(2), float64(1)) -// assert.Greater(t, "b", "a") -func Greater(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Greater(t, e1, e2, msgAndArgs...) { - return - } - t.FailNow() -} - -// GreaterOrEqual asserts that the first element is greater than or equal to the second -// -// assert.GreaterOrEqual(t, 2, 1) -// assert.GreaterOrEqual(t, 2, 2) -// assert.GreaterOrEqual(t, "b", "a") -// assert.GreaterOrEqual(t, "b", "b") -func GreaterOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.GreaterOrEqual(t, e1, e2, msgAndArgs...) { - return - } - t.FailNow() -} - -// GreaterOrEqualf asserts that the first element is greater than or equal to the second -// -// assert.GreaterOrEqualf(t, 2, 1, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "a", "error message %s", "formatted") -// assert.GreaterOrEqualf(t, "b", "b", "error message %s", "formatted") -func GreaterOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.GreaterOrEqualf(t, e1, e2, msg, args...) { - return - } - t.FailNow() -} - -// Greaterf asserts that the first element is greater than the second -// -// assert.Greaterf(t, 2, 1, "error message %s", "formatted") -// assert.Greaterf(t, float64(2), float64(1), "error message %s", "formatted") -// assert.Greaterf(t, "b", "a", "error message %s", "formatted") -func Greaterf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Greaterf(t, e1, e2, msg, args...) { - return - } - t.FailNow() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPBodyContains(t, handler, method, url, values, str, msgAndArgs...) { - return - } - t.FailNow() -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPBodyContainsf(t, handler, method, url, values, str, msg, args...) { - return - } - t.FailNow() -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPBodyNotContains(t, handler, method, url, values, str, msgAndArgs...) { - return - } - t.FailNow() -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContainsf(t, myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContainsf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPBodyNotContainsf(t, handler, method, url, values, str, msg, args...) { - return - } - t.FailNow() -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPError(t, handler, method, url, values, msgAndArgs...) { - return - } - t.FailNow() -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// assert.HTTPErrorf(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPErrorf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPErrorf(t, handler, method, url, values, msg, args...) { - return - } - t.FailNow() -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPRedirect(t, handler, method, url, values, msgAndArgs...) { - return - } - t.FailNow() -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirectf(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirectf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPRedirectf(t, handler, method, url, values, msg, args...) { - return - } - t.FailNow() -} - -// HTTPStatusCode asserts that a specified handler returns a specified status code. -// -// assert.HTTPStatusCode(t, myHandler, "GET", "/notImplemented", nil, 501) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPStatusCode(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPStatusCode(t, handler, method, url, values, statuscode, msgAndArgs...) { - return - } - t.FailNow() -} - -// HTTPStatusCodef asserts that a specified handler returns a specified status code. -// -// assert.HTTPStatusCodef(t, myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPStatusCodef(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPStatusCodef(t, handler, method, url, values, statuscode, msg, args...) { - return - } - t.FailNow() -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPSuccess(t, handler, method, url, values, msgAndArgs...) { - return - } - t.FailNow() -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccessf(t, myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccessf(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.HTTPSuccessf(t, handler, method, url, values, msg, args...) { - return - } - t.FailNow() -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject)) -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Implements(t, interfaceObject, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// assert.Implementsf(t, (*MyInterface)(nil), new(MyObject), "error message %s", "formatted") -func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Implementsf(t, interfaceObject, object, msg, args...) { - return - } - t.FailNow() -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, 22/7.0, 0.01) -func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InDelta(t, expected, actual, delta, msgAndArgs...) { - return - } - t.FailNow() -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValues(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InDeltaMapValues(t, expected, actual, delta, msgAndArgs...) { - return - } - t.FailNow() -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func InDeltaMapValuesf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InDeltaMapValuesf(t, expected, actual, delta, msg, args...) { - return - } - t.FailNow() -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { - return - } - t.FailNow() -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InDeltaSlicef(t, expected, actual, delta, msg, args...) { - return - } - t.FailNow() -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted") -func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InDeltaf(t, expected, actual, delta, msg, args...) { - return - } - t.FailNow() -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { - return - } - t.FailNow() -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { - return - } - t.FailNow() -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlicef(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InEpsilonSlicef(t, expected, actual, epsilon, msg, args...) { - return - } - t.FailNow() -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func InEpsilonf(t TestingT, expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.InEpsilonf(t, expected, actual, epsilon, msg, args...) { - return - } - t.FailNow() -} - -// IsDecreasing asserts that the collection is decreasing -// -// assert.IsDecreasing(t, []int{2, 1, 0}) -// assert.IsDecreasing(t, []float{2, 1}) -// assert.IsDecreasing(t, []string{"b", "a"}) -func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsDecreasing(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// IsDecreasingf asserts that the collection is decreasing -// -// assert.IsDecreasingf(t, []int{2, 1, 0}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsDecreasingf(t, []string{"b", "a"}, "error message %s", "formatted") -func IsDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsDecreasingf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// IsIncreasing asserts that the collection is increasing -// -// assert.IsIncreasing(t, []int{1, 2, 3}) -// assert.IsIncreasing(t, []float{1, 2}) -// assert.IsIncreasing(t, []string{"a", "b"}) -func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsIncreasing(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// IsIncreasingf asserts that the collection is increasing -// -// assert.IsIncreasingf(t, []int{1, 2, 3}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsIncreasingf(t, []string{"a", "b"}, "error message %s", "formatted") -func IsIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsIncreasingf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// IsNonDecreasing asserts that the collection is not decreasing -// -// assert.IsNonDecreasing(t, []int{1, 1, 2}) -// assert.IsNonDecreasing(t, []float{1, 2}) -// assert.IsNonDecreasing(t, []string{"a", "b"}) -func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsNonDecreasing(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// IsNonDecreasingf asserts that the collection is not decreasing -// -// assert.IsNonDecreasingf(t, []int{1, 1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []float{1, 2}, "error message %s", "formatted") -// assert.IsNonDecreasingf(t, []string{"a", "b"}, "error message %s", "formatted") -func IsNonDecreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsNonDecreasingf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// IsNonIncreasing asserts that the collection is not increasing -// -// assert.IsNonIncreasing(t, []int{2, 1, 1}) -// assert.IsNonIncreasing(t, []float{2, 1}) -// assert.IsNonIncreasing(t, []string{"b", "a"}) -func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsNonIncreasing(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// IsNonIncreasingf asserts that the collection is not increasing -// -// assert.IsNonIncreasingf(t, []int{2, 1, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []float{2, 1}, "error message %s", "formatted") -// assert.IsNonIncreasingf(t, []string{"b", "a"}, "error message %s", "formatted") -func IsNonIncreasingf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsNonIncreasingf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsType(t, expectedType, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// IsTypef asserts that the specified objects are of the same type. -func IsTypef(t TestingT, expectedType interface{}, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.IsTypef(t, expectedType, object, msg, args...) { - return - } - t.FailNow() -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.JSONEq(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// assert.JSONEqf(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func JSONEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.JSONEqf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3) -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Len(t, object, length, msgAndArgs...) { - return - } - t.FailNow() -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// assert.Lenf(t, mySlice, 3, "error message %s", "formatted") -func Lenf(t TestingT, object interface{}, length int, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Lenf(t, object, length, msg, args...) { - return - } - t.FailNow() -} - -// Less asserts that the first element is less than the second -// -// assert.Less(t, 1, 2) -// assert.Less(t, float64(1), float64(2)) -// assert.Less(t, "a", "b") -func Less(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Less(t, e1, e2, msgAndArgs...) { - return - } - t.FailNow() -} - -// LessOrEqual asserts that the first element is less than or equal to the second -// -// assert.LessOrEqual(t, 1, 2) -// assert.LessOrEqual(t, 2, 2) -// assert.LessOrEqual(t, "a", "b") -// assert.LessOrEqual(t, "b", "b") -func LessOrEqual(t TestingT, e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.LessOrEqual(t, e1, e2, msgAndArgs...) { - return - } - t.FailNow() -} - -// LessOrEqualf asserts that the first element is less than or equal to the second -// -// assert.LessOrEqualf(t, 1, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, 2, 2, "error message %s", "formatted") -// assert.LessOrEqualf(t, "a", "b", "error message %s", "formatted") -// assert.LessOrEqualf(t, "b", "b", "error message %s", "formatted") -func LessOrEqualf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.LessOrEqualf(t, e1, e2, msg, args...) { - return - } - t.FailNow() -} - -// Lessf asserts that the first element is less than the second -// -// assert.Lessf(t, 1, 2, "error message %s", "formatted") -// assert.Lessf(t, float64(1), float64(2), "error message %s", "formatted") -// assert.Lessf(t, "a", "b", "error message %s", "formatted") -func Lessf(t TestingT, e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Lessf(t, e1, e2, msg, args...) { - return - } - t.FailNow() -} - -// Negative asserts that the specified element is negative -// -// assert.Negative(t, -1) -// assert.Negative(t, -1.23) -func Negative(t TestingT, e interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Negative(t, e, msgAndArgs...) { - return - } - t.FailNow() -} - -// Negativef asserts that the specified element is negative -// -// assert.Negativef(t, -1, "error message %s", "formatted") -// assert.Negativef(t, -1.23, "error message %s", "formatted") -func Negativef(t TestingT, e interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Negativef(t, e, msg, args...) { - return - } - t.FailNow() -} - -// Never asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// assert.Never(t, func() bool { return false; }, time.Second, 10*time.Millisecond) -func Never(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Never(t, condition, waitFor, tick, msgAndArgs...) { - return - } - t.FailNow() -} - -// Neverf asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// assert.Neverf(t, func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func Neverf(t TestingT, condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Neverf(t, condition, waitFor, tick, msg, args...) { - return - } - t.FailNow() -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err) -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Nil(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// Nilf asserts that the specified object is nil. -// -// assert.Nilf(t, err, "error message %s", "formatted") -func Nilf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Nilf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// NoDirExists checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func NoDirExists(t TestingT, path string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NoDirExists(t, path, msgAndArgs...) { - return - } - t.FailNow() -} - -// NoDirExistsf checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NoDirExistsf(t, path, msg, args...) { - return - } - t.FailNow() -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoError(t TestingT, err error, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NoError(t, err, msgAndArgs...) { - return - } - t.FailNow() -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoErrorf(t, err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func NoErrorf(t TestingT, err error, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NoErrorf(t, err, msg, args...) { - return - } - t.FailNow() -} - -// NoFileExists checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func NoFileExists(t TestingT, path string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NoFileExists(t, path, msgAndArgs...) { - return - } - t.FailNow() -} - -// NoFileExistsf checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func NoFileExistsf(t TestingT, path string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NoFileExistsf(t, path, msg, args...) { - return - } - t.FailNow() -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth") -// assert.NotContains(t, ["Hello", "World"], "Earth") -// assert.NotContains(t, {"Hello": "World"}, "Earth") -func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotContains(t, s, contains, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContainsf(t, "Hello World", "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, ["Hello", "World"], "Earth", "error message %s", "formatted") -// assert.NotContainsf(t, {"Hello": "World"}, "Earth", "error message %s", "formatted") -func NotContainsf(t TestingT, s interface{}, contains interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotContainsf(t, s, contains, msg, args...) { - return - } - t.FailNow() -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotEmpty(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmptyf(t, obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func NotEmptyf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotEmptyf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotEqual(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotEqualValues asserts that two objects are not equal even when converted to the same type -// -// assert.NotEqualValues(t, obj1, obj2) -func NotEqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotEqualValues(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotEqualValuesf asserts that two objects are not equal even when converted to the same type -// -// assert.NotEqualValuesf(t, obj1, obj2, "error message %s", "formatted") -func NotEqualValuesf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotEqualValuesf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// assert.NotEqualf(t, obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqualf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotEqualf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// NotErrorIs asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func NotErrorIs(t TestingT, err error, target error, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotErrorIs(t, err, target, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotErrorIsf asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func NotErrorIsf(t TestingT, err error, target error, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotErrorIsf(t, err, target, msg, args...) { - return - } - t.FailNow() -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err) -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotNil(t, object, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotNilf asserts that the specified object is not nil. -// -// assert.NotNilf(t, err, "error message %s", "formatted") -func NotNilf(t TestingT, object interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotNilf(t, object, msg, args...) { - return - } - t.FailNow() -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ RemainCalm() }) -func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotPanics(t, f, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanicsf(t, func(){ RemainCalm() }, "error message %s", "formatted") -func NotPanicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotPanicsf(t, f, msg, args...) { - return - } - t.FailNow() -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotRegexp(t, rx, str, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// assert.NotRegexpf(t, regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// assert.NotRegexpf(t, "^start", "it's not starting", "error message %s", "formatted") -func NotRegexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotRegexpf(t, rx, str, msg, args...) { - return - } - t.FailNow() -} - -// NotSame asserts that two pointers do not reference the same object. -// -// assert.NotSame(t, ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func NotSame(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotSame(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotSamef asserts that two pointers do not reference the same object. -// -// assert.NotSamef(t, ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func NotSamef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotSamef(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubset(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func NotSubset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotSubset(t, list, subset, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// assert.NotSubsetf(t, [1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func NotSubsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotSubsetf(t, list, subset, msg, args...) { - return - } - t.FailNow() -} - -// NotZero asserts that i is not the zero value for its type. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotZero(t, i, msgAndArgs...) { - return - } - t.FailNow() -} - -// NotZerof asserts that i is not the zero value for its type. -func NotZerof(t TestingT, i interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.NotZerof(t, i, msg, args...) { - return - } - t.FailNow() -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ GoCrazy() }) -func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Panics(t, f, msgAndArgs...) { - return - } - t.FailNow() -} - -// PanicsWithError asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// assert.PanicsWithError(t, "crazy error", func(){ GoCrazy() }) -func PanicsWithError(t TestingT, errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.PanicsWithError(t, errString, f, msgAndArgs...) { - return - } - t.FailNow() -} - -// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// assert.PanicsWithErrorf(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func PanicsWithErrorf(t TestingT, errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.PanicsWithErrorf(t, errString, f, msg, args...) { - return - } - t.FailNow() -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValue(t, "crazy error", func(){ GoCrazy() }) -func PanicsWithValue(t TestingT, expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.PanicsWithValue(t, expected, f, msgAndArgs...) { - return - } - t.FailNow() -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// assert.PanicsWithValuef(t, "crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func PanicsWithValuef(t TestingT, expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.PanicsWithValuef(t, expected, f, msg, args...) { - return - } - t.FailNow() -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panicsf(t, func(){ GoCrazy() }, "error message %s", "formatted") -func Panicsf(t TestingT, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Panicsf(t, f, msg, args...) { - return - } - t.FailNow() -} - -// Positive asserts that the specified element is positive -// -// assert.Positive(t, 1) -// assert.Positive(t, 1.23) -func Positive(t TestingT, e interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Positive(t, e, msgAndArgs...) { - return - } - t.FailNow() -} - -// Positivef asserts that the specified element is positive -// -// assert.Positivef(t, 1, "error message %s", "formatted") -// assert.Positivef(t, 1.23, "error message %s", "formatted") -func Positivef(t TestingT, e interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Positivef(t, e, msg, args...) { - return - } - t.FailNow() -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Regexp(t, rx, str, msgAndArgs...) { - return - } - t.FailNow() -} - -// Regexpf asserts that a specified regexp matches a string. -// -// assert.Regexpf(t, regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// assert.Regexpf(t, "start...$", "it's not starting", "error message %s", "formatted") -func Regexpf(t TestingT, rx interface{}, str interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Regexpf(t, rx, str, msg, args...) { - return - } - t.FailNow() -} - -// Same asserts that two pointers reference the same object. -// -// assert.Same(t, ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func Same(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Same(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// Samef asserts that two pointers reference the same object. -// -// assert.Samef(t, ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func Samef(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Samef(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subset(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func Subset(t TestingT, list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Subset(t, list, subset, msgAndArgs...) { - return - } - t.FailNow() -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// assert.Subsetf(t, [1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func Subsetf(t TestingT, list interface{}, subset interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Subsetf(t, list, subset, msg, args...) { - return - } - t.FailNow() -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool) -func True(t TestingT, value bool, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.True(t, value, msgAndArgs...) { - return - } - t.FailNow() -} - -// Truef asserts that the specified value is true. -// -// assert.Truef(t, myBool, "error message %s", "formatted") -func Truef(t TestingT, value bool, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Truef(t, value, msg, args...) { - return - } - t.FailNow() -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second) -func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { - return - } - t.FailNow() -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// assert.WithinDurationf(t, time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func WithinDurationf(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.WithinDurationf(t, expected, actual, delta, msg, args...) { - return - } - t.FailNow() -} - -// WithinRange asserts that a time is within a time range (inclusive). -// -// assert.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) -func WithinRange(t TestingT, actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.WithinRange(t, actual, start, end, msgAndArgs...) { - return - } - t.FailNow() -} - -// WithinRangef asserts that a time is within a time range (inclusive). -// -// assert.WithinRangef(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") -func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.WithinRangef(t, actual, start, end, msg, args...) { - return - } - t.FailNow() -} - -// YAMLEq asserts that two YAML strings are equivalent. -func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.YAMLEq(t, expected, actual, msgAndArgs...) { - return - } - t.FailNow() -} - -// YAMLEqf asserts that two YAML strings are equivalent. -func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.YAMLEqf(t, expected, actual, msg, args...) { - return - } - t.FailNow() -} - -// Zero asserts that i is the zero value for its type. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Zero(t, i, msgAndArgs...) { - return - } - t.FailNow() -} - -// Zerof asserts that i is the zero value for its type. -func Zerof(t TestingT, i interface{}, msg string, args ...interface{}) { - if h, ok := t.(tHelper); ok { - h.Helper() - } - if assert.Zerof(t, i, msg, args...) { - return - } - t.FailNow() -} diff --git a/vendor/github.com/stretchr/testify/require/require.go.tmpl b/vendor/github.com/stretchr/testify/require/require.go.tmpl deleted file mode 100644 index 55e42dd..0000000 --- a/vendor/github.com/stretchr/testify/require/require.go.tmpl +++ /dev/null @@ -1,6 +0,0 @@ -{{.Comment}} -func {{.DocInfo.Name}}(t TestingT, {{.Params}}) { - if h, ok := t.(tHelper); ok { h.Helper() } - if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return } - t.FailNow() -} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go deleted file mode 100644 index 960bf6f..0000000 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ /dev/null @@ -1,1515 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package require - -import ( - assert "github.com/stretchr/testify/assert" - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Condition(a.t, comp, msgAndArgs...) -} - -// Conditionf uses a Comparison to assert a complex condition. -func (a *Assertions) Conditionf(comp assert.Comparison, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Conditionf(a.t, comp, msg, args...) -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World") -// a.Contains(["Hello", "World"], "World") -// a.Contains({"Hello": "World"}, "Hello") -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Contains(a.t, s, contains, msgAndArgs...) -} - -// Containsf asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Containsf("Hello World", "World", "error message %s", "formatted") -// a.Containsf(["Hello", "World"], "World", "error message %s", "formatted") -// a.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted") -func (a *Assertions) Containsf(s interface{}, contains interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Containsf(a.t, s, contains, msg, args...) -} - -// DirExists checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExists(path string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - DirExists(a.t, path, msgAndArgs...) -} - -// DirExistsf checks whether a directory exists in the given path. It also fails -// if the path is a file rather a directory or there is an error checking whether it exists. -func (a *Assertions) DirExistsf(path string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - DirExistsf(a.t, path, msg, args...) -} - -// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2]) -func (a *Assertions) ElementsMatch(listA interface{}, listB interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ElementsMatch(a.t, listA, listB, msgAndArgs...) -} - -// ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified -// listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, -// the number of appearances of each of them in both lists should match. -// -// a.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted") -func (a *Assertions) ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ElementsMatchf(a.t, listA, listB, msg, args...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Empty(a.t, object, msgAndArgs...) -} - -// Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Emptyf(obj, "error message %s", "formatted") -func (a *Assertions) Emptyf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Emptyf(a.t, object, msg, args...) -} - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString) -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualError(a.t, theError, errString, msgAndArgs...) -} - -// EqualErrorf asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualErrorf(err, expectedErrorString, "error message %s", "formatted") -func (a *Assertions) EqualErrorf(theError error, errString string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualErrorf(a.t, theError, errString, msg, args...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123)) -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// EqualValuesf asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted") -func (a *Assertions) EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - EqualValuesf(a.t, expected, actual, msg, args...) -} - -// Equalf asserts that two objects are equal. -// -// a.Equalf(123, 123, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). Function equality -// cannot be determined and will always fail. -func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Equalf(a.t, expected, actual, msg, args...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err) { -// assert.Equal(t, expectedError, err) -// } -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Error(a.t, err, msgAndArgs...) -} - -// ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func (a *Assertions) ErrorAs(err error, target interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ErrorAs(a.t, err, target, msgAndArgs...) -} - -// ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. -// This is a wrapper for errors.As. -func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ErrorAsf(a.t, err, target, msg, args...) -} - -// ErrorContains asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// a.ErrorContains(err, expectedErrorSubString) -func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ErrorContains(a.t, theError, contains, msgAndArgs...) -} - -// ErrorContainsf asserts that a function returned an error (i.e. not `nil`) -// and that the error contains the specified substring. -// -// actualObj, err := SomeFunction() -// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted") -func (a *Assertions) ErrorContainsf(theError error, contains string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ErrorContainsf(a.t, theError, contains, msg, args...) -} - -// ErrorIs asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) ErrorIs(err error, target error, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ErrorIs(a.t, err, target, msgAndArgs...) -} - -// ErrorIsf asserts that at least one of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - ErrorIsf(a.t, err, target, msg, args...) -} - -// Errorf asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Errorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedErrorf, err) -// } -func (a *Assertions) Errorf(err error, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Errorf(a.t, err, msg, args...) -} - -// Eventually asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// a.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond) -func (a *Assertions) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Eventually(a.t, condition, waitFor, tick, msgAndArgs...) -} - -// Eventuallyf asserts that given condition will be met in waitFor time, -// periodically checking target function each tick. -// -// a.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func (a *Assertions) Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Eventuallyf(a.t, condition, waitFor, tick, msg, args...) -} - -// Exactly asserts that two objects are equal in value and type. -// -// a.Exactly(int32(123), int64(123)) -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Exactly(a.t, expected, actual, msgAndArgs...) -} - -// Exactlyf asserts that two objects are equal in value and type. -// -// a.Exactlyf(int32(123), int64(123), "error message %s", "formatted") -func (a *Assertions) Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Exactlyf(a.t, expected, actual, msg, args...) -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Fail(a.t, failureMessage, msgAndArgs...) -} - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FailNow(a.t, failureMessage, msgAndArgs...) -} - -// FailNowf fails test -func (a *Assertions) FailNowf(failureMessage string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FailNowf(a.t, failureMessage, msg, args...) -} - -// Failf reports a failure through -func (a *Assertions) Failf(failureMessage string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Failf(a.t, failureMessage, msg, args...) -} - -// False asserts that the specified value is false. -// -// a.False(myBool) -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - False(a.t, value, msgAndArgs...) -} - -// Falsef asserts that the specified value is false. -// -// a.Falsef(myBool, "error message %s", "formatted") -func (a *Assertions) Falsef(value bool, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Falsef(a.t, value, msg, args...) -} - -// FileExists checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExists(path string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FileExists(a.t, path, msgAndArgs...) -} - -// FileExistsf checks whether a file exists in the given path. It also fails if -// the path points to a directory or there is an error when trying to check the file. -func (a *Assertions) FileExistsf(path string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - FileExistsf(a.t, path, msg, args...) -} - -// Greater asserts that the first element is greater than the second -// -// a.Greater(2, 1) -// a.Greater(float64(2), float64(1)) -// a.Greater("b", "a") -func (a *Assertions) Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Greater(a.t, e1, e2, msgAndArgs...) -} - -// GreaterOrEqual asserts that the first element is greater than or equal to the second -// -// a.GreaterOrEqual(2, 1) -// a.GreaterOrEqual(2, 2) -// a.GreaterOrEqual("b", "a") -// a.GreaterOrEqual("b", "b") -func (a *Assertions) GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - GreaterOrEqual(a.t, e1, e2, msgAndArgs...) -} - -// GreaterOrEqualf asserts that the first element is greater than or equal to the second -// -// a.GreaterOrEqualf(2, 1, "error message %s", "formatted") -// a.GreaterOrEqualf(2, 2, "error message %s", "formatted") -// a.GreaterOrEqualf("b", "a", "error message %s", "formatted") -// a.GreaterOrEqualf("b", "b", "error message %s", "formatted") -func (a *Assertions) GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - GreaterOrEqualf(a.t, e1, e2, msg, args...) -} - -// Greaterf asserts that the first element is greater than the second -// -// a.Greaterf(2, 1, "error message %s", "formatted") -// a.Greaterf(float64(2), float64(1), "error message %s", "formatted") -// a.Greaterf("b", "a", "error message %s", "formatted") -func (a *Assertions) Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Greaterf(a.t, e1, e2, msg, args...) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyContainsf asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyNotContains(a.t, handler, method, url, values, str, msgAndArgs...) -} - -// HTTPBodyNotContainsf asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPBodyNotContainsf(a.t, handler, method, url, values, str, msg, args...) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPError(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPErrorf asserts that a specified handler returns an error status code. -// -// a.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPErrorf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPRedirect(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPRedirectf asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPRedirectf(a.t, handler, method, url, values, msg, args...) -} - -// HTTPStatusCode asserts that a specified handler returns a specified status code. -// -// a.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPStatusCode(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPStatusCode(a.t, handler, method, url, values, statuscode, msgAndArgs...) -} - -// HTTPStatusCodef asserts that a specified handler returns a specified status code. -// -// a.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPStatusCodef(a.t, handler, method, url, values, statuscode, msg, args...) -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPSuccess(a.t, handler, method, url, values, msgAndArgs...) -} - -// HTTPSuccessf asserts that a specified handler returns a success status code. -// -// a.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - HTTPSuccessf(a.t, handler, method, url, values, msg, args...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject)) -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// Implementsf asserts that an object is implemented by the specified interface. -// -// a.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted") -func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Implementsf(a.t, interfaceObject, object, msg, args...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, 22/7.0, 0.01) -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValues(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaMapValues(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys. -func (a *Assertions) InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaMapValuesf(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaSlicef is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaSlicef(a.t, expected, actual, delta, msg, args...) -} - -// InDeltaf asserts that the two numerals are within delta of each other. -// -// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted") -func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InDeltaf(a.t, expected, actual, delta, msg, args...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilonSlicef(a.t, expected, actual, epsilon, msg, args...) -} - -// InEpsilonf asserts that expected and actual have a relative error less than epsilon -func (a *Assertions) InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - InEpsilonf(a.t, expected, actual, epsilon, msg, args...) -} - -// IsDecreasing asserts that the collection is decreasing -// -// a.IsDecreasing([]int{2, 1, 0}) -// a.IsDecreasing([]float{2, 1}) -// a.IsDecreasing([]string{"b", "a"}) -func (a *Assertions) IsDecreasing(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsDecreasing(a.t, object, msgAndArgs...) -} - -// IsDecreasingf asserts that the collection is decreasing -// -// a.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted") -// a.IsDecreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted") -func (a *Assertions) IsDecreasingf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsDecreasingf(a.t, object, msg, args...) -} - -// IsIncreasing asserts that the collection is increasing -// -// a.IsIncreasing([]int{1, 2, 3}) -// a.IsIncreasing([]float{1, 2}) -// a.IsIncreasing([]string{"a", "b"}) -func (a *Assertions) IsIncreasing(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsIncreasing(a.t, object, msgAndArgs...) -} - -// IsIncreasingf asserts that the collection is increasing -// -// a.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted") -// a.IsIncreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted") -func (a *Assertions) IsIncreasingf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsIncreasingf(a.t, object, msg, args...) -} - -// IsNonDecreasing asserts that the collection is not decreasing -// -// a.IsNonDecreasing([]int{1, 1, 2}) -// a.IsNonDecreasing([]float{1, 2}) -// a.IsNonDecreasing([]string{"a", "b"}) -func (a *Assertions) IsNonDecreasing(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsNonDecreasing(a.t, object, msgAndArgs...) -} - -// IsNonDecreasingf asserts that the collection is not decreasing -// -// a.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted") -// a.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted") -func (a *Assertions) IsNonDecreasingf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsNonDecreasingf(a.t, object, msg, args...) -} - -// IsNonIncreasing asserts that the collection is not increasing -// -// a.IsNonIncreasing([]int{2, 1, 1}) -// a.IsNonIncreasing([]float{2, 1}) -// a.IsNonIncreasing([]string{"b", "a"}) -func (a *Assertions) IsNonIncreasing(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsNonIncreasing(a.t, object, msgAndArgs...) -} - -// IsNonIncreasingf asserts that the collection is not increasing -// -// a.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted") -// a.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted") -func (a *Assertions) IsNonIncreasingf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsNonIncreasingf(a.t, object, msg, args...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsType(a.t, expectedType, object, msgAndArgs...) -} - -// IsTypef asserts that the specified objects are of the same type. -func (a *Assertions) IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - IsTypef(a.t, expectedType, object, msg, args...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - JSONEq(a.t, expected, actual, msgAndArgs...) -} - -// JSONEqf asserts that two JSON strings are equivalent. -// -// a.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted") -func (a *Assertions) JSONEqf(expected string, actual string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - JSONEqf(a.t, expected, actual, msg, args...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3) -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Len(a.t, object, length, msgAndArgs...) -} - -// Lenf asserts that the specified object has specific length. -// Lenf also fails if the object has a type that len() not accept. -// -// a.Lenf(mySlice, 3, "error message %s", "formatted") -func (a *Assertions) Lenf(object interface{}, length int, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Lenf(a.t, object, length, msg, args...) -} - -// Less asserts that the first element is less than the second -// -// a.Less(1, 2) -// a.Less(float64(1), float64(2)) -// a.Less("a", "b") -func (a *Assertions) Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Less(a.t, e1, e2, msgAndArgs...) -} - -// LessOrEqual asserts that the first element is less than or equal to the second -// -// a.LessOrEqual(1, 2) -// a.LessOrEqual(2, 2) -// a.LessOrEqual("a", "b") -// a.LessOrEqual("b", "b") -func (a *Assertions) LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - LessOrEqual(a.t, e1, e2, msgAndArgs...) -} - -// LessOrEqualf asserts that the first element is less than or equal to the second -// -// a.LessOrEqualf(1, 2, "error message %s", "formatted") -// a.LessOrEqualf(2, 2, "error message %s", "formatted") -// a.LessOrEqualf("a", "b", "error message %s", "formatted") -// a.LessOrEqualf("b", "b", "error message %s", "formatted") -func (a *Assertions) LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - LessOrEqualf(a.t, e1, e2, msg, args...) -} - -// Lessf asserts that the first element is less than the second -// -// a.Lessf(1, 2, "error message %s", "formatted") -// a.Lessf(float64(1), float64(2), "error message %s", "formatted") -// a.Lessf("a", "b", "error message %s", "formatted") -func (a *Assertions) Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Lessf(a.t, e1, e2, msg, args...) -} - -// Negative asserts that the specified element is negative -// -// a.Negative(-1) -// a.Negative(-1.23) -func (a *Assertions) Negative(e interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Negative(a.t, e, msgAndArgs...) -} - -// Negativef asserts that the specified element is negative -// -// a.Negativef(-1, "error message %s", "formatted") -// a.Negativef(-1.23, "error message %s", "formatted") -func (a *Assertions) Negativef(e interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Negativef(a.t, e, msg, args...) -} - -// Never asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// a.Never(func() bool { return false; }, time.Second, 10*time.Millisecond) -func (a *Assertions) Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Never(a.t, condition, waitFor, tick, msgAndArgs...) -} - -// Neverf asserts that the given condition doesn't satisfy in waitFor time, -// periodically checking the target function each tick. -// -// a.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted") -func (a *Assertions) Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Neverf(a.t, condition, waitFor, tick, msg, args...) -} - -// Nil asserts that the specified object is nil. -// -// a.Nil(err) -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Nil(a.t, object, msgAndArgs...) -} - -// Nilf asserts that the specified object is nil. -// -// a.Nilf(err, "error message %s", "formatted") -func (a *Assertions) Nilf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Nilf(a.t, object, msg, args...) -} - -// NoDirExists checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func (a *Assertions) NoDirExists(path string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoDirExists(a.t, path, msgAndArgs...) -} - -// NoDirExistsf checks whether a directory does not exist in the given path. -// It fails if the path points to an existing _directory_ only. -func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoDirExistsf(a.t, path, msg, args...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoError(a.t, err, msgAndArgs...) -} - -// NoErrorf asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoErrorf(err, "error message %s", "formatted") { -// assert.Equal(t, expectedObj, actualObj) -// } -func (a *Assertions) NoErrorf(err error, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoErrorf(a.t, err, msg, args...) -} - -// NoFileExists checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func (a *Assertions) NoFileExists(path string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoFileExists(a.t, path, msgAndArgs...) -} - -// NoFileExistsf checks whether a file does not exist in a given path. It fails -// if the path points to an existing _file_ only. -func (a *Assertions) NoFileExistsf(path string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NoFileExistsf(a.t, path, msg, args...) -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth") -// a.NotContains(["Hello", "World"], "Earth") -// a.NotContains({"Hello": "World"}, "Earth") -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotContains(a.t, s, contains, msgAndArgs...) -} - -// NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContainsf("Hello World", "Earth", "error message %s", "formatted") -// a.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted") -// a.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted") -func (a *Assertions) NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotContainsf(a.t, s, contains, msg, args...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEmpty(a.t, object, msgAndArgs...) -} - -// NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmptyf(obj, "error message %s", "formatted") { -// assert.Equal(t, "two", obj[1]) -// } -func (a *Assertions) NotEmptyf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEmptyf(a.t, object, msg, args...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2) -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// NotEqualValues asserts that two objects are not equal even when converted to the same type -// -// a.NotEqualValues(obj1, obj2) -func (a *Assertions) NotEqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEqualValues(a.t, expected, actual, msgAndArgs...) -} - -// NotEqualValuesf asserts that two objects are not equal even when converted to the same type -// -// a.NotEqualValuesf(obj1, obj2, "error message %s", "formatted") -func (a *Assertions) NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEqualValuesf(a.t, expected, actual, msg, args...) -} - -// NotEqualf asserts that the specified values are NOT equal. -// -// a.NotEqualf(obj1, obj2, "error message %s", "formatted") -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotEqualf(a.t, expected, actual, msg, args...) -} - -// NotErrorIs asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) NotErrorIs(err error, target error, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotErrorIs(a.t, err, target, msgAndArgs...) -} - -// NotErrorIsf asserts that at none of the errors in err's chain matches target. -// This is a wrapper for errors.Is. -func (a *Assertions) NotErrorIsf(err error, target error, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotErrorIsf(a.t, err, target, msg, args...) -} - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err) -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotNil(a.t, object, msgAndArgs...) -} - -// NotNilf asserts that the specified object is not nil. -// -// a.NotNilf(err, "error message %s", "formatted") -func (a *Assertions) NotNilf(object interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotNilf(a.t, object, msg, args...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ RemainCalm() }) -func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotPanics(a.t, f, msgAndArgs...) -} - -// NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted") -func (a *Assertions) NotPanicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotPanicsf(a.t, f, msg, args...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexpf asserts that a specified regexp does not match a string. -// -// a.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted") -// a.NotRegexpf("^start", "it's not starting", "error message %s", "formatted") -func (a *Assertions) NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotRegexpf(a.t, rx, str, msg, args...) -} - -// NotSame asserts that two pointers do not reference the same object. -// -// a.NotSame(ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) NotSame(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotSame(a.t, expected, actual, msgAndArgs...) -} - -// NotSamef asserts that two pointers do not reference the same object. -// -// a.NotSamef(ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotSamef(a.t, expected, actual, msg, args...) -} - -// NotSubset asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubset([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]") -func (a *Assertions) NotSubset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotSubset(a.t, list, subset, msgAndArgs...) -} - -// NotSubsetf asserts that the specified list(array, slice...) contains not all -// elements given in the specified subset(array, slice...). -// -// a.NotSubsetf([1, 3, 4], [1, 2], "But [1, 3, 4] does not contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotSubsetf(a.t, list, subset, msg, args...) -} - -// NotZero asserts that i is not the zero value for its type. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotZero(a.t, i, msgAndArgs...) -} - -// NotZerof asserts that i is not the zero value for its type. -func (a *Assertions) NotZerof(i interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - NotZerof(a.t, i, msg, args...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ GoCrazy() }) -func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Panics(a.t, f, msgAndArgs...) -} - -// PanicsWithError asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// a.PanicsWithError("crazy error", func(){ GoCrazy() }) -func (a *Assertions) PanicsWithError(errString string, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - PanicsWithError(a.t, errString, f, msgAndArgs...) -} - -// PanicsWithErrorf asserts that the code inside the specified PanicTestFunc -// panics, and that the recovered panic value is an error that satisfies the -// EqualError comparison. -// -// a.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) PanicsWithErrorf(errString string, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - PanicsWithErrorf(a.t, errString, f, msg, args...) -} - -// PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValue("crazy error", func(){ GoCrazy() }) -func (a *Assertions) PanicsWithValue(expected interface{}, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - PanicsWithValue(a.t, expected, f, msgAndArgs...) -} - -// PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that -// the recovered panic value equals the expected panic value. -// -// a.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) PanicsWithValuef(expected interface{}, f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - PanicsWithValuef(a.t, expected, f, msg, args...) -} - -// Panicsf asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted") -func (a *Assertions) Panicsf(f assert.PanicTestFunc, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Panicsf(a.t, f, msg, args...) -} - -// Positive asserts that the specified element is positive -// -// a.Positive(1) -// a.Positive(1.23) -func (a *Assertions) Positive(e interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Positive(a.t, e, msgAndArgs...) -} - -// Positivef asserts that the specified element is positive -// -// a.Positivef(1, "error message %s", "formatted") -// a.Positivef(1.23, "error message %s", "formatted") -func (a *Assertions) Positivef(e interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Positivef(a.t, e, msg, args...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Regexp(a.t, rx, str, msgAndArgs...) -} - -// Regexpf asserts that a specified regexp matches a string. -// -// a.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted") -// a.Regexpf("start...$", "it's not starting", "error message %s", "formatted") -func (a *Assertions) Regexpf(rx interface{}, str interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Regexpf(a.t, rx, str, msg, args...) -} - -// Same asserts that two pointers reference the same object. -// -// a.Same(ptr1, ptr2) -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) Same(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Same(a.t, expected, actual, msgAndArgs...) -} - -// Samef asserts that two pointers reference the same object. -// -// a.Samef(ptr1, ptr2, "error message %s", "formatted") -// -// Both arguments must be pointer variables. Pointer variable sameness is -// determined based on the equality of both type and value. -func (a *Assertions) Samef(expected interface{}, actual interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Samef(a.t, expected, actual, msg, args...) -} - -// Subset asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subset([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]") -func (a *Assertions) Subset(list interface{}, subset interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Subset(a.t, list, subset, msgAndArgs...) -} - -// Subsetf asserts that the specified list(array, slice...) contains all -// elements given in the specified subset(array, slice...). -// -// a.Subsetf([1, 2, 3], [1, 2], "But [1, 2, 3] does contain [1, 2]", "error message %s", "formatted") -func (a *Assertions) Subsetf(list interface{}, subset interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Subsetf(a.t, list, subset, msg, args...) -} - -// True asserts that the specified value is true. -// -// a.True(myBool) -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - True(a.t, value, msgAndArgs...) -} - -// Truef asserts that the specified value is true. -// -// a.Truef(myBool, "error message %s", "formatted") -func (a *Assertions) Truef(value bool, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Truef(a.t, value, msg, args...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second) -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// WithinDurationf asserts that the two times are within duration delta of each other. -// -// a.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted") -func (a *Assertions) WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - WithinDurationf(a.t, expected, actual, delta, msg, args...) -} - -// WithinRange asserts that a time is within a time range (inclusive). -// -// a.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second)) -func (a *Assertions) WithinRange(actual time.Time, start time.Time, end time.Time, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - WithinRange(a.t, actual, start, end, msgAndArgs...) -} - -// WithinRangef asserts that a time is within a time range (inclusive). -// -// a.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted") -func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - WithinRangef(a.t, actual, start, end, msg, args...) -} - -// YAMLEq asserts that two YAML strings are equivalent. -func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - YAMLEq(a.t, expected, actual, msgAndArgs...) -} - -// YAMLEqf asserts that two YAML strings are equivalent. -func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - YAMLEqf(a.t, expected, actual, msg, args...) -} - -// Zero asserts that i is the zero value for its type. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Zero(a.t, i, msgAndArgs...) -} - -// Zerof asserts that i is the zero value for its type. -func (a *Assertions) Zerof(i interface{}, msg string, args ...interface{}) { - if h, ok := a.t.(tHelper); ok { - h.Helper() - } - Zerof(a.t, i, msg, args...) -} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl b/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl deleted file mode 100644 index 54124df..0000000 --- a/vendor/github.com/stretchr/testify/require/require_forward.go.tmpl +++ /dev/null @@ -1,5 +0,0 @@ -{{.CommentWithoutT "a"}} -func (a *Assertions) {{.DocInfo.Name}}({{.Params}}) { - if h, ok := a.t.(tHelper); ok { h.Helper() } - {{.DocInfo.Name}}(a.t, {{.ForwardedParams}}) -} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go deleted file mode 100644 index 91772df..0000000 --- a/vendor/github.com/stretchr/testify/require/requirements.go +++ /dev/null @@ -1,29 +0,0 @@ -package require - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) - FailNow() -} - -type tHelper interface { - Helper() -} - -// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful -// for table driven tests. -type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) - -// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful -// for table driven tests. -type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) - -// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful -// for table driven tests. -type BoolAssertionFunc func(TestingT, bool, ...interface{}) - -// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful -// for table driven tests. -type ErrorAssertionFunc func(TestingT, error, ...interface{}) - -//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=require -template=require.go.tmpl -include-format-funcs" diff --git a/vendor/golang.org/x/crypto/LICENSE b/vendor/golang.org/x/crypto/LICENSE deleted file mode 100644 index 6a66aea..0000000 --- a/vendor/golang.org/x/crypto/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 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/golang.org/x/crypto/PATENTS b/vendor/golang.org/x/crypto/PATENTS deleted file mode 100644 index 7330990..0000000 --- a/vendor/golang.org/x/crypto/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/crypto/sha3/doc.go b/vendor/golang.org/x/crypto/sha3/doc.go deleted file mode 100644 index decd8cf..0000000 --- a/vendor/golang.org/x/crypto/sha3/doc.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 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 sha3 implements the SHA-3 fixed-output-length hash functions and -// the SHAKE variable-output-length hash functions defined by FIPS-202. -// -// Both types of hash function use the "sponge" construction and the Keccak -// permutation. For a detailed specification see http://keccak.noekeon.org/ -// -// # Guidance -// -// If you aren't sure what function you need, use SHAKE256 with at least 64 -// bytes of output. The SHAKE instances are faster than the SHA3 instances; -// the latter have to allocate memory to conform to the hash.Hash interface. -// -// If you need a secret-key MAC (message authentication code), prepend the -// secret key to the input, hash with SHAKE256 and read at least 32 bytes of -// output. -// -// # Security strengths -// -// The SHA3-x (x equals 224, 256, 384, or 512) functions have a security -// strength against preimage attacks of x bits. Since they only produce "x" -// bits of output, their collision-resistance is only "x/2" bits. -// -// The SHAKE-256 and -128 functions have a generic security strength of 256 and -// 128 bits against all attacks, provided that at least 2x bits of their output -// is used. Requesting more than 64 or 32 bytes of output, respectively, does -// not increase the collision-resistance of the SHAKE functions. -// -// # The sponge construction -// -// A sponge builds a pseudo-random function from a public pseudo-random -// permutation, by applying the permutation to a state of "rate + capacity" -// bytes, but hiding "capacity" of the bytes. -// -// A sponge starts out with a zero state. To hash an input using a sponge, up -// to "rate" bytes of the input are XORed into the sponge's state. The sponge -// is then "full" and the permutation is applied to "empty" it. This process is -// repeated until all the input has been "absorbed". The input is then padded. -// The digest is "squeezed" from the sponge in the same way, except that output -// is copied out instead of input being XORed in. -// -// A sponge is parameterized by its generic security strength, which is equal -// to half its capacity; capacity + rate is equal to the permutation's width. -// Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means -// that the security strength of a sponge instance is equal to (1600 - bitrate) / 2. -// -// # Recommendations -// -// The SHAKE functions are recommended for most new uses. They can produce -// output of arbitrary length. SHAKE256, with an output length of at least -// 64 bytes, provides 256-bit security against all attacks. The Keccak team -// recommends it for most applications upgrading from SHA2-512. (NIST chose a -// much stronger, but much slower, sponge instance for SHA3-512.) -// -// The SHA-3 functions are "drop-in" replacements for the SHA-2 functions. -// They produce output of the same length, with the same security strengths -// against all attacks. This means, in particular, that SHA3-256 only has -// 128-bit collision resistance, because its output length is 32 bytes. -package sha3 // import "golang.org/x/crypto/sha3" diff --git a/vendor/golang.org/x/crypto/sha3/hashes.go b/vendor/golang.org/x/crypto/sha3/hashes.go deleted file mode 100644 index 0d8043f..0000000 --- a/vendor/golang.org/x/crypto/sha3/hashes.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 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 sha3 - -// This file provides functions for creating instances of the SHA-3 -// and SHAKE hash functions, as well as utility functions for hashing -// bytes. - -import ( - "hash" -) - -// New224 creates a new SHA3-224 hash. -// Its generic security strength is 224 bits against preimage attacks, -// and 112 bits against collision attacks. -func New224() hash.Hash { - if h := new224Asm(); h != nil { - return h - } - return &state{rate: 144, outputLen: 28, dsbyte: 0x06} -} - -// New256 creates a new SHA3-256 hash. -// Its generic security strength is 256 bits against preimage attacks, -// and 128 bits against collision attacks. -func New256() hash.Hash { - if h := new256Asm(); h != nil { - return h - } - return &state{rate: 136, outputLen: 32, dsbyte: 0x06} -} - -// New384 creates a new SHA3-384 hash. -// Its generic security strength is 384 bits against preimage attacks, -// and 192 bits against collision attacks. -func New384() hash.Hash { - if h := new384Asm(); h != nil { - return h - } - return &state{rate: 104, outputLen: 48, dsbyte: 0x06} -} - -// New512 creates a new SHA3-512 hash. -// Its generic security strength is 512 bits against preimage attacks, -// and 256 bits against collision attacks. -func New512() hash.Hash { - if h := new512Asm(); h != nil { - return h - } - return &state{rate: 72, outputLen: 64, dsbyte: 0x06} -} - -// NewLegacyKeccak256 creates a new Keccak-256 hash. -// -// Only use this function if you require compatibility with an existing cryptosystem -// that uses non-standard padding. All other users should use New256 instead. -func NewLegacyKeccak256() hash.Hash { return &state{rate: 136, outputLen: 32, dsbyte: 0x01} } - -// NewLegacyKeccak512 creates a new Keccak-512 hash. -// -// Only use this function if you require compatibility with an existing cryptosystem -// that uses non-standard padding. All other users should use New512 instead. -func NewLegacyKeccak512() hash.Hash { return &state{rate: 72, outputLen: 64, dsbyte: 0x01} } - -// Sum224 returns the SHA3-224 digest of the data. -func Sum224(data []byte) (digest [28]byte) { - h := New224() - h.Write(data) - h.Sum(digest[:0]) - return -} - -// Sum256 returns the SHA3-256 digest of the data. -func Sum256(data []byte) (digest [32]byte) { - h := New256() - h.Write(data) - h.Sum(digest[:0]) - return -} - -// Sum384 returns the SHA3-384 digest of the data. -func Sum384(data []byte) (digest [48]byte) { - h := New384() - h.Write(data) - h.Sum(digest[:0]) - return -} - -// Sum512 returns the SHA3-512 digest of the data. -func Sum512(data []byte) (digest [64]byte) { - h := New512() - h.Write(data) - h.Sum(digest[:0]) - return -} diff --git a/vendor/golang.org/x/crypto/sha3/hashes_generic.go b/vendor/golang.org/x/crypto/sha3/hashes_generic.go deleted file mode 100644 index c74fc20..0000000 --- a/vendor/golang.org/x/crypto/sha3/hashes_generic.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2017 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. - -//go:build !gc || purego || !s390x -// +build !gc purego !s390x - -package sha3 - -import ( - "hash" -) - -// new224Asm returns an assembly implementation of SHA3-224 if available, -// otherwise it returns nil. -func new224Asm() hash.Hash { return nil } - -// new256Asm returns an assembly implementation of SHA3-256 if available, -// otherwise it returns nil. -func new256Asm() hash.Hash { return nil } - -// new384Asm returns an assembly implementation of SHA3-384 if available, -// otherwise it returns nil. -func new384Asm() hash.Hash { return nil } - -// new512Asm returns an assembly implementation of SHA3-512 if available, -// otherwise it returns nil. -func new512Asm() hash.Hash { return nil } diff --git a/vendor/golang.org/x/crypto/sha3/keccakf.go b/vendor/golang.org/x/crypto/sha3/keccakf.go deleted file mode 100644 index e5faa37..0000000 --- a/vendor/golang.org/x/crypto/sha3/keccakf.go +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright 2014 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. - -//go:build !amd64 || purego || !gc -// +build !amd64 purego !gc - -package sha3 - -import "math/bits" - -// rc stores the round constants for use in the ι step. -var rc = [24]uint64{ - 0x0000000000000001, - 0x0000000000008082, - 0x800000000000808A, - 0x8000000080008000, - 0x000000000000808B, - 0x0000000080000001, - 0x8000000080008081, - 0x8000000000008009, - 0x000000000000008A, - 0x0000000000000088, - 0x0000000080008009, - 0x000000008000000A, - 0x000000008000808B, - 0x800000000000008B, - 0x8000000000008089, - 0x8000000000008003, - 0x8000000000008002, - 0x8000000000000080, - 0x000000000000800A, - 0x800000008000000A, - 0x8000000080008081, - 0x8000000000008080, - 0x0000000080000001, - 0x8000000080008008, -} - -// keccakF1600 applies the Keccak permutation to a 1600b-wide -// state represented as a slice of 25 uint64s. -func keccakF1600(a *[25]uint64) { - // Implementation translated from Keccak-inplace.c - // in the keccak reference code. - var t, bc0, bc1, bc2, bc3, bc4, d0, d1, d2, d3, d4 uint64 - - for i := 0; i < 24; i += 4 { - // Combines the 5 steps in each round into 2 steps. - // Unrolls 4 rounds per loop and spreads some steps across rounds. - - // Round 1 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[6] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[12] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[18] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[24] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i] - a[6] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[16] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[22] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[3] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[10] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[1] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[7] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[19] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[20] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[11] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[23] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[4] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[5] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[2] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[8] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[14] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[15] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - // Round 2 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[16] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[7] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[23] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[14] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+1] - a[16] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[11] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[2] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[18] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[20] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[6] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[22] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[4] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[15] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[1] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[8] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[24] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[10] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[12] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[3] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[19] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[5] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - // Round 3 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[11] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[22] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[8] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[19] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+2] - a[11] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[1] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[12] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[23] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[15] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[16] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[2] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[24] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[5] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[6] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[3] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[14] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[20] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[7] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[18] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[4] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[10] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - // Round 4 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[1] ^ d1 - bc1 = bits.RotateLeft64(t, 44) - t = a[2] ^ d2 - bc2 = bits.RotateLeft64(t, 43) - t = a[3] ^ d3 - bc3 = bits.RotateLeft64(t, 21) - t = a[4] ^ d4 - bc4 = bits.RotateLeft64(t, 14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ rc[i+3] - a[1] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc2 = bits.RotateLeft64(t, 3) - t = a[6] ^ d1 - bc3 = bits.RotateLeft64(t, 45) - t = a[7] ^ d2 - bc4 = bits.RotateLeft64(t, 61) - t = a[8] ^ d3 - bc0 = bits.RotateLeft64(t, 28) - t = a[9] ^ d4 - bc1 = bits.RotateLeft64(t, 20) - a[5] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc4 = bits.RotateLeft64(t, 18) - t = a[11] ^ d1 - bc0 = bits.RotateLeft64(t, 1) - t = a[12] ^ d2 - bc1 = bits.RotateLeft64(t, 6) - t = a[13] ^ d3 - bc2 = bits.RotateLeft64(t, 25) - t = a[14] ^ d4 - bc3 = bits.RotateLeft64(t, 8) - a[10] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc1 = bits.RotateLeft64(t, 36) - t = a[16] ^ d1 - bc2 = bits.RotateLeft64(t, 10) - t = a[17] ^ d2 - bc3 = bits.RotateLeft64(t, 15) - t = a[18] ^ d3 - bc4 = bits.RotateLeft64(t, 56) - t = a[19] ^ d4 - bc0 = bits.RotateLeft64(t, 27) - a[15] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc3 = bits.RotateLeft64(t, 41) - t = a[21] ^ d1 - bc4 = bits.RotateLeft64(t, 2) - t = a[22] ^ d2 - bc0 = bits.RotateLeft64(t, 62) - t = a[23] ^ d3 - bc1 = bits.RotateLeft64(t, 55) - t = a[24] ^ d4 - bc2 = bits.RotateLeft64(t, 39) - a[20] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - } -} diff --git a/vendor/golang.org/x/crypto/sha3/keccakf_amd64.go b/vendor/golang.org/x/crypto/sha3/keccakf_amd64.go deleted file mode 100644 index 248a382..0000000 --- a/vendor/golang.org/x/crypto/sha3/keccakf_amd64.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2015 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. - -//go:build amd64 && !purego && gc -// +build amd64,!purego,gc - -package sha3 - -// This function is implemented in keccakf_amd64.s. - -//go:noescape - -func keccakF1600(a *[25]uint64) diff --git a/vendor/golang.org/x/crypto/sha3/keccakf_amd64.s b/vendor/golang.org/x/crypto/sha3/keccakf_amd64.s deleted file mode 100644 index 4cfa543..0000000 --- a/vendor/golang.org/x/crypto/sha3/keccakf_amd64.s +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2015 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. - -//go:build amd64 && !purego && gc -// +build amd64,!purego,gc - -// This code was translated into a form compatible with 6a from the public -// domain sources at https://github.com/gvanas/KeccakCodePackage - -// Offsets in state -#define _ba (0*8) -#define _be (1*8) -#define _bi (2*8) -#define _bo (3*8) -#define _bu (4*8) -#define _ga (5*8) -#define _ge (6*8) -#define _gi (7*8) -#define _go (8*8) -#define _gu (9*8) -#define _ka (10*8) -#define _ke (11*8) -#define _ki (12*8) -#define _ko (13*8) -#define _ku (14*8) -#define _ma (15*8) -#define _me (16*8) -#define _mi (17*8) -#define _mo (18*8) -#define _mu (19*8) -#define _sa (20*8) -#define _se (21*8) -#define _si (22*8) -#define _so (23*8) -#define _su (24*8) - -// Temporary registers -#define rT1 AX - -// Round vars -#define rpState DI -#define rpStack SP - -#define rDa BX -#define rDe CX -#define rDi DX -#define rDo R8 -#define rDu R9 - -#define rBa R10 -#define rBe R11 -#define rBi R12 -#define rBo R13 -#define rBu R14 - -#define rCa SI -#define rCe BP -#define rCi rBi -#define rCo rBo -#define rCu R15 - -#define MOVQ_RBI_RCE MOVQ rBi, rCe -#define XORQ_RT1_RCA XORQ rT1, rCa -#define XORQ_RT1_RCE XORQ rT1, rCe -#define XORQ_RBA_RCU XORQ rBa, rCu -#define XORQ_RBE_RCU XORQ rBe, rCu -#define XORQ_RDU_RCU XORQ rDu, rCu -#define XORQ_RDA_RCA XORQ rDa, rCa -#define XORQ_RDE_RCE XORQ rDe, rCe - -#define mKeccakRound(iState, oState, rc, B_RBI_RCE, G_RT1_RCA, G_RT1_RCE, G_RBA_RCU, K_RT1_RCA, K_RT1_RCE, K_RBA_RCU, M_RT1_RCA, M_RT1_RCE, M_RBE_RCU, S_RDU_RCU, S_RDA_RCA, S_RDE_RCE) \ - /* Prepare round */ \ - MOVQ rCe, rDa; \ - ROLQ $1, rDa; \ - \ - MOVQ _bi(iState), rCi; \ - XORQ _gi(iState), rDi; \ - XORQ rCu, rDa; \ - XORQ _ki(iState), rCi; \ - XORQ _mi(iState), rDi; \ - XORQ rDi, rCi; \ - \ - MOVQ rCi, rDe; \ - ROLQ $1, rDe; \ - \ - MOVQ _bo(iState), rCo; \ - XORQ _go(iState), rDo; \ - XORQ rCa, rDe; \ - XORQ _ko(iState), rCo; \ - XORQ _mo(iState), rDo; \ - XORQ rDo, rCo; \ - \ - MOVQ rCo, rDi; \ - ROLQ $1, rDi; \ - \ - MOVQ rCu, rDo; \ - XORQ rCe, rDi; \ - ROLQ $1, rDo; \ - \ - MOVQ rCa, rDu; \ - XORQ rCi, rDo; \ - ROLQ $1, rDu; \ - \ - /* Result b */ \ - MOVQ _ba(iState), rBa; \ - MOVQ _ge(iState), rBe; \ - XORQ rCo, rDu; \ - MOVQ _ki(iState), rBi; \ - MOVQ _mo(iState), rBo; \ - MOVQ _su(iState), rBu; \ - XORQ rDe, rBe; \ - ROLQ $44, rBe; \ - XORQ rDi, rBi; \ - XORQ rDa, rBa; \ - ROLQ $43, rBi; \ - \ - MOVQ rBe, rCa; \ - MOVQ rc, rT1; \ - ORQ rBi, rCa; \ - XORQ rBa, rT1; \ - XORQ rT1, rCa; \ - MOVQ rCa, _ba(oState); \ - \ - XORQ rDu, rBu; \ - ROLQ $14, rBu; \ - MOVQ rBa, rCu; \ - ANDQ rBe, rCu; \ - XORQ rBu, rCu; \ - MOVQ rCu, _bu(oState); \ - \ - XORQ rDo, rBo; \ - ROLQ $21, rBo; \ - MOVQ rBo, rT1; \ - ANDQ rBu, rT1; \ - XORQ rBi, rT1; \ - MOVQ rT1, _bi(oState); \ - \ - NOTQ rBi; \ - ORQ rBa, rBu; \ - ORQ rBo, rBi; \ - XORQ rBo, rBu; \ - XORQ rBe, rBi; \ - MOVQ rBu, _bo(oState); \ - MOVQ rBi, _be(oState); \ - B_RBI_RCE; \ - \ - /* Result g */ \ - MOVQ _gu(iState), rBe; \ - XORQ rDu, rBe; \ - MOVQ _ka(iState), rBi; \ - ROLQ $20, rBe; \ - XORQ rDa, rBi; \ - ROLQ $3, rBi; \ - MOVQ _bo(iState), rBa; \ - MOVQ rBe, rT1; \ - ORQ rBi, rT1; \ - XORQ rDo, rBa; \ - MOVQ _me(iState), rBo; \ - MOVQ _si(iState), rBu; \ - ROLQ $28, rBa; \ - XORQ rBa, rT1; \ - MOVQ rT1, _ga(oState); \ - G_RT1_RCA; \ - \ - XORQ rDe, rBo; \ - ROLQ $45, rBo; \ - MOVQ rBi, rT1; \ - ANDQ rBo, rT1; \ - XORQ rBe, rT1; \ - MOVQ rT1, _ge(oState); \ - G_RT1_RCE; \ - \ - XORQ rDi, rBu; \ - ROLQ $61, rBu; \ - MOVQ rBu, rT1; \ - ORQ rBa, rT1; \ - XORQ rBo, rT1; \ - MOVQ rT1, _go(oState); \ - \ - ANDQ rBe, rBa; \ - XORQ rBu, rBa; \ - MOVQ rBa, _gu(oState); \ - NOTQ rBu; \ - G_RBA_RCU; \ - \ - ORQ rBu, rBo; \ - XORQ rBi, rBo; \ - MOVQ rBo, _gi(oState); \ - \ - /* Result k */ \ - MOVQ _be(iState), rBa; \ - MOVQ _gi(iState), rBe; \ - MOVQ _ko(iState), rBi; \ - MOVQ _mu(iState), rBo; \ - MOVQ _sa(iState), rBu; \ - XORQ rDi, rBe; \ - ROLQ $6, rBe; \ - XORQ rDo, rBi; \ - ROLQ $25, rBi; \ - MOVQ rBe, rT1; \ - ORQ rBi, rT1; \ - XORQ rDe, rBa; \ - ROLQ $1, rBa; \ - XORQ rBa, rT1; \ - MOVQ rT1, _ka(oState); \ - K_RT1_RCA; \ - \ - XORQ rDu, rBo; \ - ROLQ $8, rBo; \ - MOVQ rBi, rT1; \ - ANDQ rBo, rT1; \ - XORQ rBe, rT1; \ - MOVQ rT1, _ke(oState); \ - K_RT1_RCE; \ - \ - XORQ rDa, rBu; \ - ROLQ $18, rBu; \ - NOTQ rBo; \ - MOVQ rBo, rT1; \ - ANDQ rBu, rT1; \ - XORQ rBi, rT1; \ - MOVQ rT1, _ki(oState); \ - \ - MOVQ rBu, rT1; \ - ORQ rBa, rT1; \ - XORQ rBo, rT1; \ - MOVQ rT1, _ko(oState); \ - \ - ANDQ rBe, rBa; \ - XORQ rBu, rBa; \ - MOVQ rBa, _ku(oState); \ - K_RBA_RCU; \ - \ - /* Result m */ \ - MOVQ _ga(iState), rBe; \ - XORQ rDa, rBe; \ - MOVQ _ke(iState), rBi; \ - ROLQ $36, rBe; \ - XORQ rDe, rBi; \ - MOVQ _bu(iState), rBa; \ - ROLQ $10, rBi; \ - MOVQ rBe, rT1; \ - MOVQ _mi(iState), rBo; \ - ANDQ rBi, rT1; \ - XORQ rDu, rBa; \ - MOVQ _so(iState), rBu; \ - ROLQ $27, rBa; \ - XORQ rBa, rT1; \ - MOVQ rT1, _ma(oState); \ - M_RT1_RCA; \ - \ - XORQ rDi, rBo; \ - ROLQ $15, rBo; \ - MOVQ rBi, rT1; \ - ORQ rBo, rT1; \ - XORQ rBe, rT1; \ - MOVQ rT1, _me(oState); \ - M_RT1_RCE; \ - \ - XORQ rDo, rBu; \ - ROLQ $56, rBu; \ - NOTQ rBo; \ - MOVQ rBo, rT1; \ - ORQ rBu, rT1; \ - XORQ rBi, rT1; \ - MOVQ rT1, _mi(oState); \ - \ - ORQ rBa, rBe; \ - XORQ rBu, rBe; \ - MOVQ rBe, _mu(oState); \ - \ - ANDQ rBa, rBu; \ - XORQ rBo, rBu; \ - MOVQ rBu, _mo(oState); \ - M_RBE_RCU; \ - \ - /* Result s */ \ - MOVQ _bi(iState), rBa; \ - MOVQ _go(iState), rBe; \ - MOVQ _ku(iState), rBi; \ - XORQ rDi, rBa; \ - MOVQ _ma(iState), rBo; \ - ROLQ $62, rBa; \ - XORQ rDo, rBe; \ - MOVQ _se(iState), rBu; \ - ROLQ $55, rBe; \ - \ - XORQ rDu, rBi; \ - MOVQ rBa, rDu; \ - XORQ rDe, rBu; \ - ROLQ $2, rBu; \ - ANDQ rBe, rDu; \ - XORQ rBu, rDu; \ - MOVQ rDu, _su(oState); \ - \ - ROLQ $39, rBi; \ - S_RDU_RCU; \ - NOTQ rBe; \ - XORQ rDa, rBo; \ - MOVQ rBe, rDa; \ - ANDQ rBi, rDa; \ - XORQ rBa, rDa; \ - MOVQ rDa, _sa(oState); \ - S_RDA_RCA; \ - \ - ROLQ $41, rBo; \ - MOVQ rBi, rDe; \ - ORQ rBo, rDe; \ - XORQ rBe, rDe; \ - MOVQ rDe, _se(oState); \ - S_RDE_RCE; \ - \ - MOVQ rBo, rDi; \ - MOVQ rBu, rDo; \ - ANDQ rBu, rDi; \ - ORQ rBa, rDo; \ - XORQ rBi, rDi; \ - XORQ rBo, rDo; \ - MOVQ rDi, _si(oState); \ - MOVQ rDo, _so(oState) \ - -// func keccakF1600(state *[25]uint64) -TEXT ·keccakF1600(SB), 0, $200-8 - MOVQ state+0(FP), rpState - - // Convert the user state into an internal state - NOTQ _be(rpState) - NOTQ _bi(rpState) - NOTQ _go(rpState) - NOTQ _ki(rpState) - NOTQ _mi(rpState) - NOTQ _sa(rpState) - - // Execute the KeccakF permutation - MOVQ _ba(rpState), rCa - MOVQ _be(rpState), rCe - MOVQ _bu(rpState), rCu - - XORQ _ga(rpState), rCa - XORQ _ge(rpState), rCe - XORQ _gu(rpState), rCu - - XORQ _ka(rpState), rCa - XORQ _ke(rpState), rCe - XORQ _ku(rpState), rCu - - XORQ _ma(rpState), rCa - XORQ _me(rpState), rCe - XORQ _mu(rpState), rCu - - XORQ _sa(rpState), rCa - XORQ _se(rpState), rCe - MOVQ _si(rpState), rDi - MOVQ _so(rpState), rDo - XORQ _su(rpState), rCu - - mKeccakRound(rpState, rpStack, $0x0000000000000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x0000000000008082, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x800000000000808a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000080008000, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000000000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000000000008a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x0000000000000088, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x0000000080008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x000000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000008000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x800000000000008b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000000008089, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000008003, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000000008002, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000000080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000000000800a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x800000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000008080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000080008008, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP) - - // Revert the internal state to the user state - NOTQ _be(rpState) - NOTQ _bi(rpState) - NOTQ _go(rpState) - NOTQ _ki(rpState) - NOTQ _mi(rpState) - NOTQ _sa(rpState) - - RET diff --git a/vendor/golang.org/x/crypto/sha3/register.go b/vendor/golang.org/x/crypto/sha3/register.go deleted file mode 100644 index 8b4453a..0000000 --- a/vendor/golang.org/x/crypto/sha3/register.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2014 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. - -//go:build go1.4 -// +build go1.4 - -package sha3 - -import ( - "crypto" -) - -func init() { - crypto.RegisterHash(crypto.SHA3_224, New224) - crypto.RegisterHash(crypto.SHA3_256, New256) - crypto.RegisterHash(crypto.SHA3_384, New384) - crypto.RegisterHash(crypto.SHA3_512, New512) -} diff --git a/vendor/golang.org/x/crypto/sha3/sha3.go b/vendor/golang.org/x/crypto/sha3/sha3.go deleted file mode 100644 index fa182be..0000000 --- a/vendor/golang.org/x/crypto/sha3/sha3.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2014 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 sha3 - -// spongeDirection indicates the direction bytes are flowing through the sponge. -type spongeDirection int - -const ( - // spongeAbsorbing indicates that the sponge is absorbing input. - spongeAbsorbing spongeDirection = iota - // spongeSqueezing indicates that the sponge is being squeezed. - spongeSqueezing -) - -const ( - // maxRate is the maximum size of the internal buffer. SHAKE-256 - // currently needs the largest buffer. - maxRate = 168 -) - -type state struct { - // Generic sponge components. - a [25]uint64 // main state of the hash - buf []byte // points into storage - rate int // the number of bytes of state to use - - // dsbyte contains the "domain separation" bits and the first bit of - // the padding. Sections 6.1 and 6.2 of [1] separate the outputs of the - // SHA-3 and SHAKE functions by appending bitstrings to the message. - // Using a little-endian bit-ordering convention, these are "01" for SHA-3 - // and "1111" for SHAKE, or 00000010b and 00001111b, respectively. Then the - // padding rule from section 5.1 is applied to pad the message to a multiple - // of the rate, which involves adding a "1" bit, zero or more "0" bits, and - // a final "1" bit. We merge the first "1" bit from the padding into dsbyte, - // giving 00000110b (0x06) and 00011111b (0x1f). - // [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf - // "Draft FIPS 202: SHA-3 Standard: Permutation-Based Hash and - // Extendable-Output Functions (May 2014)" - dsbyte byte - - storage storageBuf - - // Specific to SHA-3 and SHAKE. - outputLen int // the default output size in bytes - state spongeDirection // whether the sponge is absorbing or squeezing -} - -// BlockSize returns the rate of sponge underlying this hash function. -func (d *state) BlockSize() int { return d.rate } - -// Size returns the output size of the hash function in bytes. -func (d *state) Size() int { return d.outputLen } - -// Reset clears the internal state by zeroing the sponge state and -// the byte buffer, and setting Sponge.state to absorbing. -func (d *state) Reset() { - // Zero the permutation's state. - for i := range d.a { - d.a[i] = 0 - } - d.state = spongeAbsorbing - d.buf = d.storage.asBytes()[:0] -} - -func (d *state) clone() *state { - ret := *d - if ret.state == spongeAbsorbing { - ret.buf = ret.storage.asBytes()[:len(ret.buf)] - } else { - ret.buf = ret.storage.asBytes()[d.rate-cap(d.buf) : d.rate] - } - - return &ret -} - -// permute applies the KeccakF-1600 permutation. It handles -// any input-output buffering. -func (d *state) permute() { - switch d.state { - case spongeAbsorbing: - // If we're absorbing, we need to xor the input into the state - // before applying the permutation. - xorIn(d, d.buf) - d.buf = d.storage.asBytes()[:0] - keccakF1600(&d.a) - case spongeSqueezing: - // If we're squeezing, we need to apply the permutation before - // copying more output. - keccakF1600(&d.a) - d.buf = d.storage.asBytes()[:d.rate] - copyOut(d, d.buf) - } -} - -// pads appends the domain separation bits in dsbyte, applies -// the multi-bitrate 10..1 padding rule, and permutes the state. -func (d *state) padAndPermute(dsbyte byte) { - if d.buf == nil { - d.buf = d.storage.asBytes()[:0] - } - // Pad with this instance's domain-separator bits. We know that there's - // at least one byte of space in d.buf because, if it were full, - // permute would have been called to empty it. dsbyte also contains the - // first one bit for the padding. See the comment in the state struct. - d.buf = append(d.buf, dsbyte) - zerosStart := len(d.buf) - d.buf = d.storage.asBytes()[:d.rate] - for i := zerosStart; i < d.rate; i++ { - d.buf[i] = 0 - } - // This adds the final one bit for the padding. Because of the way that - // bits are numbered from the LSB upwards, the final bit is the MSB of - // the last byte. - d.buf[d.rate-1] ^= 0x80 - // Apply the permutation - d.permute() - d.state = spongeSqueezing - d.buf = d.storage.asBytes()[:d.rate] - copyOut(d, d.buf) -} - -// Write absorbs more data into the hash's state. It produces an error -// if more data is written to the ShakeHash after writing -func (d *state) Write(p []byte) (written int, err error) { - if d.state != spongeAbsorbing { - panic("sha3: write to sponge after read") - } - if d.buf == nil { - d.buf = d.storage.asBytes()[:0] - } - written = len(p) - - for len(p) > 0 { - if len(d.buf) == 0 && len(p) >= d.rate { - // The fast path; absorb a full "rate" bytes of input and apply the permutation. - xorIn(d, p[:d.rate]) - p = p[d.rate:] - keccakF1600(&d.a) - } else { - // The slow path; buffer the input until we can fill the sponge, and then xor it in. - todo := d.rate - len(d.buf) - if todo > len(p) { - todo = len(p) - } - d.buf = append(d.buf, p[:todo]...) - p = p[todo:] - - // If the sponge is full, apply the permutation. - if len(d.buf) == d.rate { - d.permute() - } - } - } - - return -} - -// Read squeezes an arbitrary number of bytes from the sponge. -func (d *state) Read(out []byte) (n int, err error) { - // If we're still absorbing, pad and apply the permutation. - if d.state == spongeAbsorbing { - d.padAndPermute(d.dsbyte) - } - - n = len(out) - - // Now, do the squeezing. - for len(out) > 0 { - n := copy(out, d.buf) - d.buf = d.buf[n:] - out = out[n:] - - // Apply the permutation if we've squeezed the sponge dry. - if len(d.buf) == 0 { - d.permute() - } - } - - return -} - -// Sum applies padding to the hash state and then squeezes out the desired -// number of output bytes. -func (d *state) Sum(in []byte) []byte { - // Make a copy of the original hash so that caller can keep writing - // and summing. - dup := d.clone() - hash := make([]byte, dup.outputLen) - dup.Read(hash) - return append(in, hash...) -} diff --git a/vendor/golang.org/x/crypto/sha3/sha3_s390x.go b/vendor/golang.org/x/crypto/sha3/sha3_s390x.go deleted file mode 100644 index 63a3edb..0000000 --- a/vendor/golang.org/x/crypto/sha3/sha3_s390x.go +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2017 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. - -//go:build gc && !purego -// +build gc,!purego - -package sha3 - -// This file contains code for using the 'compute intermediate -// message digest' (KIMD) and 'compute last message digest' (KLMD) -// instructions to compute SHA-3 and SHAKE hashes on IBM Z. - -import ( - "hash" - - "golang.org/x/sys/cpu" -) - -// codes represent 7-bit KIMD/KLMD function codes as defined in -// the Principles of Operation. -type code uint64 - -const ( - // function codes for KIMD/KLMD - sha3_224 code = 32 - sha3_256 = 33 - sha3_384 = 34 - sha3_512 = 35 - shake_128 = 36 - shake_256 = 37 - nopad = 0x100 -) - -// kimd is a wrapper for the 'compute intermediate message digest' instruction. -// src must be a multiple of the rate for the given function code. -// -//go:noescape -func kimd(function code, chain *[200]byte, src []byte) - -// klmd is a wrapper for the 'compute last message digest' instruction. -// src padding is handled by the instruction. -// -//go:noescape -func klmd(function code, chain *[200]byte, dst, src []byte) - -type asmState struct { - a [200]byte // 1600 bit state - buf []byte // care must be taken to ensure cap(buf) is a multiple of rate - rate int // equivalent to block size - storage [3072]byte // underlying storage for buf - outputLen int // output length if fixed, 0 if not - function code // KIMD/KLMD function code - state spongeDirection // whether the sponge is absorbing or squeezing -} - -func newAsmState(function code) *asmState { - var s asmState - s.function = function - switch function { - case sha3_224: - s.rate = 144 - s.outputLen = 28 - case sha3_256: - s.rate = 136 - s.outputLen = 32 - case sha3_384: - s.rate = 104 - s.outputLen = 48 - case sha3_512: - s.rate = 72 - s.outputLen = 64 - case shake_128: - s.rate = 168 - case shake_256: - s.rate = 136 - default: - panic("sha3: unrecognized function code") - } - - // limit s.buf size to a multiple of s.rate - s.resetBuf() - return &s -} - -func (s *asmState) clone() *asmState { - c := *s - c.buf = c.storage[:len(s.buf):cap(s.buf)] - return &c -} - -// copyIntoBuf copies b into buf. It will panic if there is not enough space to -// store all of b. -func (s *asmState) copyIntoBuf(b []byte) { - bufLen := len(s.buf) - s.buf = s.buf[:len(s.buf)+len(b)] - copy(s.buf[bufLen:], b) -} - -// resetBuf points buf at storage, sets the length to 0 and sets cap to be a -// multiple of the rate. -func (s *asmState) resetBuf() { - max := (cap(s.storage) / s.rate) * s.rate - s.buf = s.storage[:0:max] -} - -// Write (via the embedded io.Writer interface) adds more data to the running hash. -// It never returns an error. -func (s *asmState) Write(b []byte) (int, error) { - if s.state != spongeAbsorbing { - panic("sha3: write to sponge after read") - } - length := len(b) - for len(b) > 0 { - if len(s.buf) == 0 && len(b) >= cap(s.buf) { - // Hash the data directly and push any remaining bytes - // into the buffer. - remainder := len(b) % s.rate - kimd(s.function, &s.a, b[:len(b)-remainder]) - if remainder != 0 { - s.copyIntoBuf(b[len(b)-remainder:]) - } - return length, nil - } - - if len(s.buf) == cap(s.buf) { - // flush the buffer - kimd(s.function, &s.a, s.buf) - s.buf = s.buf[:0] - } - - // copy as much as we can into the buffer - n := len(b) - if len(b) > cap(s.buf)-len(s.buf) { - n = cap(s.buf) - len(s.buf) - } - s.copyIntoBuf(b[:n]) - b = b[n:] - } - return length, nil -} - -// Read squeezes an arbitrary number of bytes from the sponge. -func (s *asmState) Read(out []byte) (n int, err error) { - n = len(out) - - // need to pad if we were absorbing - if s.state == spongeAbsorbing { - s.state = spongeSqueezing - - // write hash directly into out if possible - if len(out)%s.rate == 0 { - klmd(s.function, &s.a, out, s.buf) // len(out) may be 0 - s.buf = s.buf[:0] - return - } - - // write hash into buffer - max := cap(s.buf) - if max > len(out) { - max = (len(out)/s.rate)*s.rate + s.rate - } - klmd(s.function, &s.a, s.buf[:max], s.buf) - s.buf = s.buf[:max] - } - - for len(out) > 0 { - // flush the buffer - if len(s.buf) != 0 { - c := copy(out, s.buf) - out = out[c:] - s.buf = s.buf[c:] - continue - } - - // write hash directly into out if possible - if len(out)%s.rate == 0 { - klmd(s.function|nopad, &s.a, out, nil) - return - } - - // write hash into buffer - s.resetBuf() - if cap(s.buf) > len(out) { - s.buf = s.buf[:(len(out)/s.rate)*s.rate+s.rate] - } - klmd(s.function|nopad, &s.a, s.buf, nil) - } - return -} - -// Sum appends the current hash to b and returns the resulting slice. -// It does not change the underlying hash state. -func (s *asmState) Sum(b []byte) []byte { - if s.outputLen == 0 { - panic("sha3: cannot call Sum on SHAKE functions") - } - - // Copy the state to preserve the original. - a := s.a - - // Hash the buffer. Note that we don't clear it because we - // aren't updating the state. - klmd(s.function, &a, nil, s.buf) - return append(b, a[:s.outputLen]...) -} - -// Reset resets the Hash to its initial state. -func (s *asmState) Reset() { - for i := range s.a { - s.a[i] = 0 - } - s.resetBuf() - s.state = spongeAbsorbing -} - -// Size returns the number of bytes Sum will return. -func (s *asmState) Size() int { - return s.outputLen -} - -// BlockSize returns the hash's underlying block size. -// The Write method must be able to accept any amount -// of data, but it may operate more efficiently if all writes -// are a multiple of the block size. -func (s *asmState) BlockSize() int { - return s.rate -} - -// Clone returns a copy of the ShakeHash in its current state. -func (s *asmState) Clone() ShakeHash { - return s.clone() -} - -// new224Asm returns an assembly implementation of SHA3-224 if available, -// otherwise it returns nil. -func new224Asm() hash.Hash { - if cpu.S390X.HasSHA3 { - return newAsmState(sha3_224) - } - return nil -} - -// new256Asm returns an assembly implementation of SHA3-256 if available, -// otherwise it returns nil. -func new256Asm() hash.Hash { - if cpu.S390X.HasSHA3 { - return newAsmState(sha3_256) - } - return nil -} - -// new384Asm returns an assembly implementation of SHA3-384 if available, -// otherwise it returns nil. -func new384Asm() hash.Hash { - if cpu.S390X.HasSHA3 { - return newAsmState(sha3_384) - } - return nil -} - -// new512Asm returns an assembly implementation of SHA3-512 if available, -// otherwise it returns nil. -func new512Asm() hash.Hash { - if cpu.S390X.HasSHA3 { - return newAsmState(sha3_512) - } - return nil -} - -// newShake128Asm returns an assembly implementation of SHAKE-128 if available, -// otherwise it returns nil. -func newShake128Asm() ShakeHash { - if cpu.S390X.HasSHA3 { - return newAsmState(shake_128) - } - return nil -} - -// newShake256Asm returns an assembly implementation of SHAKE-256 if available, -// otherwise it returns nil. -func newShake256Asm() ShakeHash { - if cpu.S390X.HasSHA3 { - return newAsmState(shake_256) - } - return nil -} diff --git a/vendor/golang.org/x/crypto/sha3/sha3_s390x.s b/vendor/golang.org/x/crypto/sha3/sha3_s390x.s deleted file mode 100644 index a0e051b..0000000 --- a/vendor/golang.org/x/crypto/sha3/sha3_s390x.s +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2017 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. - -//go:build gc && !purego -// +build gc,!purego - -#include "textflag.h" - -// func kimd(function code, chain *[200]byte, src []byte) -TEXT ·kimd(SB), NOFRAME|NOSPLIT, $0-40 - MOVD function+0(FP), R0 - MOVD chain+8(FP), R1 - LMG src+16(FP), R2, R3 // R2=base, R3=len - -continue: - WORD $0xB93E0002 // KIMD --, R2 - BVS continue // continue if interrupted - MOVD $0, R0 // reset R0 for pre-go1.8 compilers - RET - -// func klmd(function code, chain *[200]byte, dst, src []byte) -TEXT ·klmd(SB), NOFRAME|NOSPLIT, $0-64 - // TODO: SHAKE support - MOVD function+0(FP), R0 - MOVD chain+8(FP), R1 - LMG dst+16(FP), R2, R3 // R2=base, R3=len - LMG src+40(FP), R4, R5 // R4=base, R5=len - -continue: - WORD $0xB93F0024 // KLMD R2, R4 - BVS continue // continue if interrupted - MOVD $0, R0 // reset R0 for pre-go1.8 compilers - RET diff --git a/vendor/golang.org/x/crypto/sha3/shake.go b/vendor/golang.org/x/crypto/sha3/shake.go deleted file mode 100644 index d7be295..0000000 --- a/vendor/golang.org/x/crypto/sha3/shake.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2014 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 sha3 - -// This file defines the ShakeHash interface, and provides -// functions for creating SHAKE and cSHAKE instances, as well as utility -// functions for hashing bytes to arbitrary-length output. -// -// -// SHAKE implementation is based on FIPS PUB 202 [1] -// cSHAKE implementations is based on NIST SP 800-185 [2] -// -// [1] https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf -// [2] https://doi.org/10.6028/NIST.SP.800-185 - -import ( - "encoding/binary" - "io" -) - -// ShakeHash defines the interface to hash functions that -// support arbitrary-length output. -type ShakeHash interface { - // Write absorbs more data into the hash's state. It panics if input is - // written to it after output has been read from it. - io.Writer - - // Read reads more output from the hash; reading affects the hash's - // state. (ShakeHash.Read is thus very different from Hash.Sum) - // It never returns an error. - io.Reader - - // Clone returns a copy of the ShakeHash in its current state. - Clone() ShakeHash - - // Reset resets the ShakeHash to its initial state. - Reset() -} - -// cSHAKE specific context -type cshakeState struct { - *state // SHA-3 state context and Read/Write operations - - // initBlock is the cSHAKE specific initialization set of bytes. It is initialized - // by newCShake function and stores concatenation of N followed by S, encoded - // by the method specified in 3.3 of [1]. - // It is stored here in order for Reset() to be able to put context into - // initial state. - initBlock []byte -} - -// Consts for configuring initial SHA-3 state -const ( - dsbyteShake = 0x1f - dsbyteCShake = 0x04 - rate128 = 168 - rate256 = 136 -) - -func bytepad(input []byte, w int) []byte { - // leftEncode always returns max 9 bytes - buf := make([]byte, 0, 9+len(input)+w) - buf = append(buf, leftEncode(uint64(w))...) - buf = append(buf, input...) - padlen := w - (len(buf) % w) - return append(buf, make([]byte, padlen)...) -} - -func leftEncode(value uint64) []byte { - var b [9]byte - binary.BigEndian.PutUint64(b[1:], value) - // Trim all but last leading zero bytes - i := byte(1) - for i < 8 && b[i] == 0 { - i++ - } - // Prepend number of encoded bytes - b[i-1] = 9 - i - return b[i-1:] -} - -func newCShake(N, S []byte, rate int, dsbyte byte) ShakeHash { - c := cshakeState{state: &state{rate: rate, dsbyte: dsbyte}} - - // leftEncode returns max 9 bytes - c.initBlock = make([]byte, 0, 9*2+len(N)+len(S)) - c.initBlock = append(c.initBlock, leftEncode(uint64(len(N)*8))...) - c.initBlock = append(c.initBlock, N...) - c.initBlock = append(c.initBlock, leftEncode(uint64(len(S)*8))...) - c.initBlock = append(c.initBlock, S...) - c.Write(bytepad(c.initBlock, c.rate)) - return &c -} - -// Reset resets the hash to initial state. -func (c *cshakeState) Reset() { - c.state.Reset() - c.Write(bytepad(c.initBlock, c.rate)) -} - -// Clone returns copy of a cSHAKE context within its current state. -func (c *cshakeState) Clone() ShakeHash { - b := make([]byte, len(c.initBlock)) - copy(b, c.initBlock) - return &cshakeState{state: c.clone(), initBlock: b} -} - -// Clone returns copy of SHAKE context within its current state. -func (c *state) Clone() ShakeHash { - return c.clone() -} - -// NewShake128 creates a new SHAKE128 variable-output-length ShakeHash. -// Its generic security strength is 128 bits against all attacks if at -// least 32 bytes of its output are used. -func NewShake128() ShakeHash { - if h := newShake128Asm(); h != nil { - return h - } - return &state{rate: rate128, dsbyte: dsbyteShake} -} - -// NewShake256 creates a new SHAKE256 variable-output-length ShakeHash. -// Its generic security strength is 256 bits against all attacks if -// at least 64 bytes of its output are used. -func NewShake256() ShakeHash { - if h := newShake256Asm(); h != nil { - return h - } - return &state{rate: rate256, dsbyte: dsbyteShake} -} - -// NewCShake128 creates a new instance of cSHAKE128 variable-output-length ShakeHash, -// a customizable variant of SHAKE128. -// N is used to define functions based on cSHAKE, it can be empty when plain cSHAKE is -// desired. S is a customization byte string used for domain separation - two cSHAKE -// computations on same input with different S yield unrelated outputs. -// When N and S are both empty, this is equivalent to NewShake128. -func NewCShake128(N, S []byte) ShakeHash { - if len(N) == 0 && len(S) == 0 { - return NewShake128() - } - return newCShake(N, S, rate128, dsbyteCShake) -} - -// NewCShake256 creates a new instance of cSHAKE256 variable-output-length ShakeHash, -// a customizable variant of SHAKE256. -// N is used to define functions based on cSHAKE, it can be empty when plain cSHAKE is -// desired. S is a customization byte string used for domain separation - two cSHAKE -// computations on same input with different S yield unrelated outputs. -// When N and S are both empty, this is equivalent to NewShake256. -func NewCShake256(N, S []byte) ShakeHash { - if len(N) == 0 && len(S) == 0 { - return NewShake256() - } - return newCShake(N, S, rate256, dsbyteCShake) -} - -// ShakeSum128 writes an arbitrary-length digest of data into hash. -func ShakeSum128(hash, data []byte) { - h := NewShake128() - h.Write(data) - h.Read(hash) -} - -// ShakeSum256 writes an arbitrary-length digest of data into hash. -func ShakeSum256(hash, data []byte) { - h := NewShake256() - h.Write(data) - h.Read(hash) -} diff --git a/vendor/golang.org/x/crypto/sha3/shake_generic.go b/vendor/golang.org/x/crypto/sha3/shake_generic.go deleted file mode 100644 index 5c0710e..0000000 --- a/vendor/golang.org/x/crypto/sha3/shake_generic.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2017 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. - -//go:build !gc || purego || !s390x -// +build !gc purego !s390x - -package sha3 - -// newShake128Asm returns an assembly implementation of SHAKE-128 if available, -// otherwise it returns nil. -func newShake128Asm() ShakeHash { - return nil -} - -// newShake256Asm returns an assembly implementation of SHAKE-256 if available, -// otherwise it returns nil. -func newShake256Asm() ShakeHash { - return nil -} diff --git a/vendor/golang.org/x/crypto/sha3/xor.go b/vendor/golang.org/x/crypto/sha3/xor.go deleted file mode 100644 index 59c8eb9..0000000 --- a/vendor/golang.org/x/crypto/sha3/xor.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 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. - -//go:build (!amd64 && !386 && !ppc64le) || purego -// +build !amd64,!386,!ppc64le purego - -package sha3 - -// A storageBuf is an aligned array of maxRate bytes. -type storageBuf [maxRate]byte - -func (b *storageBuf) asBytes() *[maxRate]byte { - return (*[maxRate]byte)(b) -} - -var ( - xorIn = xorInGeneric - copyOut = copyOutGeneric - xorInUnaligned = xorInGeneric - copyOutUnaligned = copyOutGeneric -) - -const xorImplementationUnaligned = "generic" diff --git a/vendor/golang.org/x/crypto/sha3/xor_generic.go b/vendor/golang.org/x/crypto/sha3/xor_generic.go deleted file mode 100644 index 8d94771..0000000 --- a/vendor/golang.org/x/crypto/sha3/xor_generic.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2015 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 sha3 - -import "encoding/binary" - -// xorInGeneric xors the bytes in buf into the state; it -// makes no non-portable assumptions about memory layout -// or alignment. -func xorInGeneric(d *state, buf []byte) { - n := len(buf) / 8 - - for i := 0; i < n; i++ { - a := binary.LittleEndian.Uint64(buf) - d.a[i] ^= a - buf = buf[8:] - } -} - -// copyOutGeneric copies uint64s to a byte buffer. -func copyOutGeneric(d *state, b []byte) { - for i := 0; len(b) >= 8; i++ { - binary.LittleEndian.PutUint64(b, d.a[i]) - b = b[8:] - } -} diff --git a/vendor/golang.org/x/crypto/sha3/xor_unaligned.go b/vendor/golang.org/x/crypto/sha3/xor_unaligned.go deleted file mode 100644 index 1ce6062..0000000 --- a/vendor/golang.org/x/crypto/sha3/xor_unaligned.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 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. - -//go:build (amd64 || 386 || ppc64le) && !purego -// +build amd64 386 ppc64le -// +build !purego - -package sha3 - -import "unsafe" - -// A storageBuf is an aligned array of maxRate bytes. -type storageBuf [maxRate / 8]uint64 - -func (b *storageBuf) asBytes() *[maxRate]byte { - return (*[maxRate]byte)(unsafe.Pointer(b)) -} - -// xorInUnaligned uses unaligned reads and writes to update d.a to contain d.a -// XOR buf. -func xorInUnaligned(d *state, buf []byte) { - n := len(buf) - bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0]))[: n/8 : n/8] - if n >= 72 { - d.a[0] ^= bw[0] - d.a[1] ^= bw[1] - d.a[2] ^= bw[2] - d.a[3] ^= bw[3] - d.a[4] ^= bw[4] - d.a[5] ^= bw[5] - d.a[6] ^= bw[6] - d.a[7] ^= bw[7] - d.a[8] ^= bw[8] - } - if n >= 104 { - d.a[9] ^= bw[9] - d.a[10] ^= bw[10] - d.a[11] ^= bw[11] - d.a[12] ^= bw[12] - } - if n >= 136 { - d.a[13] ^= bw[13] - d.a[14] ^= bw[14] - d.a[15] ^= bw[15] - d.a[16] ^= bw[16] - } - if n >= 144 { - d.a[17] ^= bw[17] - } - if n >= 168 { - d.a[18] ^= bw[18] - d.a[19] ^= bw[19] - d.a[20] ^= bw[20] - } -} - -func copyOutUnaligned(d *state, buf []byte) { - ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0])) - copy(buf, ab[:]) -} - -var ( - xorIn = xorInUnaligned - copyOut = copyOutUnaligned -) - -const xorImplementationUnaligned = "unaligned" diff --git a/vendor/golang.org/x/sys/LICENSE b/vendor/golang.org/x/sys/LICENSE deleted file mode 100644 index 6a66aea..0000000 --- a/vendor/golang.org/x/sys/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 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/golang.org/x/sys/PATENTS b/vendor/golang.org/x/sys/PATENTS deleted file mode 100644 index 7330990..0000000 --- a/vendor/golang.org/x/sys/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s b/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s deleted file mode 100644 index db9171c..0000000 --- a/vendor/golang.org/x/sys/cpu/asm_aix_ppc64.s +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018 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. - -//go:build gc -// +build gc - -#include "textflag.h" - -// -// System calls for ppc64, AIX are implemented in runtime/syscall_aix.go -// - -TEXT ·syscall6(SB),NOSPLIT,$0-88 - JMP syscall·syscall6(SB) - -TEXT ·rawSyscall6(SB),NOSPLIT,$0-88 - JMP syscall·rawSyscall6(SB) diff --git a/vendor/golang.org/x/sys/cpu/byteorder.go b/vendor/golang.org/x/sys/cpu/byteorder.go deleted file mode 100644 index 271055b..0000000 --- a/vendor/golang.org/x/sys/cpu/byteorder.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2019 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 cpu - -import ( - "runtime" -) - -// byteOrder is a subset of encoding/binary.ByteOrder. -type byteOrder interface { - Uint32([]byte) uint32 - Uint64([]byte) uint64 -} - -type littleEndian struct{} -type bigEndian struct{} - -func (littleEndian) Uint32(b []byte) uint32 { - _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func (littleEndian) Uint64(b []byte) uint64 { - _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -func (bigEndian) Uint32(b []byte) uint32 { - _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 - return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 -} - -func (bigEndian) Uint64(b []byte) uint64 { - _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | - uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 -} - -// hostByteOrder returns littleEndian on little-endian machines and -// bigEndian on big-endian machines. -func hostByteOrder() byteOrder { - switch runtime.GOARCH { - case "386", "amd64", "amd64p32", - "alpha", - "arm", "arm64", - "loong64", - "mipsle", "mips64le", "mips64p32le", - "nios2", - "ppc64le", - "riscv", "riscv64", - "sh": - return littleEndian{} - case "armbe", "arm64be", - "m68k", - "mips", "mips64", "mips64p32", - "ppc", "ppc64", - "s390", "s390x", - "shbe", - "sparc", "sparc64": - return bigEndian{} - } - panic("unknown architecture") -} diff --git a/vendor/golang.org/x/sys/cpu/cpu.go b/vendor/golang.org/x/sys/cpu/cpu.go deleted file mode 100644 index 83f112c..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu.go +++ /dev/null @@ -1,287 +0,0 @@ -// Copyright 2018 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 cpu implements processor feature detection for -// various CPU architectures. -package cpu - -import ( - "os" - "strings" -) - -// Initialized reports whether the CPU features were initialized. -// -// For some GOOS/GOARCH combinations initialization of the CPU features depends -// on reading an operating specific file, e.g. /proc/self/auxv on linux/arm -// Initialized will report false if reading the file fails. -var Initialized bool - -// CacheLinePad is used to pad structs to avoid false sharing. -type CacheLinePad struct{ _ [cacheLineSize]byte } - -// X86 contains the supported CPU features of the -// current X86/AMD64 platform. If the current platform -// is not X86/AMD64 then all feature flags are false. -// -// X86 is padded to avoid false sharing. Further the HasAVX -// and HasAVX2 are only set if the OS supports XMM and YMM -// registers in addition to the CPUID feature bit being set. -var X86 struct { - _ CacheLinePad - HasAES bool // AES hardware implementation (AES NI) - HasADX bool // Multi-precision add-carry instruction extensions - HasAVX bool // Advanced vector extension - HasAVX2 bool // Advanced vector extension 2 - HasAVX512 bool // Advanced vector extension 512 - HasAVX512F bool // Advanced vector extension 512 Foundation Instructions - HasAVX512CD bool // Advanced vector extension 512 Conflict Detection Instructions - HasAVX512ER bool // Advanced vector extension 512 Exponential and Reciprocal Instructions - HasAVX512PF bool // Advanced vector extension 512 Prefetch Instructions Instructions - HasAVX512VL bool // Advanced vector extension 512 Vector Length Extensions - HasAVX512BW bool // Advanced vector extension 512 Byte and Word Instructions - HasAVX512DQ bool // Advanced vector extension 512 Doubleword and Quadword Instructions - HasAVX512IFMA bool // Advanced vector extension 512 Integer Fused Multiply Add - HasAVX512VBMI bool // Advanced vector extension 512 Vector Byte Manipulation Instructions - HasAVX5124VNNIW bool // Advanced vector extension 512 Vector Neural Network Instructions Word variable precision - HasAVX5124FMAPS bool // Advanced vector extension 512 Fused Multiply Accumulation Packed Single precision - HasAVX512VPOPCNTDQ bool // Advanced vector extension 512 Double and quad word population count instructions - HasAVX512VPCLMULQDQ bool // Advanced vector extension 512 Vector carry-less multiply operations - HasAVX512VNNI bool // Advanced vector extension 512 Vector Neural Network Instructions - HasAVX512GFNI bool // Advanced vector extension 512 Galois field New Instructions - HasAVX512VAES bool // Advanced vector extension 512 Vector AES instructions - HasAVX512VBMI2 bool // Advanced vector extension 512 Vector Byte Manipulation Instructions 2 - HasAVX512BITALG bool // Advanced vector extension 512 Bit Algorithms - HasAVX512BF16 bool // Advanced vector extension 512 BFloat16 Instructions - HasBMI1 bool // Bit manipulation instruction set 1 - HasBMI2 bool // Bit manipulation instruction set 2 - HasCX16 bool // Compare and exchange 16 Bytes - HasERMS bool // Enhanced REP for MOVSB and STOSB - HasFMA bool // Fused-multiply-add instructions - HasOSXSAVE bool // OS supports XSAVE/XRESTOR for saving/restoring XMM registers. - HasPCLMULQDQ bool // PCLMULQDQ instruction - most often used for AES-GCM - HasPOPCNT bool // Hamming weight instruction POPCNT. - HasRDRAND bool // RDRAND instruction (on-chip random number generator) - HasRDSEED bool // RDSEED instruction (on-chip random number generator) - HasSSE2 bool // Streaming SIMD extension 2 (always available on amd64) - HasSSE3 bool // Streaming SIMD extension 3 - HasSSSE3 bool // Supplemental streaming SIMD extension 3 - HasSSE41 bool // Streaming SIMD extension 4 and 4.1 - HasSSE42 bool // Streaming SIMD extension 4 and 4.2 - _ CacheLinePad -} - -// ARM64 contains the supported CPU features of the -// current ARMv8(aarch64) platform. If the current platform -// is not arm64 then all feature flags are false. -var ARM64 struct { - _ CacheLinePad - HasFP bool // Floating-point instruction set (always available) - HasASIMD bool // Advanced SIMD (always available) - HasEVTSTRM bool // Event stream support - HasAES bool // AES hardware implementation - HasPMULL bool // Polynomial multiplication instruction set - HasSHA1 bool // SHA1 hardware implementation - HasSHA2 bool // SHA2 hardware implementation - HasCRC32 bool // CRC32 hardware implementation - HasATOMICS bool // Atomic memory operation instruction set - HasFPHP bool // Half precision floating-point instruction set - HasASIMDHP bool // Advanced SIMD half precision instruction set - HasCPUID bool // CPUID identification scheme registers - HasASIMDRDM bool // Rounding double multiply add/subtract instruction set - HasJSCVT bool // Javascript conversion from floating-point to integer - HasFCMA bool // Floating-point multiplication and addition of complex numbers - HasLRCPC bool // Release Consistent processor consistent support - HasDCPOP bool // Persistent memory support - HasSHA3 bool // SHA3 hardware implementation - HasSM3 bool // SM3 hardware implementation - HasSM4 bool // SM4 hardware implementation - HasASIMDDP bool // Advanced SIMD double precision instruction set - HasSHA512 bool // SHA512 hardware implementation - HasSVE bool // Scalable Vector Extensions - HasASIMDFHM bool // Advanced SIMD multiplication FP16 to FP32 - _ CacheLinePad -} - -// ARM contains the supported CPU features of the current ARM (32-bit) platform. -// All feature flags are false if: -// 1. the current platform is not arm, or -// 2. the current operating system is not Linux. -var ARM struct { - _ CacheLinePad - HasSWP bool // SWP instruction support - HasHALF bool // Half-word load and store support - HasTHUMB bool // ARM Thumb instruction set - Has26BIT bool // Address space limited to 26-bits - HasFASTMUL bool // 32-bit operand, 64-bit result multiplication support - HasFPA bool // Floating point arithmetic support - HasVFP bool // Vector floating point support - HasEDSP bool // DSP Extensions support - HasJAVA bool // Java instruction set - HasIWMMXT bool // Intel Wireless MMX technology support - HasCRUNCH bool // MaverickCrunch context switching and handling - HasTHUMBEE bool // Thumb EE instruction set - HasNEON bool // NEON instruction set - HasVFPv3 bool // Vector floating point version 3 support - HasVFPv3D16 bool // Vector floating point version 3 D8-D15 - HasTLS bool // Thread local storage support - HasVFPv4 bool // Vector floating point version 4 support - HasIDIVA bool // Integer divide instruction support in ARM mode - HasIDIVT bool // Integer divide instruction support in Thumb mode - HasVFPD32 bool // Vector floating point version 3 D15-D31 - HasLPAE bool // Large Physical Address Extensions - HasEVTSTRM bool // Event stream support - HasAES bool // AES hardware implementation - HasPMULL bool // Polynomial multiplication instruction set - HasSHA1 bool // SHA1 hardware implementation - HasSHA2 bool // SHA2 hardware implementation - HasCRC32 bool // CRC32 hardware implementation - _ CacheLinePad -} - -// MIPS64X contains the supported CPU features of the current mips64/mips64le -// platforms. If the current platform is not mips64/mips64le or the current -// operating system is not Linux then all feature flags are false. -var MIPS64X struct { - _ CacheLinePad - HasMSA bool // MIPS SIMD architecture - _ CacheLinePad -} - -// PPC64 contains the supported CPU features of the current ppc64/ppc64le platforms. -// If the current platform is not ppc64/ppc64le then all feature flags are false. -// -// For ppc64/ppc64le, it is safe to check only for ISA level starting on ISA v3.00, -// since there are no optional categories. There are some exceptions that also -// require kernel support to work (DARN, SCV), so there are feature bits for -// those as well. The struct is padded to avoid false sharing. -var PPC64 struct { - _ CacheLinePad - HasDARN bool // Hardware random number generator (requires kernel enablement) - HasSCV bool // Syscall vectored (requires kernel enablement) - IsPOWER8 bool // ISA v2.07 (POWER8) - IsPOWER9 bool // ISA v3.00 (POWER9), implies IsPOWER8 - _ CacheLinePad -} - -// S390X contains the supported CPU features of the current IBM Z -// (s390x) platform. If the current platform is not IBM Z then all -// feature flags are false. -// -// S390X is padded to avoid false sharing. Further HasVX is only set -// if the OS supports vector registers in addition to the STFLE -// feature bit being set. -var S390X struct { - _ CacheLinePad - HasZARCH bool // z/Architecture mode is active [mandatory] - HasSTFLE bool // store facility list extended - HasLDISP bool // long (20-bit) displacements - HasEIMM bool // 32-bit immediates - HasDFP bool // decimal floating point - HasETF3EH bool // ETF-3 enhanced - HasMSA bool // message security assist (CPACF) - HasAES bool // KM-AES{128,192,256} functions - HasAESCBC bool // KMC-AES{128,192,256} functions - HasAESCTR bool // KMCTR-AES{128,192,256} functions - HasAESGCM bool // KMA-GCM-AES{128,192,256} functions - HasGHASH bool // KIMD-GHASH function - HasSHA1 bool // K{I,L}MD-SHA-1 functions - HasSHA256 bool // K{I,L}MD-SHA-256 functions - HasSHA512 bool // K{I,L}MD-SHA-512 functions - HasSHA3 bool // K{I,L}MD-SHA3-{224,256,384,512} and K{I,L}MD-SHAKE-{128,256} functions - HasVX bool // vector facility - HasVXE bool // vector-enhancements facility 1 - _ CacheLinePad -} - -func init() { - archInit() - initOptions() - processOptions() -} - -// options contains the cpu debug options that can be used in GODEBUG. -// Options are arch dependent and are added by the arch specific initOptions functions. -// Features that are mandatory for the specific GOARCH should have the Required field set -// (e.g. SSE2 on amd64). -var options []option - -// Option names should be lower case. e.g. avx instead of AVX. -type option struct { - Name string - Feature *bool - Specified bool // whether feature value was specified in GODEBUG - Enable bool // whether feature should be enabled - Required bool // whether feature is mandatory and can not be disabled -} - -func processOptions() { - env := os.Getenv("GODEBUG") -field: - for env != "" { - field := "" - i := strings.IndexByte(env, ',') - if i < 0 { - field, env = env, "" - } else { - field, env = env[:i], env[i+1:] - } - if len(field) < 4 || field[:4] != "cpu." { - continue - } - i = strings.IndexByte(field, '=') - if i < 0 { - print("GODEBUG sys/cpu: no value specified for \"", field, "\"\n") - continue - } - key, value := field[4:i], field[i+1:] // e.g. "SSE2", "on" - - var enable bool - switch value { - case "on": - enable = true - case "off": - enable = false - default: - print("GODEBUG sys/cpu: value \"", value, "\" not supported for cpu option \"", key, "\"\n") - continue field - } - - if key == "all" { - for i := range options { - options[i].Specified = true - options[i].Enable = enable || options[i].Required - } - continue field - } - - for i := range options { - if options[i].Name == key { - options[i].Specified = true - options[i].Enable = enable - continue field - } - } - - print("GODEBUG sys/cpu: unknown cpu feature \"", key, "\"\n") - } - - for _, o := range options { - if !o.Specified { - continue - } - - if o.Enable && !*o.Feature { - print("GODEBUG sys/cpu: can not enable \"", o.Name, "\", missing CPU support\n") - continue - } - - if !o.Enable && o.Required { - print("GODEBUG sys/cpu: can not disable \"", o.Name, "\", required CPU feature\n") - continue - } - - *o.Feature = o.Enable - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_aix.go b/vendor/golang.org/x/sys/cpu/cpu_aix.go deleted file mode 100644 index 8aaeef5..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_aix.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2019 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. - -//go:build aix -// +build aix - -package cpu - -const ( - // getsystemcfg constants - _SC_IMPL = 2 - _IMPL_POWER8 = 0x10000 - _IMPL_POWER9 = 0x20000 -) - -func archInit() { - impl := getsystemcfg(_SC_IMPL) - if impl&_IMPL_POWER8 != 0 { - PPC64.IsPOWER8 = true - } - if impl&_IMPL_POWER9 != 0 { - PPC64.IsPOWER8 = true - PPC64.IsPOWER9 = true - } - - Initialized = true -} - -func getsystemcfg(label int) (n uint64) { - r0, _ := callgetsystemcfg(label) - n = uint64(r0) - return -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm.go b/vendor/golang.org/x/sys/cpu/cpu_arm.go deleted file mode 100644 index 301b752..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_arm.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2018 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 cpu - -const cacheLineSize = 32 - -// HWCAP/HWCAP2 bits. -// These are specific to Linux. -const ( - hwcap_SWP = 1 << 0 - hwcap_HALF = 1 << 1 - hwcap_THUMB = 1 << 2 - hwcap_26BIT = 1 << 3 - hwcap_FAST_MULT = 1 << 4 - hwcap_FPA = 1 << 5 - hwcap_VFP = 1 << 6 - hwcap_EDSP = 1 << 7 - hwcap_JAVA = 1 << 8 - hwcap_IWMMXT = 1 << 9 - hwcap_CRUNCH = 1 << 10 - hwcap_THUMBEE = 1 << 11 - hwcap_NEON = 1 << 12 - hwcap_VFPv3 = 1 << 13 - hwcap_VFPv3D16 = 1 << 14 - hwcap_TLS = 1 << 15 - hwcap_VFPv4 = 1 << 16 - hwcap_IDIVA = 1 << 17 - hwcap_IDIVT = 1 << 18 - hwcap_VFPD32 = 1 << 19 - hwcap_LPAE = 1 << 20 - hwcap_EVTSTRM = 1 << 21 - - hwcap2_AES = 1 << 0 - hwcap2_PMULL = 1 << 1 - hwcap2_SHA1 = 1 << 2 - hwcap2_SHA2 = 1 << 3 - hwcap2_CRC32 = 1 << 4 -) - -func initOptions() { - options = []option{ - {Name: "pmull", Feature: &ARM.HasPMULL}, - {Name: "sha1", Feature: &ARM.HasSHA1}, - {Name: "sha2", Feature: &ARM.HasSHA2}, - {Name: "swp", Feature: &ARM.HasSWP}, - {Name: "thumb", Feature: &ARM.HasTHUMB}, - {Name: "thumbee", Feature: &ARM.HasTHUMBEE}, - {Name: "tls", Feature: &ARM.HasTLS}, - {Name: "vfp", Feature: &ARM.HasVFP}, - {Name: "vfpd32", Feature: &ARM.HasVFPD32}, - {Name: "vfpv3", Feature: &ARM.HasVFPv3}, - {Name: "vfpv3d16", Feature: &ARM.HasVFPv3D16}, - {Name: "vfpv4", Feature: &ARM.HasVFPv4}, - {Name: "half", Feature: &ARM.HasHALF}, - {Name: "26bit", Feature: &ARM.Has26BIT}, - {Name: "fastmul", Feature: &ARM.HasFASTMUL}, - {Name: "fpa", Feature: &ARM.HasFPA}, - {Name: "edsp", Feature: &ARM.HasEDSP}, - {Name: "java", Feature: &ARM.HasJAVA}, - {Name: "iwmmxt", Feature: &ARM.HasIWMMXT}, - {Name: "crunch", Feature: &ARM.HasCRUNCH}, - {Name: "neon", Feature: &ARM.HasNEON}, - {Name: "idivt", Feature: &ARM.HasIDIVT}, - {Name: "idiva", Feature: &ARM.HasIDIVA}, - {Name: "lpae", Feature: &ARM.HasLPAE}, - {Name: "evtstrm", Feature: &ARM.HasEVTSTRM}, - {Name: "aes", Feature: &ARM.HasAES}, - {Name: "crc32", Feature: &ARM.HasCRC32}, - } - -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_arm64.go deleted file mode 100644 index f3eb993..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2019 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 cpu - -import "runtime" - -// cacheLineSize is used to prevent false sharing of cache lines. -// We choose 128 because Apple Silicon, a.k.a. M1, has 128-byte cache line size. -// It doesn't cost much and is much more future-proof. -const cacheLineSize = 128 - -func initOptions() { - options = []option{ - {Name: "fp", Feature: &ARM64.HasFP}, - {Name: "asimd", Feature: &ARM64.HasASIMD}, - {Name: "evstrm", Feature: &ARM64.HasEVTSTRM}, - {Name: "aes", Feature: &ARM64.HasAES}, - {Name: "fphp", Feature: &ARM64.HasFPHP}, - {Name: "jscvt", Feature: &ARM64.HasJSCVT}, - {Name: "lrcpc", Feature: &ARM64.HasLRCPC}, - {Name: "pmull", Feature: &ARM64.HasPMULL}, - {Name: "sha1", Feature: &ARM64.HasSHA1}, - {Name: "sha2", Feature: &ARM64.HasSHA2}, - {Name: "sha3", Feature: &ARM64.HasSHA3}, - {Name: "sha512", Feature: &ARM64.HasSHA512}, - {Name: "sm3", Feature: &ARM64.HasSM3}, - {Name: "sm4", Feature: &ARM64.HasSM4}, - {Name: "sve", Feature: &ARM64.HasSVE}, - {Name: "crc32", Feature: &ARM64.HasCRC32}, - {Name: "atomics", Feature: &ARM64.HasATOMICS}, - {Name: "asimdhp", Feature: &ARM64.HasASIMDHP}, - {Name: "cpuid", Feature: &ARM64.HasCPUID}, - {Name: "asimrdm", Feature: &ARM64.HasASIMDRDM}, - {Name: "fcma", Feature: &ARM64.HasFCMA}, - {Name: "dcpop", Feature: &ARM64.HasDCPOP}, - {Name: "asimddp", Feature: &ARM64.HasASIMDDP}, - {Name: "asimdfhm", Feature: &ARM64.HasASIMDFHM}, - } -} - -func archInit() { - switch runtime.GOOS { - case "freebsd": - readARM64Registers() - case "linux", "netbsd", "openbsd": - doinit() - default: - // Many platforms don't seem to allow reading these registers. - setMinimalFeatures() - } -} - -// setMinimalFeatures fakes the minimal ARM64 features expected by -// TestARM64minimalFeatures. -func setMinimalFeatures() { - ARM64.HasASIMD = true - ARM64.HasFP = true -} - -func readARM64Registers() { - Initialized = true - - parseARM64SystemRegisters(getisar0(), getisar1(), getpfr0()) -} - -func parseARM64SystemRegisters(isar0, isar1, pfr0 uint64) { - // ID_AA64ISAR0_EL1 - switch extractBits(isar0, 4, 7) { - case 1: - ARM64.HasAES = true - case 2: - ARM64.HasAES = true - ARM64.HasPMULL = true - } - - switch extractBits(isar0, 8, 11) { - case 1: - ARM64.HasSHA1 = true - } - - switch extractBits(isar0, 12, 15) { - case 1: - ARM64.HasSHA2 = true - case 2: - ARM64.HasSHA2 = true - ARM64.HasSHA512 = true - } - - switch extractBits(isar0, 16, 19) { - case 1: - ARM64.HasCRC32 = true - } - - switch extractBits(isar0, 20, 23) { - case 2: - ARM64.HasATOMICS = true - } - - switch extractBits(isar0, 28, 31) { - case 1: - ARM64.HasASIMDRDM = true - } - - switch extractBits(isar0, 32, 35) { - case 1: - ARM64.HasSHA3 = true - } - - switch extractBits(isar0, 36, 39) { - case 1: - ARM64.HasSM3 = true - } - - switch extractBits(isar0, 40, 43) { - case 1: - ARM64.HasSM4 = true - } - - switch extractBits(isar0, 44, 47) { - case 1: - ARM64.HasASIMDDP = true - } - - // ID_AA64ISAR1_EL1 - switch extractBits(isar1, 0, 3) { - case 1: - ARM64.HasDCPOP = true - } - - switch extractBits(isar1, 12, 15) { - case 1: - ARM64.HasJSCVT = true - } - - switch extractBits(isar1, 16, 19) { - case 1: - ARM64.HasFCMA = true - } - - switch extractBits(isar1, 20, 23) { - case 1: - ARM64.HasLRCPC = true - } - - // ID_AA64PFR0_EL1 - switch extractBits(pfr0, 16, 19) { - case 0: - ARM64.HasFP = true - case 1: - ARM64.HasFP = true - ARM64.HasFPHP = true - } - - switch extractBits(pfr0, 20, 23) { - case 0: - ARM64.HasASIMD = true - case 1: - ARM64.HasASIMD = true - ARM64.HasASIMDHP = true - } - - switch extractBits(pfr0, 32, 35) { - case 1: - ARM64.HasSVE = true - } -} - -func extractBits(data uint64, start, end uint) uint { - return (uint)(data>>start) & ((1 << (end - start + 1)) - 1) -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_arm64.s b/vendor/golang.org/x/sys/cpu/cpu_arm64.s deleted file mode 100644 index c61f95a..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_arm64.s +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2019 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. - -//go:build gc -// +build gc - -#include "textflag.h" - -// func getisar0() uint64 -TEXT ·getisar0(SB),NOSPLIT,$0-8 - // get Instruction Set Attributes 0 into x0 - // mrs x0, ID_AA64ISAR0_EL1 = d5380600 - WORD $0xd5380600 - MOVD R0, ret+0(FP) - RET - -// func getisar1() uint64 -TEXT ·getisar1(SB),NOSPLIT,$0-8 - // get Instruction Set Attributes 1 into x0 - // mrs x0, ID_AA64ISAR1_EL1 = d5380620 - WORD $0xd5380620 - MOVD R0, ret+0(FP) - RET - -// func getpfr0() uint64 -TEXT ·getpfr0(SB),NOSPLIT,$0-8 - // get Processor Feature Register 0 into x0 - // mrs x0, ID_AA64PFR0_EL1 = d5380400 - WORD $0xd5380400 - MOVD R0, ret+0(FP) - RET diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go deleted file mode 100644 index ccf542a..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2019 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. - -//go:build gc -// +build gc - -package cpu - -func getisar0() uint64 -func getisar1() uint64 -func getpfr0() uint64 diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go deleted file mode 100644 index 0af2f24..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_s390x.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright 2019 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. - -//go:build gc -// +build gc - -package cpu - -// haveAsmFunctions reports whether the other functions in this file can -// be safely called. -func haveAsmFunctions() bool { return true } - -// The following feature detection functions are defined in cpu_s390x.s. -// They are likely to be expensive to call so the results should be cached. -func stfle() facilityList -func kmQuery() queryResult -func kmcQuery() queryResult -func kmctrQuery() queryResult -func kmaQuery() queryResult -func kimdQuery() queryResult -func klmdQuery() queryResult diff --git a/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go b/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go deleted file mode 100644 index fa7cdb9..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gc_x86.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018 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. - -//go:build (386 || amd64 || amd64p32) && gc -// +build 386 amd64 amd64p32 -// +build gc - -package cpu - -// cpuid is implemented in cpu_x86.s for gc compiler -// and in cpu_gccgo.c for gccgo. -func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) - -// xgetbv with ecx = 0 is implemented in cpu_x86.s for gc compiler -// and in cpu_gccgo.c for gccgo. -func xgetbv() (eax, edx uint32) diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go deleted file mode 100644 index 2aff318..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_arm64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2019 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. - -//go:build gccgo -// +build gccgo - -package cpu - -func getisar0() uint64 { return 0 } -func getisar1() uint64 { return 0 } -func getpfr0() uint64 { return 0 } diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go deleted file mode 100644 index 4bfbda6..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_s390x.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2019 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. - -//go:build gccgo -// +build gccgo - -package cpu - -// haveAsmFunctions reports whether the other functions in this file can -// be safely called. -func haveAsmFunctions() bool { return false } - -// TODO(mundaym): the following feature detection functions are currently -// stubs. See https://golang.org/cl/162887 for how to fix this. -// They are likely to be expensive to call so the results should be cached. -func stfle() facilityList { panic("not implemented for gccgo") } -func kmQuery() queryResult { panic("not implemented for gccgo") } -func kmcQuery() queryResult { panic("not implemented for gccgo") } -func kmctrQuery() queryResult { panic("not implemented for gccgo") } -func kmaQuery() queryResult { panic("not implemented for gccgo") } -func kimdQuery() queryResult { panic("not implemented for gccgo") } -func klmdQuery() queryResult { panic("not implemented for gccgo") } diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c b/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c deleted file mode 100644 index a4605e6..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.c +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2018 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. - -// +build 386 amd64 amd64p32 -// +build gccgo - -#include -#include -#include - -// Need to wrap __get_cpuid_count because it's declared as static. -int -gccgoGetCpuidCount(uint32_t leaf, uint32_t subleaf, - uint32_t *eax, uint32_t *ebx, - uint32_t *ecx, uint32_t *edx) -{ - return __get_cpuid_count(leaf, subleaf, eax, ebx, ecx, edx); -} - -#pragma GCC diagnostic ignored "-Wunknown-pragmas" -#pragma GCC push_options -#pragma GCC target("xsave") -#pragma clang attribute push (__attribute__((target("xsave"))), apply_to=function) - -// xgetbv reads the contents of an XCR (Extended Control Register) -// specified in the ECX register into registers EDX:EAX. -// Currently, the only supported value for XCR is 0. -void -gccgoXgetbv(uint32_t *eax, uint32_t *edx) -{ - uint64_t v = _xgetbv(0); - *eax = v & 0xffffffff; - *edx = v >> 32; -} - -#pragma clang attribute pop -#pragma GCC pop_options diff --git a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go b/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go deleted file mode 100644 index 863d415..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_gccgo_x86.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2018 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. - -//go:build (386 || amd64 || amd64p32) && gccgo -// +build 386 amd64 amd64p32 -// +build gccgo - -package cpu - -//extern gccgoGetCpuidCount -func gccgoGetCpuidCount(eaxArg, ecxArg uint32, eax, ebx, ecx, edx *uint32) - -func cpuid(eaxArg, ecxArg uint32) (eax, ebx, ecx, edx uint32) { - var a, b, c, d uint32 - gccgoGetCpuidCount(eaxArg, ecxArg, &a, &b, &c, &d) - return a, b, c, d -} - -//extern gccgoXgetbv -func gccgoXgetbv(eax, edx *uint32) - -func xgetbv() (eax, edx uint32) { - var a, d uint32 - gccgoXgetbv(&a, &d) - return a, d -} - -// gccgo doesn't build on Darwin, per: -// https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/gcc.rb#L76 -func darwinSupportsAVX512() bool { - return false -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux.go b/vendor/golang.org/x/sys/cpu/cpu_linux.go deleted file mode 100644 index 159a686..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 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. - -//go:build !386 && !amd64 && !amd64p32 && !arm64 -// +build !386,!amd64,!amd64p32,!arm64 - -package cpu - -func archInit() { - if err := readHWCAP(); err != nil { - return - } - doinit() - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go b/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go deleted file mode 100644 index 2057006..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_arm.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2019 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 cpu - -func doinit() { - ARM.HasSWP = isSet(hwCap, hwcap_SWP) - ARM.HasHALF = isSet(hwCap, hwcap_HALF) - ARM.HasTHUMB = isSet(hwCap, hwcap_THUMB) - ARM.Has26BIT = isSet(hwCap, hwcap_26BIT) - ARM.HasFASTMUL = isSet(hwCap, hwcap_FAST_MULT) - ARM.HasFPA = isSet(hwCap, hwcap_FPA) - ARM.HasVFP = isSet(hwCap, hwcap_VFP) - ARM.HasEDSP = isSet(hwCap, hwcap_EDSP) - ARM.HasJAVA = isSet(hwCap, hwcap_JAVA) - ARM.HasIWMMXT = isSet(hwCap, hwcap_IWMMXT) - ARM.HasCRUNCH = isSet(hwCap, hwcap_CRUNCH) - ARM.HasTHUMBEE = isSet(hwCap, hwcap_THUMBEE) - ARM.HasNEON = isSet(hwCap, hwcap_NEON) - ARM.HasVFPv3 = isSet(hwCap, hwcap_VFPv3) - ARM.HasVFPv3D16 = isSet(hwCap, hwcap_VFPv3D16) - ARM.HasTLS = isSet(hwCap, hwcap_TLS) - ARM.HasVFPv4 = isSet(hwCap, hwcap_VFPv4) - ARM.HasIDIVA = isSet(hwCap, hwcap_IDIVA) - ARM.HasIDIVT = isSet(hwCap, hwcap_IDIVT) - ARM.HasVFPD32 = isSet(hwCap, hwcap_VFPD32) - ARM.HasLPAE = isSet(hwCap, hwcap_LPAE) - ARM.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) - ARM.HasAES = isSet(hwCap2, hwcap2_AES) - ARM.HasPMULL = isSet(hwCap2, hwcap2_PMULL) - ARM.HasSHA1 = isSet(hwCap2, hwcap2_SHA1) - ARM.HasSHA2 = isSet(hwCap2, hwcap2_SHA2) - ARM.HasCRC32 = isSet(hwCap2, hwcap2_CRC32) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go deleted file mode 100644 index 79a38a0..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_arm64.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2018 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 cpu - -// HWCAP/HWCAP2 bits. These are exposed by Linux. -const ( - hwcap_FP = 1 << 0 - hwcap_ASIMD = 1 << 1 - hwcap_EVTSTRM = 1 << 2 - hwcap_AES = 1 << 3 - hwcap_PMULL = 1 << 4 - hwcap_SHA1 = 1 << 5 - hwcap_SHA2 = 1 << 6 - hwcap_CRC32 = 1 << 7 - hwcap_ATOMICS = 1 << 8 - hwcap_FPHP = 1 << 9 - hwcap_ASIMDHP = 1 << 10 - hwcap_CPUID = 1 << 11 - hwcap_ASIMDRDM = 1 << 12 - hwcap_JSCVT = 1 << 13 - hwcap_FCMA = 1 << 14 - hwcap_LRCPC = 1 << 15 - hwcap_DCPOP = 1 << 16 - hwcap_SHA3 = 1 << 17 - hwcap_SM3 = 1 << 18 - hwcap_SM4 = 1 << 19 - hwcap_ASIMDDP = 1 << 20 - hwcap_SHA512 = 1 << 21 - hwcap_SVE = 1 << 22 - hwcap_ASIMDFHM = 1 << 23 -) - -func doinit() { - if err := readHWCAP(); err != nil { - // failed to read /proc/self/auxv, try reading registers directly - readARM64Registers() - return - } - - // HWCAP feature bits - ARM64.HasFP = isSet(hwCap, hwcap_FP) - ARM64.HasASIMD = isSet(hwCap, hwcap_ASIMD) - ARM64.HasEVTSTRM = isSet(hwCap, hwcap_EVTSTRM) - ARM64.HasAES = isSet(hwCap, hwcap_AES) - ARM64.HasPMULL = isSet(hwCap, hwcap_PMULL) - ARM64.HasSHA1 = isSet(hwCap, hwcap_SHA1) - ARM64.HasSHA2 = isSet(hwCap, hwcap_SHA2) - ARM64.HasCRC32 = isSet(hwCap, hwcap_CRC32) - ARM64.HasATOMICS = isSet(hwCap, hwcap_ATOMICS) - ARM64.HasFPHP = isSet(hwCap, hwcap_FPHP) - ARM64.HasASIMDHP = isSet(hwCap, hwcap_ASIMDHP) - ARM64.HasCPUID = isSet(hwCap, hwcap_CPUID) - ARM64.HasASIMDRDM = isSet(hwCap, hwcap_ASIMDRDM) - ARM64.HasJSCVT = isSet(hwCap, hwcap_JSCVT) - ARM64.HasFCMA = isSet(hwCap, hwcap_FCMA) - ARM64.HasLRCPC = isSet(hwCap, hwcap_LRCPC) - ARM64.HasDCPOP = isSet(hwCap, hwcap_DCPOP) - ARM64.HasSHA3 = isSet(hwCap, hwcap_SHA3) - ARM64.HasSM3 = isSet(hwCap, hwcap_SM3) - ARM64.HasSM4 = isSet(hwCap, hwcap_SM4) - ARM64.HasASIMDDP = isSet(hwCap, hwcap_ASIMDDP) - ARM64.HasSHA512 = isSet(hwCap, hwcap_SHA512) - ARM64.HasSVE = isSet(hwCap, hwcap_SVE) - ARM64.HasASIMDFHM = isSet(hwCap, hwcap_ASIMDFHM) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go deleted file mode 100644 index 6000db4..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_mips64x.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2020 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. - -//go:build linux && (mips64 || mips64le) -// +build linux -// +build mips64 mips64le - -package cpu - -// HWCAP bits. These are exposed by the Linux kernel 5.4. -const ( - // CPU features - hwcap_MIPS_MSA = 1 << 1 -) - -func doinit() { - // HWCAP feature bits - MIPS64X.HasMSA = isSet(hwCap, hwcap_MIPS_MSA) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go b/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go deleted file mode 100644 index f4992b1..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_noinit.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2019 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. - -//go:build linux && !arm && !arm64 && !mips64 && !mips64le && !ppc64 && !ppc64le && !s390x -// +build linux,!arm,!arm64,!mips64,!mips64le,!ppc64,!ppc64le,!s390x - -package cpu - -func doinit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go deleted file mode 100644 index 021356d..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_ppc64x.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2018 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. - -//go:build linux && (ppc64 || ppc64le) -// +build linux -// +build ppc64 ppc64le - -package cpu - -// HWCAP/HWCAP2 bits. These are exposed by the kernel. -const ( - // ISA Level - _PPC_FEATURE2_ARCH_2_07 = 0x80000000 - _PPC_FEATURE2_ARCH_3_00 = 0x00800000 - - // CPU features - _PPC_FEATURE2_DARN = 0x00200000 - _PPC_FEATURE2_SCV = 0x00100000 -) - -func doinit() { - // HWCAP2 feature bits - PPC64.IsPOWER8 = isSet(hwCap2, _PPC_FEATURE2_ARCH_2_07) - PPC64.IsPOWER9 = isSet(hwCap2, _PPC_FEATURE2_ARCH_3_00) - PPC64.HasDARN = isSet(hwCap2, _PPC_FEATURE2_DARN) - PPC64.HasSCV = isSet(hwCap2, _PPC_FEATURE2_SCV) -} - -func isSet(hwc uint, value uint) bool { - return hwc&value != 0 -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go deleted file mode 100644 index 1517ac6..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_linux_s390x.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2019 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 cpu - -const ( - // bit mask values from /usr/include/bits/hwcap.h - hwcap_ZARCH = 2 - hwcap_STFLE = 4 - hwcap_MSA = 8 - hwcap_LDISP = 16 - hwcap_EIMM = 32 - hwcap_DFP = 64 - hwcap_ETF3EH = 256 - hwcap_VX = 2048 - hwcap_VXE = 8192 -) - -func initS390Xbase() { - // test HWCAP bit vector - has := func(featureMask uint) bool { - return hwCap&featureMask == featureMask - } - - // mandatory - S390X.HasZARCH = has(hwcap_ZARCH) - - // optional - S390X.HasSTFLE = has(hwcap_STFLE) - S390X.HasLDISP = has(hwcap_LDISP) - S390X.HasEIMM = has(hwcap_EIMM) - S390X.HasETF3EH = has(hwcap_ETF3EH) - S390X.HasDFP = has(hwcap_DFP) - S390X.HasMSA = has(hwcap_MSA) - S390X.HasVX = has(hwcap_VX) - if S390X.HasVX { - S390X.HasVXE = has(hwcap_VXE) - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_loong64.go b/vendor/golang.org/x/sys/cpu/cpu_loong64.go deleted file mode 100644 index 0f57b05..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_loong64.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2022 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. - -//go:build loong64 -// +build loong64 - -package cpu - -const cacheLineSize = 64 - -func initOptions() { -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_mips64x.go b/vendor/golang.org/x/sys/cpu/cpu_mips64x.go deleted file mode 100644 index f4063c6..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_mips64x.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2018 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. - -//go:build mips64 || mips64le -// +build mips64 mips64le - -package cpu - -const cacheLineSize = 32 - -func initOptions() { - options = []option{ - {Name: "msa", Feature: &MIPS64X.HasMSA}, - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_mipsx.go b/vendor/golang.org/x/sys/cpu/cpu_mipsx.go deleted file mode 100644 index 07c4e36..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_mipsx.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2018 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. - -//go:build mips || mipsle -// +build mips mipsle - -package cpu - -const cacheLineSize = 32 - -func initOptions() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go deleted file mode 100644 index ebfb3fc..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_netbsd_arm64.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2020 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 cpu - -import ( - "syscall" - "unsafe" -) - -// Minimal copy of functionality from x/sys/unix so the cpu package can call -// sysctl without depending on x/sys/unix. - -const ( - _CTL_QUERY = -2 - - _SYSCTL_VERS_1 = 0x1000000 -) - -var _zero uintptr - -func sysctl(mib []int32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - var _p0 unsafe.Pointer - if len(mib) > 0 { - _p0 = unsafe.Pointer(&mib[0]) - } else { - _p0 = unsafe.Pointer(&_zero) - } - _, _, errno := syscall.Syscall6( - syscall.SYS___SYSCTL, - uintptr(_p0), - uintptr(len(mib)), - uintptr(unsafe.Pointer(old)), - uintptr(unsafe.Pointer(oldlen)), - uintptr(unsafe.Pointer(new)), - uintptr(newlen)) - if errno != 0 { - return errno - } - return nil -} - -type sysctlNode struct { - Flags uint32 - Num int32 - Name [32]int8 - Ver uint32 - __rsvd uint32 - Un [16]byte - _sysctl_size [8]byte - _sysctl_func [8]byte - _sysctl_parent [8]byte - _sysctl_desc [8]byte -} - -func sysctlNodes(mib []int32) ([]sysctlNode, error) { - var olen uintptr - - // Get a list of all sysctl nodes below the given MIB by performing - // a sysctl for the given MIB with CTL_QUERY appended. - mib = append(mib, _CTL_QUERY) - qnode := sysctlNode{Flags: _SYSCTL_VERS_1} - qp := (*byte)(unsafe.Pointer(&qnode)) - sz := unsafe.Sizeof(qnode) - if err := sysctl(mib, nil, &olen, qp, sz); err != nil { - return nil, err - } - - // Now that we know the size, get the actual nodes. - nodes := make([]sysctlNode, olen/sz) - np := (*byte)(unsafe.Pointer(&nodes[0])) - if err := sysctl(mib, np, &olen, qp, sz); err != nil { - return nil, err - } - - return nodes, nil -} - -func nametomib(name string) ([]int32, error) { - // Split name into components. - var parts []string - last := 0 - for i := 0; i < len(name); i++ { - if name[i] == '.' { - parts = append(parts, name[last:i]) - last = i + 1 - } - } - parts = append(parts, name[last:]) - - mib := []int32{} - // Discover the nodes and construct the MIB OID. - for partno, part := range parts { - nodes, err := sysctlNodes(mib) - if err != nil { - return nil, err - } - for _, node := range nodes { - n := make([]byte, 0) - for i := range node.Name { - if node.Name[i] != 0 { - n = append(n, byte(node.Name[i])) - } - } - if string(n) == part { - mib = append(mib, int32(node.Num)) - break - } - } - if len(mib) != partno+1 { - return nil, err - } - } - - return mib, nil -} - -// aarch64SysctlCPUID is struct aarch64_sysctl_cpu_id from NetBSD's -type aarch64SysctlCPUID struct { - midr uint64 /* Main ID Register */ - revidr uint64 /* Revision ID Register */ - mpidr uint64 /* Multiprocessor Affinity Register */ - aa64dfr0 uint64 /* A64 Debug Feature Register 0 */ - aa64dfr1 uint64 /* A64 Debug Feature Register 1 */ - aa64isar0 uint64 /* A64 Instruction Set Attribute Register 0 */ - aa64isar1 uint64 /* A64 Instruction Set Attribute Register 1 */ - aa64mmfr0 uint64 /* A64 Memory Model Feature Register 0 */ - aa64mmfr1 uint64 /* A64 Memory Model Feature Register 1 */ - aa64mmfr2 uint64 /* A64 Memory Model Feature Register 2 */ - aa64pfr0 uint64 /* A64 Processor Feature Register 0 */ - aa64pfr1 uint64 /* A64 Processor Feature Register 1 */ - aa64zfr0 uint64 /* A64 SVE Feature ID Register 0 */ - mvfr0 uint32 /* Media and VFP Feature Register 0 */ - mvfr1 uint32 /* Media and VFP Feature Register 1 */ - mvfr2 uint32 /* Media and VFP Feature Register 2 */ - pad uint32 - clidr uint64 /* Cache Level ID Register */ - ctr uint64 /* Cache Type Register */ -} - -func sysctlCPUID(name string) (*aarch64SysctlCPUID, error) { - mib, err := nametomib(name) - if err != nil { - return nil, err - } - - out := aarch64SysctlCPUID{} - n := unsafe.Sizeof(out) - _, _, errno := syscall.Syscall6( - syscall.SYS___SYSCTL, - uintptr(unsafe.Pointer(&mib[0])), - uintptr(len(mib)), - uintptr(unsafe.Pointer(&out)), - uintptr(unsafe.Pointer(&n)), - uintptr(0), - uintptr(0)) - if errno != 0 { - return nil, errno - } - return &out, nil -} - -func doinit() { - cpuid, err := sysctlCPUID("machdep.cpu0.cpu_id") - if err != nil { - setMinimalFeatures() - return - } - parseARM64SystemRegisters(cpuid.aa64isar0, cpuid.aa64isar1, cpuid.aa64pfr0) - - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go deleted file mode 100644 index 85b64d5..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2022 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 cpu - -import ( - "syscall" - "unsafe" -) - -// Minimal copy of functionality from x/sys/unix so the cpu package can call -// sysctl without depending on x/sys/unix. - -const ( - // From OpenBSD's sys/sysctl.h. - _CTL_MACHDEP = 7 - - // From OpenBSD's machine/cpu.h. - _CPU_ID_AA64ISAR0 = 2 - _CPU_ID_AA64ISAR1 = 3 -) - -// Implemented in the runtime package (runtime/sys_openbsd3.go) -func syscall_syscall6(fn, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) - -//go:linkname syscall_syscall6 syscall.syscall6 - -func sysctl(mib []uint32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { - _, _, errno := syscall_syscall6(libc_sysctl_trampoline_addr, uintptr(unsafe.Pointer(&mib[0])), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen)) - if errno != 0 { - return errno - } - return nil -} - -var libc_sysctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_sysctl sysctl "libc.so" - -func sysctlUint64(mib []uint32) (uint64, bool) { - var out uint64 - nout := unsafe.Sizeof(out) - if err := sysctl(mib, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0); err != nil { - return 0, false - } - return out, true -} - -func doinit() { - setMinimalFeatures() - - // Get ID_AA64ISAR0 and ID_AA64ISAR1 from sysctl. - isar0, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR0}) - if !ok { - return - } - isar1, ok := sysctlUint64([]uint32{_CTL_MACHDEP, _CPU_ID_AA64ISAR1}) - if !ok { - return - } - parseARM64SystemRegisters(isar0, isar1, 0) - - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s b/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s deleted file mode 100644 index 054ba05..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_openbsd_arm64.s +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2022 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. - -#include "textflag.h" - -TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 - JMP libc_sysctl(SB) - -GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 -DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_arm.go b/vendor/golang.org/x/sys/cpu/cpu_other_arm.go deleted file mode 100644 index d7b4fb4..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_arm.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2020 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. - -//go:build !linux && arm -// +build !linux,arm - -package cpu - -func archInit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go b/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go deleted file mode 100644 index f3cde12..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_arm64.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2019 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. - -//go:build !linux && !netbsd && !openbsd && arm64 -// +build !linux,!netbsd,!openbsd,arm64 - -package cpu - -func doinit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go b/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go deleted file mode 100644 index 0dafe96..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_mips64x.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2020 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. - -//go:build !linux && (mips64 || mips64le) -// +build !linux -// +build mips64 mips64le - -package cpu - -func archInit() { - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go deleted file mode 100644 index 060d46b..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_ppc64x.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2022 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. - -//go:build !aix && !linux && (ppc64 || ppc64le) -// +build !aix -// +build !linux -// +build ppc64 ppc64le - -package cpu - -func archInit() { - PPC64.IsPOWER8 = true - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go deleted file mode 100644 index dd10eb7..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_other_riscv64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2022 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. - -//go:build !linux && riscv64 -// +build !linux,riscv64 - -package cpu - -func archInit() { - Initialized = true -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go b/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go deleted file mode 100644 index 4e8acd1..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_ppc64x.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2020 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. - -//go:build ppc64 || ppc64le -// +build ppc64 ppc64le - -package cpu - -const cacheLineSize = 128 - -func initOptions() { - options = []option{ - {Name: "darn", Feature: &PPC64.HasDARN}, - {Name: "scv", Feature: &PPC64.HasSCV}, - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_riscv64.go b/vendor/golang.org/x/sys/cpu/cpu_riscv64.go deleted file mode 100644 index bd6c128..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_riscv64.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2019 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. - -//go:build riscv64 -// +build riscv64 - -package cpu - -const cacheLineSize = 32 - -func initOptions() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_s390x.go b/vendor/golang.org/x/sys/cpu/cpu_s390x.go deleted file mode 100644 index 5881b88..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_s390x.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2020 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 cpu - -const cacheLineSize = 256 - -func initOptions() { - options = []option{ - {Name: "zarch", Feature: &S390X.HasZARCH, Required: true}, - {Name: "stfle", Feature: &S390X.HasSTFLE, Required: true}, - {Name: "ldisp", Feature: &S390X.HasLDISP, Required: true}, - {Name: "eimm", Feature: &S390X.HasEIMM, Required: true}, - {Name: "dfp", Feature: &S390X.HasDFP}, - {Name: "etf3eh", Feature: &S390X.HasETF3EH}, - {Name: "msa", Feature: &S390X.HasMSA}, - {Name: "aes", Feature: &S390X.HasAES}, - {Name: "aescbc", Feature: &S390X.HasAESCBC}, - {Name: "aesctr", Feature: &S390X.HasAESCTR}, - {Name: "aesgcm", Feature: &S390X.HasAESGCM}, - {Name: "ghash", Feature: &S390X.HasGHASH}, - {Name: "sha1", Feature: &S390X.HasSHA1}, - {Name: "sha256", Feature: &S390X.HasSHA256}, - {Name: "sha3", Feature: &S390X.HasSHA3}, - {Name: "sha512", Feature: &S390X.HasSHA512}, - {Name: "vx", Feature: &S390X.HasVX}, - {Name: "vxe", Feature: &S390X.HasVXE}, - } -} - -// bitIsSet reports whether the bit at index is set. The bit index -// is in big endian order, so bit index 0 is the leftmost bit. -func bitIsSet(bits []uint64, index uint) bool { - return bits[index/64]&((1<<63)>>(index%64)) != 0 -} - -// facility is a bit index for the named facility. -type facility uint8 - -const ( - // mandatory facilities - zarch facility = 1 // z architecture mode is active - stflef facility = 7 // store-facility-list-extended - ldisp facility = 18 // long-displacement - eimm facility = 21 // extended-immediate - - // miscellaneous facilities - dfp facility = 42 // decimal-floating-point - etf3eh facility = 30 // extended-translation 3 enhancement - - // cryptography facilities - msa facility = 17 // message-security-assist - msa3 facility = 76 // message-security-assist extension 3 - msa4 facility = 77 // message-security-assist extension 4 - msa5 facility = 57 // message-security-assist extension 5 - msa8 facility = 146 // message-security-assist extension 8 - msa9 facility = 155 // message-security-assist extension 9 - - // vector facilities - vx facility = 129 // vector facility - vxe facility = 135 // vector-enhancements 1 - vxe2 facility = 148 // vector-enhancements 2 -) - -// facilityList contains the result of an STFLE call. -// Bits are numbered in big endian order so the -// leftmost bit (the MSB) is at index 0. -type facilityList struct { - bits [4]uint64 -} - -// Has reports whether the given facilities are present. -func (s *facilityList) Has(fs ...facility) bool { - if len(fs) == 0 { - panic("no facility bits provided") - } - for _, f := range fs { - if !bitIsSet(s.bits[:], uint(f)) { - return false - } - } - return true -} - -// function is the code for the named cryptographic function. -type function uint8 - -const ( - // KM{,A,C,CTR} function codes - aes128 function = 18 // AES-128 - aes192 function = 19 // AES-192 - aes256 function = 20 // AES-256 - - // K{I,L}MD function codes - sha1 function = 1 // SHA-1 - sha256 function = 2 // SHA-256 - sha512 function = 3 // SHA-512 - sha3_224 function = 32 // SHA3-224 - sha3_256 function = 33 // SHA3-256 - sha3_384 function = 34 // SHA3-384 - sha3_512 function = 35 // SHA3-512 - shake128 function = 36 // SHAKE-128 - shake256 function = 37 // SHAKE-256 - - // KLMD function codes - ghash function = 65 // GHASH -) - -// queryResult contains the result of a Query function -// call. Bits are numbered in big endian order so the -// leftmost bit (the MSB) is at index 0. -type queryResult struct { - bits [2]uint64 -} - -// Has reports whether the given functions are present. -func (q *queryResult) Has(fns ...function) bool { - if len(fns) == 0 { - panic("no function codes provided") - } - for _, f := range fns { - if !bitIsSet(q.bits[:], uint(f)) { - return false - } - } - return true -} - -func doinit() { - initS390Xbase() - - // We need implementations of stfle, km and so on - // to detect cryptographic features. - if !haveAsmFunctions() { - return - } - - // optional cryptographic functions - if S390X.HasMSA { - aes := []function{aes128, aes192, aes256} - - // cipher message - km, kmc := kmQuery(), kmcQuery() - S390X.HasAES = km.Has(aes...) - S390X.HasAESCBC = kmc.Has(aes...) - if S390X.HasSTFLE { - facilities := stfle() - if facilities.Has(msa4) { - kmctr := kmctrQuery() - S390X.HasAESCTR = kmctr.Has(aes...) - } - if facilities.Has(msa8) { - kma := kmaQuery() - S390X.HasAESGCM = kma.Has(aes...) - } - } - - // compute message digest - kimd := kimdQuery() // intermediate (no padding) - klmd := klmdQuery() // last (padding) - S390X.HasSHA1 = kimd.Has(sha1) && klmd.Has(sha1) - S390X.HasSHA256 = kimd.Has(sha256) && klmd.Has(sha256) - S390X.HasSHA512 = kimd.Has(sha512) && klmd.Has(sha512) - S390X.HasGHASH = kimd.Has(ghash) // KLMD-GHASH does not exist - sha3 := []function{ - sha3_224, sha3_256, sha3_384, sha3_512, - shake128, shake256, - } - S390X.HasSHA3 = kimd.Has(sha3...) && klmd.Has(sha3...) - } -} diff --git a/vendor/golang.org/x/sys/cpu/cpu_s390x.s b/vendor/golang.org/x/sys/cpu/cpu_s390x.s deleted file mode 100644 index 96f81e2..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_s390x.s +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2019 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. - -//go:build gc -// +build gc - -#include "textflag.h" - -// func stfle() facilityList -TEXT ·stfle(SB), NOSPLIT|NOFRAME, $0-32 - MOVD $ret+0(FP), R1 - MOVD $3, R0 // last doubleword index to store - XC $32, (R1), (R1) // clear 4 doublewords (32 bytes) - WORD $0xb2b01000 // store facility list extended (STFLE) - RET - -// func kmQuery() queryResult -TEXT ·kmQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KM-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB92E0024 // cipher message (KM) - RET - -// func kmcQuery() queryResult -TEXT ·kmcQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KMC-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB92F0024 // cipher message with chaining (KMC) - RET - -// func kmctrQuery() queryResult -TEXT ·kmctrQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KMCTR-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB92D4024 // cipher message with counter (KMCTR) - RET - -// func kmaQuery() queryResult -TEXT ·kmaQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KMA-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xb9296024 // cipher message with authentication (KMA) - RET - -// func kimdQuery() queryResult -TEXT ·kimdQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KIMD-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB93E0024 // compute intermediate message digest (KIMD) - RET - -// func klmdQuery() queryResult -TEXT ·klmdQuery(SB), NOSPLIT|NOFRAME, $0-16 - MOVD $0, R0 // set function code to 0 (KLMD-Query) - MOVD $ret+0(FP), R1 // address of 16-byte return value - WORD $0xB93F0024 // compute last message digest (KLMD) - RET diff --git a/vendor/golang.org/x/sys/cpu/cpu_wasm.go b/vendor/golang.org/x/sys/cpu/cpu_wasm.go deleted file mode 100644 index 7747d88..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_wasm.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2019 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. - -//go:build wasm -// +build wasm - -package cpu - -// We're compiling the cpu package for an unknown (software-abstracted) CPU. -// Make CacheLinePad an empty struct and hope that the usual struct alignment -// rules are good enough. - -const cacheLineSize = 0 - -func initOptions() {} - -func archInit() {} diff --git a/vendor/golang.org/x/sys/cpu/cpu_x86.go b/vendor/golang.org/x/sys/cpu/cpu_x86.go deleted file mode 100644 index f5aacfc..0000000 --- a/vendor/golang.org/x/sys/cpu/cpu_x86.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2018 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. - -//go:build 386 || amd64 || amd64p32 -// +build 386 amd64 amd64p32 - -package cpu - -import "runtime" - -const cacheLineSize = 64 - -func initOptions() { - options = []option{ - {Name: "adx", Feature: &X86.HasADX}, - {Name: "aes", Feature: &X86.HasAES}, - {Name: "avx", Feature: &X86.HasAVX}, - {Name: "avx2", Feature: &X86.HasAVX2}, - {Name: "avx512", Feature: &X86.HasAVX512}, - {Name: "avx512f", Feature: &X86.HasAVX512F}, - {Name: "avx512cd", Feature: &X86.HasAVX512CD}, - {Name: "avx512er", Feature: &X86.HasAVX512ER}, - {Name: "avx512pf", Feature: &X86.HasAVX512PF}, - {Name: "avx512vl", Feature: &X86.HasAVX512VL}, - {Name: "avx512bw", Feature: &X86.HasAVX512BW}, - {Name: "avx512dq", Feature: &X86.HasAVX512DQ}, - {Name: "avx512ifma", Feature: &X86.HasAVX512IFMA}, - {Name: "avx512vbmi", Feature: &X86.HasAVX512VBMI}, - {Name: "avx512vnniw", Feature: &X86.HasAVX5124VNNIW}, - {Name: "avx5124fmaps", Feature: &X86.HasAVX5124FMAPS}, - {Name: "avx512vpopcntdq", Feature: &X86.HasAVX512VPOPCNTDQ}, - {Name: "avx512vpclmulqdq", Feature: &X86.HasAVX512VPCLMULQDQ}, - {Name: "avx512vnni", Feature: &X86.HasAVX512VNNI}, - {Name: "avx512gfni", Feature: &X86.HasAVX512GFNI}, - {Name: "avx512vaes", Feature: &X86.HasAVX512VAES}, - {Name: "avx512vbmi2", Feature: &X86.HasAVX512VBMI2}, - {Name: "avx512bitalg", Feature: &X86.HasAVX512BITALG}, - {Name: "avx512bf16", Feature: &X86.HasAVX512BF16}, - {Name: "bmi1", Feature: &X86.HasBMI1}, - {Name: "bmi2", Feature: &X86.HasBMI2}, - {Name: "cx16", Feature: &X86.HasCX16}, - {Name: "erms", Feature: &X86.HasERMS}, - {Name: "fma", Feature: &X86.HasFMA}, - {Name: "osxsave", Feature: &X86.HasOSXSAVE}, - {Name: "pclmulqdq", Feature: &X86.HasPCLMULQDQ}, - {Name: "popcnt", Feature: &X86.HasPOPCNT}, - {Name: "rdrand", Feature: &X86.HasRDRAND}, - {Name: "rdseed", Feature: &X86.HasRDSEED}, - {Name: "sse3", Feature: &X86.HasSSE3}, - {Name: "sse41", Feature: &X86.HasSSE41}, - {Name: "sse42", Feature: &X86.HasSSE42}, - {Name: "ssse3", Feature: &X86.HasSSSE3}, - - // These capabilities should always be enabled on amd64: - {Name: "sse2", Feature: &X86.HasSSE2, Required: runtime.GOARCH == "amd64"}, - } -} - -func archInit() { - - Initialized = true - - maxID, _, _, _ := cpuid(0, 0) - - if maxID < 1 { - return - } - - _, _, ecx1, edx1 := cpuid(1, 0) - X86.HasSSE2 = isSet(26, edx1) - - X86.HasSSE3 = isSet(0, ecx1) - X86.HasPCLMULQDQ = isSet(1, ecx1) - X86.HasSSSE3 = isSet(9, ecx1) - X86.HasFMA = isSet(12, ecx1) - X86.HasCX16 = isSet(13, ecx1) - X86.HasSSE41 = isSet(19, ecx1) - X86.HasSSE42 = isSet(20, ecx1) - X86.HasPOPCNT = isSet(23, ecx1) - X86.HasAES = isSet(25, ecx1) - X86.HasOSXSAVE = isSet(27, ecx1) - X86.HasRDRAND = isSet(30, ecx1) - - var osSupportsAVX, osSupportsAVX512 bool - // For XGETBV, OSXSAVE bit is required and sufficient. - if X86.HasOSXSAVE { - eax, _ := xgetbv() - // Check if XMM and YMM registers have OS support. - osSupportsAVX = isSet(1, eax) && isSet(2, eax) - - if runtime.GOOS == "darwin" { - // Darwin doesn't save/restore AVX-512 mask registers correctly across signal handlers. - // Since users can't rely on mask register contents, let's not advertise AVX-512 support. - // See issue 49233. - osSupportsAVX512 = false - } else { - // Check if OPMASK and ZMM registers have OS support. - osSupportsAVX512 = osSupportsAVX && isSet(5, eax) && isSet(6, eax) && isSet(7, eax) - } - } - - X86.HasAVX = isSet(28, ecx1) && osSupportsAVX - - if maxID < 7 { - return - } - - _, ebx7, ecx7, edx7 := cpuid(7, 0) - X86.HasBMI1 = isSet(3, ebx7) - X86.HasAVX2 = isSet(5, ebx7) && osSupportsAVX - X86.HasBMI2 = isSet(8, ebx7) - X86.HasERMS = isSet(9, ebx7) - X86.HasRDSEED = isSet(18, ebx7) - X86.HasADX = isSet(19, ebx7) - - X86.HasAVX512 = isSet(16, ebx7) && osSupportsAVX512 // Because avx-512 foundation is the core required extension - if X86.HasAVX512 { - X86.HasAVX512F = true - X86.HasAVX512CD = isSet(28, ebx7) - X86.HasAVX512ER = isSet(27, ebx7) - X86.HasAVX512PF = isSet(26, ebx7) - X86.HasAVX512VL = isSet(31, ebx7) - X86.HasAVX512BW = isSet(30, ebx7) - X86.HasAVX512DQ = isSet(17, ebx7) - X86.HasAVX512IFMA = isSet(21, ebx7) - X86.HasAVX512VBMI = isSet(1, ecx7) - X86.HasAVX5124VNNIW = isSet(2, edx7) - X86.HasAVX5124FMAPS = isSet(3, edx7) - X86.HasAVX512VPOPCNTDQ = isSet(14, ecx7) - X86.HasAVX512VPCLMULQDQ = isSet(10, ecx7) - X86.HasAVX512VNNI = isSet(11, ecx7) - X86.HasAVX512GFNI = isSet(8, ecx7) - X86.HasAVX512VAES = isSet(9, ecx7) - X86.HasAVX512VBMI2 = isSet(6, ecx7) - X86.HasAVX512BITALG = isSet(12, ecx7) - - eax71, _, _, _ := cpuid(7, 1) - X86.HasAVX512BF16 = isSet(5, eax71) - } -} - -func isSet(bitpos uint, value uint32) bool { - return value&(1<> 63)) -) - -// For those platforms don't have a 'cpuid' equivalent we use HWCAP/HWCAP2 -// These are initialized in cpu_$GOARCH.go -// and should not be changed after they are initialized. -var hwCap uint -var hwCap2 uint - -func readHWCAP() error { - buf, err := ioutil.ReadFile(procAuxv) - if err != nil { - // e.g. on android /proc/self/auxv is not accessible, so silently - // ignore the error and leave Initialized = false. On some - // architectures (e.g. arm64) doinit() implements a fallback - // readout and will set Initialized = true again. - return err - } - bo := hostByteOrder() - for len(buf) >= 2*(uintSize/8) { - var tag, val uint - switch uintSize { - case 32: - tag = uint(bo.Uint32(buf[0:])) - val = uint(bo.Uint32(buf[4:])) - buf = buf[8:] - case 64: - tag = uint(bo.Uint64(buf[0:])) - val = uint(bo.Uint64(buf[8:])) - buf = buf[16:] - } - switch tag { - case _AT_HWCAP: - hwCap = val - case _AT_HWCAP2: - hwCap2 = val - } - } - return nil -} diff --git a/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go b/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go deleted file mode 100644 index 9613415..0000000 --- a/vendor/golang.org/x/sys/cpu/syscall_aix_gccgo.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 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. - -// Recreate a getsystemcfg syscall handler instead of -// using the one provided by x/sys/unix to avoid having -// the dependency between them. (See golang.org/issue/32102) -// Moreover, this file will be used during the building of -// gccgo's libgo and thus must not used a CGo method. - -//go:build aix && gccgo -// +build aix,gccgo - -package cpu - -import ( - "syscall" -) - -//extern getsystemcfg -func gccgoGetsystemcfg(label uint32) (r uint64) - -func callgetsystemcfg(label int) (r1 uintptr, e1 syscall.Errno) { - r1 = uintptr(gccgoGetsystemcfg(uint32(label))) - e1 = syscall.GetErrno() - return -} diff --git a/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go b/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go deleted file mode 100644 index 904be42..0000000 --- a/vendor/golang.org/x/sys/cpu/syscall_aix_ppc64_gc.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2019 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. - -// Minimal copy of x/sys/unix so the cpu package can make a -// system call on AIX without depending on x/sys/unix. -// (See golang.org/issue/32102) - -//go:build aix && ppc64 && gc -// +build aix,ppc64,gc - -package cpu - -import ( - "syscall" - "unsafe" -) - -//go:cgo_import_dynamic libc_getsystemcfg getsystemcfg "libc.a/shr_64.o" - -//go:linkname libc_getsystemcfg libc_getsystemcfg - -type syscallFunc uintptr - -var libc_getsystemcfg syscallFunc - -type errno = syscall.Errno - -// Implemented in runtime/syscall_aix.go. -func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err errno) -func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err errno) - -func callgetsystemcfg(label int) (r1 uintptr, e1 errno) { - r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_getsystemcfg)), 1, uintptr(label), 0, 0, 0, 0, 0) - return -} diff --git a/vendor/golang.org/x/text/LICENSE b/vendor/golang.org/x/text/LICENSE deleted file mode 100644 index 6a66aea..0000000 --- a/vendor/golang.org/x/text/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 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/golang.org/x/text/PATENTS b/vendor/golang.org/x/text/PATENTS deleted file mode 100644 index 7330990..0000000 --- a/vendor/golang.org/x/text/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/text/internal/language/common.go b/vendor/golang.org/x/text/internal/language/common.go deleted file mode 100644 index cdfdb74..0000000 --- a/vendor/golang.org/x/text/internal/language/common.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -package language - -// This file contains code common to the maketables.go and the package code. - -// AliasType is the type of an alias in AliasMap. -type AliasType int8 - -const ( - Deprecated AliasType = iota - Macro - Legacy - - AliasTypeUnknown AliasType = -1 -) diff --git a/vendor/golang.org/x/text/internal/language/compact.go b/vendor/golang.org/x/text/internal/language/compact.go deleted file mode 100644 index 46a0015..0000000 --- a/vendor/golang.org/x/text/internal/language/compact.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2018 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 language - -// CompactCoreInfo is a compact integer with the three core tags encoded. -type CompactCoreInfo uint32 - -// GetCompactCore generates a uint32 value that is guaranteed to be unique for -// different language, region, and script values. -func GetCompactCore(t Tag) (cci CompactCoreInfo, ok bool) { - if t.LangID > langNoIndexOffset { - return 0, false - } - cci |= CompactCoreInfo(t.LangID) << (8 + 12) - cci |= CompactCoreInfo(t.ScriptID) << 12 - cci |= CompactCoreInfo(t.RegionID) - return cci, true -} - -// Tag generates a tag from c. -func (c CompactCoreInfo) Tag() Tag { - return Tag{ - LangID: Language(c >> 20), - RegionID: Region(c & 0x3ff), - ScriptID: Script(c>>12) & 0xff, - } -} diff --git a/vendor/golang.org/x/text/internal/language/compact/compact.go b/vendor/golang.org/x/text/internal/language/compact/compact.go deleted file mode 100644 index 1b36935..0000000 --- a/vendor/golang.org/x/text/internal/language/compact/compact.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2018 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 compact defines a compact representation of language tags. -// -// Common language tags (at least all for which locale information is defined -// in CLDR) are assigned a unique index. Each Tag is associated with such an -// ID for selecting language-related resources (such as translations) as well -// as one for selecting regional defaults (currency, number formatting, etc.) -// -// It may want to export this functionality at some point, but at this point -// this is only available for use within x/text. -package compact // import "golang.org/x/text/internal/language/compact" - -import ( - "sort" - "strings" - - "golang.org/x/text/internal/language" -) - -// ID is an integer identifying a single tag. -type ID uint16 - -func getCoreIndex(t language.Tag) (id ID, ok bool) { - cci, ok := language.GetCompactCore(t) - if !ok { - return 0, false - } - i := sort.Search(len(coreTags), func(i int) bool { - return cci <= coreTags[i] - }) - if i == len(coreTags) || coreTags[i] != cci { - return 0, false - } - return ID(i), true -} - -// Parent returns the ID of the parent or the root ID if id is already the root. -func (id ID) Parent() ID { - return parents[id] -} - -// Tag converts id to an internal language Tag. -func (id ID) Tag() language.Tag { - if int(id) >= len(coreTags) { - return specialTags[int(id)-len(coreTags)] - } - return coreTags[id].Tag() -} - -var specialTags []language.Tag - -func init() { - tags := strings.Split(specialTagsStr, " ") - specialTags = make([]language.Tag, len(tags)) - for i, t := range tags { - specialTags[i] = language.MustParse(t) - } -} diff --git a/vendor/golang.org/x/text/internal/language/compact/language.go b/vendor/golang.org/x/text/internal/language/compact/language.go deleted file mode 100644 index 83816a7..0000000 --- a/vendor/golang.org/x/text/internal/language/compact/language.go +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright 2013 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. - -//go:generate go run gen.go gen_index.go -output tables.go -//go:generate go run gen_parents.go - -package compact - -// TODO: Remove above NOTE after: -// - verifying that tables are dropped correctly (most notably matcher tables). - -import ( - "strings" - - "golang.org/x/text/internal/language" -) - -// Tag represents a BCP 47 language tag. It is used to specify an instance of a -// specific language or locale. All language tag values are guaranteed to be -// well-formed. -type Tag struct { - // NOTE: exported tags will become part of the public API. - language ID - locale ID - full fullTag // always a language.Tag for now. -} - -const _und = 0 - -type fullTag interface { - IsRoot() bool - Parent() language.Tag -} - -// Make a compact Tag from a fully specified internal language Tag. -func Make(t language.Tag) (tag Tag) { - if region := t.TypeForKey("rg"); len(region) == 6 && region[2:] == "zzzz" { - if r, err := language.ParseRegion(region[:2]); err == nil { - tFull := t - t, _ = t.SetTypeForKey("rg", "") - // TODO: should we not consider "va" for the language tag? - var exact1, exact2 bool - tag.language, exact1 = FromTag(t) - t.RegionID = r - tag.locale, exact2 = FromTag(t) - if !exact1 || !exact2 { - tag.full = tFull - } - return tag - } - } - lang, ok := FromTag(t) - tag.language = lang - tag.locale = lang - if !ok { - tag.full = t - } - return tag -} - -// Tag returns an internal language Tag version of this tag. -func (t Tag) Tag() language.Tag { - if t.full != nil { - return t.full.(language.Tag) - } - tag := t.language.Tag() - if t.language != t.locale { - loc := t.locale.Tag() - tag, _ = tag.SetTypeForKey("rg", strings.ToLower(loc.RegionID.String())+"zzzz") - } - return tag -} - -// IsCompact reports whether this tag is fully defined in terms of ID. -func (t *Tag) IsCompact() bool { - return t.full == nil -} - -// MayHaveVariants reports whether a tag may have variants. If it returns false -// it is guaranteed the tag does not have variants. -func (t Tag) MayHaveVariants() bool { - return t.full != nil || int(t.language) >= len(coreTags) -} - -// MayHaveExtensions reports whether a tag may have extensions. If it returns -// false it is guaranteed the tag does not have them. -func (t Tag) MayHaveExtensions() bool { - return t.full != nil || - int(t.language) >= len(coreTags) || - t.language != t.locale -} - -// IsRoot returns true if t is equal to language "und". -func (t Tag) IsRoot() bool { - if t.full != nil { - return t.full.IsRoot() - } - return t.language == _und -} - -// Parent returns the CLDR parent of t. In CLDR, missing fields in data for a -// specific language are substituted with fields from the parent language. -// The parent for a language may change for newer versions of CLDR. -func (t Tag) Parent() Tag { - if t.full != nil { - return Make(t.full.Parent()) - } - if t.language != t.locale { - // Simulate stripping -u-rg-xxxxxx - return Tag{language: t.language, locale: t.language} - } - // TODO: use parent lookup table once cycle from internal package is - // removed. Probably by internalizing the table and declaring this fast - // enough. - // lang := compactID(internal.Parent(uint16(t.language))) - lang, _ := FromTag(t.language.Tag().Parent()) - return Tag{language: lang, locale: lang} -} - -// returns token t and the rest of the string. -func nextToken(s string) (t, tail string) { - p := strings.Index(s[1:], "-") - if p == -1 { - return s[1:], "" - } - p++ - return s[1:p], s[p:] -} - -// LanguageID returns an index, where 0 <= index < NumCompactTags, for tags -// for which data exists in the text repository.The index will change over time -// and should not be stored in persistent storage. If t does not match a compact -// index, exact will be false and the compact index will be returned for the -// first match after repeatedly taking the Parent of t. -func LanguageID(t Tag) (id ID, exact bool) { - return t.language, t.full == nil -} - -// RegionalID returns the ID for the regional variant of this tag. This index is -// used to indicate region-specific overrides, such as default currency, default -// calendar and week data, default time cycle, and default measurement system -// and unit preferences. -// -// For instance, the tag en-GB-u-rg-uszzzz specifies British English with US -// settings for currency, number formatting, etc. The CompactIndex for this tag -// will be that for en-GB, while the RegionalID will be the one corresponding to -// en-US. -func RegionalID(t Tag) (id ID, exact bool) { - return t.locale, t.full == nil -} - -// LanguageTag returns t stripped of regional variant indicators. -// -// At the moment this means it is stripped of a regional and variant subtag "rg" -// and "va" in the "u" extension. -func (t Tag) LanguageTag() Tag { - if t.full == nil { - return Tag{language: t.language, locale: t.language} - } - tt := t.Tag() - tt.SetTypeForKey("rg", "") - tt.SetTypeForKey("va", "") - return Make(tt) -} - -// RegionalTag returns the regional variant of the tag. -// -// At the moment this means that the region is set from the regional subtag -// "rg" in the "u" extension. -func (t Tag) RegionalTag() Tag { - rt := Tag{language: t.locale, locale: t.locale} - if t.full == nil { - return rt - } - b := language.Builder{} - tag := t.Tag() - // tag, _ = tag.SetTypeForKey("rg", "") - b.SetTag(t.locale.Tag()) - if v := tag.Variants(); v != "" { - for _, v := range strings.Split(v, "-") { - b.AddVariant(v) - } - } - for _, e := range tag.Extensions() { - b.AddExt(e) - } - return t -} - -// FromTag reports closest matching ID for an internal language Tag. -func FromTag(t language.Tag) (id ID, exact bool) { - // TODO: perhaps give more frequent tags a lower index. - // TODO: we could make the indexes stable. This will excluded some - // possibilities for optimization, so don't do this quite yet. - exact = true - - b, s, r := t.Raw() - if t.HasString() { - if t.IsPrivateUse() { - // We have no entries for user-defined tags. - return 0, false - } - hasExtra := false - if t.HasVariants() { - if t.HasExtensions() { - build := language.Builder{} - build.SetTag(language.Tag{LangID: b, ScriptID: s, RegionID: r}) - build.AddVariant(t.Variants()) - exact = false - t = build.Make() - } - hasExtra = true - } else if _, ok := t.Extension('u'); ok { - // TODO: va may mean something else. Consider not considering it. - // Strip all but the 'va' entry. - old := t - variant := t.TypeForKey("va") - t = language.Tag{LangID: b, ScriptID: s, RegionID: r} - if variant != "" { - t, _ = t.SetTypeForKey("va", variant) - hasExtra = true - } - exact = old == t - } else { - exact = false - } - if hasExtra { - // We have some variants. - for i, s := range specialTags { - if s == t { - return ID(i + len(coreTags)), exact - } - } - exact = false - } - } - if x, ok := getCoreIndex(t); ok { - return x, exact - } - exact = false - if r != 0 && s == 0 { - // Deal with cases where an extra script is inserted for the region. - t, _ := t.Maximize() - if x, ok := getCoreIndex(t); ok { - return x, exact - } - } - for t = t.Parent(); t != root; t = t.Parent() { - // No variants specified: just compare core components. - // The key has the form lllssrrr, where l, s, and r are nibbles for - // respectively the langID, scriptID, and regionID. - if x, ok := getCoreIndex(t); ok { - return x, exact - } - } - return 0, exact -} - -var root = language.Tag{} diff --git a/vendor/golang.org/x/text/internal/language/compact/parents.go b/vendor/golang.org/x/text/internal/language/compact/parents.go deleted file mode 100644 index 8d81072..0000000 --- a/vendor/golang.org/x/text/internal/language/compact/parents.go +++ /dev/null @@ -1,120 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -package compact - -// parents maps a compact index of a tag to the compact index of the parent of -// this tag. -var parents = []ID{ // 775 elements - // Entry 0 - 3F - 0x0000, 0x0000, 0x0001, 0x0001, 0x0000, 0x0004, 0x0000, 0x0006, - 0x0000, 0x0008, 0x0000, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, - 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, - 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, - 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x000a, 0x0000, - 0x0000, 0x0028, 0x0000, 0x002a, 0x0000, 0x002c, 0x0000, 0x0000, - 0x002f, 0x002e, 0x002e, 0x0000, 0x0033, 0x0000, 0x0035, 0x0000, - 0x0037, 0x0000, 0x0039, 0x0000, 0x003b, 0x0000, 0x0000, 0x003e, - // Entry 40 - 7F - 0x0000, 0x0040, 0x0040, 0x0000, 0x0043, 0x0043, 0x0000, 0x0046, - 0x0000, 0x0048, 0x0000, 0x0000, 0x004b, 0x004a, 0x004a, 0x0000, - 0x004f, 0x004f, 0x004f, 0x004f, 0x0000, 0x0054, 0x0054, 0x0000, - 0x0057, 0x0000, 0x0059, 0x0000, 0x005b, 0x0000, 0x005d, 0x005d, - 0x0000, 0x0060, 0x0000, 0x0062, 0x0000, 0x0064, 0x0000, 0x0066, - 0x0066, 0x0000, 0x0069, 0x0000, 0x006b, 0x006b, 0x006b, 0x006b, - 0x006b, 0x006b, 0x006b, 0x0000, 0x0073, 0x0000, 0x0075, 0x0000, - 0x0077, 0x0000, 0x0000, 0x007a, 0x0000, 0x007c, 0x0000, 0x007e, - // Entry 80 - BF - 0x0000, 0x0080, 0x0080, 0x0000, 0x0083, 0x0083, 0x0000, 0x0086, - 0x0087, 0x0087, 0x0087, 0x0086, 0x0088, 0x0087, 0x0087, 0x0087, - 0x0086, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0088, - 0x0087, 0x0087, 0x0087, 0x0087, 0x0088, 0x0087, 0x0088, 0x0087, - 0x0087, 0x0088, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, - 0x0087, 0x0087, 0x0087, 0x0086, 0x0087, 0x0087, 0x0087, 0x0087, - 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, - 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0086, 0x0087, 0x0086, - // Entry C0 - FF - 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, - 0x0088, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, - 0x0086, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0088, 0x0087, - 0x0087, 0x0088, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, - 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0086, 0x0086, 0x0087, - 0x0087, 0x0086, 0x0087, 0x0087, 0x0087, 0x0087, 0x0087, 0x0000, - 0x00ef, 0x0000, 0x00f1, 0x00f2, 0x00f2, 0x00f2, 0x00f2, 0x00f2, - 0x00f2, 0x00f2, 0x00f2, 0x00f2, 0x00f1, 0x00f2, 0x00f1, 0x00f1, - // Entry 100 - 13F - 0x00f2, 0x00f2, 0x00f1, 0x00f2, 0x00f2, 0x00f2, 0x00f2, 0x00f1, - 0x00f2, 0x00f2, 0x00f2, 0x00f2, 0x00f2, 0x00f2, 0x0000, 0x010e, - 0x0000, 0x0110, 0x0000, 0x0112, 0x0000, 0x0114, 0x0114, 0x0000, - 0x0117, 0x0117, 0x0117, 0x0117, 0x0000, 0x011c, 0x0000, 0x011e, - 0x0000, 0x0120, 0x0120, 0x0000, 0x0123, 0x0123, 0x0123, 0x0123, - 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, - 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, - 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, - // Entry 140 - 17F - 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, - 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, 0x0123, - 0x0123, 0x0123, 0x0000, 0x0152, 0x0000, 0x0154, 0x0000, 0x0156, - 0x0000, 0x0158, 0x0000, 0x015a, 0x0000, 0x015c, 0x015c, 0x015c, - 0x0000, 0x0160, 0x0000, 0x0000, 0x0163, 0x0000, 0x0165, 0x0000, - 0x0167, 0x0167, 0x0167, 0x0000, 0x016b, 0x0000, 0x016d, 0x0000, - 0x016f, 0x0000, 0x0171, 0x0171, 0x0000, 0x0174, 0x0000, 0x0176, - 0x0000, 0x0178, 0x0000, 0x017a, 0x0000, 0x017c, 0x0000, 0x017e, - // Entry 180 - 1BF - 0x0000, 0x0000, 0x0000, 0x0182, 0x0000, 0x0184, 0x0184, 0x0184, - 0x0184, 0x0000, 0x0000, 0x0000, 0x018b, 0x0000, 0x0000, 0x018e, - 0x0000, 0x0000, 0x0191, 0x0000, 0x0000, 0x0000, 0x0195, 0x0000, - 0x0197, 0x0000, 0x0000, 0x019a, 0x0000, 0x0000, 0x019d, 0x0000, - 0x019f, 0x0000, 0x01a1, 0x0000, 0x01a3, 0x0000, 0x01a5, 0x0000, - 0x01a7, 0x0000, 0x01a9, 0x0000, 0x01ab, 0x0000, 0x01ad, 0x0000, - 0x01af, 0x0000, 0x01b1, 0x01b1, 0x0000, 0x01b4, 0x0000, 0x01b6, - 0x0000, 0x01b8, 0x0000, 0x01ba, 0x0000, 0x01bc, 0x0000, 0x0000, - // Entry 1C0 - 1FF - 0x01bf, 0x0000, 0x01c1, 0x0000, 0x01c3, 0x0000, 0x01c5, 0x0000, - 0x01c7, 0x0000, 0x01c9, 0x0000, 0x01cb, 0x01cb, 0x01cb, 0x01cb, - 0x0000, 0x01d0, 0x0000, 0x01d2, 0x01d2, 0x0000, 0x01d5, 0x0000, - 0x01d7, 0x0000, 0x01d9, 0x0000, 0x01db, 0x0000, 0x01dd, 0x0000, - 0x01df, 0x01df, 0x0000, 0x01e2, 0x0000, 0x01e4, 0x0000, 0x01e6, - 0x0000, 0x01e8, 0x0000, 0x01ea, 0x0000, 0x01ec, 0x0000, 0x01ee, - 0x0000, 0x01f0, 0x0000, 0x0000, 0x01f3, 0x0000, 0x01f5, 0x01f5, - 0x01f5, 0x0000, 0x01f9, 0x0000, 0x01fb, 0x0000, 0x01fd, 0x0000, - // Entry 200 - 23F - 0x01ff, 0x0000, 0x0000, 0x0202, 0x0000, 0x0204, 0x0204, 0x0000, - 0x0207, 0x0000, 0x0209, 0x0209, 0x0000, 0x020c, 0x020c, 0x0000, - 0x020f, 0x020f, 0x020f, 0x020f, 0x020f, 0x020f, 0x020f, 0x0000, - 0x0217, 0x0000, 0x0219, 0x0000, 0x021b, 0x0000, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0221, 0x0000, 0x0000, 0x0224, 0x0000, 0x0226, - 0x0226, 0x0000, 0x0229, 0x0000, 0x022b, 0x022b, 0x0000, 0x0000, - 0x022f, 0x022e, 0x022e, 0x0000, 0x0000, 0x0234, 0x0000, 0x0236, - 0x0000, 0x0238, 0x0000, 0x0244, 0x023a, 0x0244, 0x0244, 0x0244, - // Entry 240 - 27F - 0x0244, 0x0244, 0x0244, 0x0244, 0x023a, 0x0244, 0x0244, 0x0000, - 0x0247, 0x0247, 0x0247, 0x0000, 0x024b, 0x0000, 0x024d, 0x0000, - 0x024f, 0x024f, 0x0000, 0x0252, 0x0000, 0x0254, 0x0254, 0x0254, - 0x0254, 0x0254, 0x0254, 0x0000, 0x025b, 0x0000, 0x025d, 0x0000, - 0x025f, 0x0000, 0x0261, 0x0000, 0x0263, 0x0000, 0x0265, 0x0000, - 0x0000, 0x0268, 0x0268, 0x0268, 0x0000, 0x026c, 0x0000, 0x026e, - 0x0000, 0x0270, 0x0000, 0x0000, 0x0000, 0x0274, 0x0273, 0x0273, - 0x0000, 0x0278, 0x0000, 0x027a, 0x0000, 0x027c, 0x0000, 0x0000, - // Entry 280 - 2BF - 0x0000, 0x0000, 0x0281, 0x0000, 0x0000, 0x0284, 0x0000, 0x0286, - 0x0286, 0x0286, 0x0286, 0x0000, 0x028b, 0x028b, 0x028b, 0x0000, - 0x028f, 0x028f, 0x028f, 0x028f, 0x028f, 0x0000, 0x0295, 0x0295, - 0x0295, 0x0295, 0x0000, 0x0000, 0x0000, 0x0000, 0x029d, 0x029d, - 0x029d, 0x0000, 0x02a1, 0x02a1, 0x02a1, 0x02a1, 0x0000, 0x0000, - 0x02a7, 0x02a7, 0x02a7, 0x02a7, 0x0000, 0x02ac, 0x0000, 0x02ae, - 0x02ae, 0x0000, 0x02b1, 0x0000, 0x02b3, 0x0000, 0x02b5, 0x02b5, - 0x0000, 0x0000, 0x02b9, 0x0000, 0x0000, 0x0000, 0x02bd, 0x0000, - // Entry 2C0 - 2FF - 0x02bf, 0x02bf, 0x0000, 0x0000, 0x02c3, 0x0000, 0x02c5, 0x0000, - 0x02c7, 0x0000, 0x02c9, 0x0000, 0x02cb, 0x0000, 0x02cd, 0x02cd, - 0x0000, 0x0000, 0x02d1, 0x0000, 0x02d3, 0x02d0, 0x02d0, 0x0000, - 0x0000, 0x02d8, 0x02d7, 0x02d7, 0x0000, 0x0000, 0x02dd, 0x0000, - 0x02df, 0x0000, 0x02e1, 0x0000, 0x0000, 0x02e4, 0x0000, 0x02e6, - 0x0000, 0x0000, 0x02e9, 0x0000, 0x02eb, 0x0000, 0x02ed, 0x0000, - 0x02ef, 0x02ef, 0x0000, 0x0000, 0x02f3, 0x02f2, 0x02f2, 0x0000, - 0x02f7, 0x0000, 0x02f9, 0x02f9, 0x02f9, 0x02f9, 0x02f9, 0x0000, - // Entry 300 - 33F - 0x02ff, 0x0300, 0x02ff, 0x0000, 0x0303, 0x0051, 0x00e6, -} // Size: 1574 bytes - -// Total table size 1574 bytes (1KiB); checksum: 895AAF0B diff --git a/vendor/golang.org/x/text/internal/language/compact/tables.go b/vendor/golang.org/x/text/internal/language/compact/tables.go deleted file mode 100644 index 32af9de..0000000 --- a/vendor/golang.org/x/text/internal/language/compact/tables.go +++ /dev/null @@ -1,1015 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -package compact - -import "golang.org/x/text/internal/language" - -// CLDRVersion is the CLDR version from which the tables in this package are derived. -const CLDRVersion = "32" - -// NumCompactTags is the number of common tags. The maximum tag is -// NumCompactTags-1. -const NumCompactTags = 775 -const ( - undIndex ID = 0 - afIndex ID = 1 - afNAIndex ID = 2 - afZAIndex ID = 3 - agqIndex ID = 4 - agqCMIndex ID = 5 - akIndex ID = 6 - akGHIndex ID = 7 - amIndex ID = 8 - amETIndex ID = 9 - arIndex ID = 10 - ar001Index ID = 11 - arAEIndex ID = 12 - arBHIndex ID = 13 - arDJIndex ID = 14 - arDZIndex ID = 15 - arEGIndex ID = 16 - arEHIndex ID = 17 - arERIndex ID = 18 - arILIndex ID = 19 - arIQIndex ID = 20 - arJOIndex ID = 21 - arKMIndex ID = 22 - arKWIndex ID = 23 - arLBIndex ID = 24 - arLYIndex ID = 25 - arMAIndex ID = 26 - arMRIndex ID = 27 - arOMIndex ID = 28 - arPSIndex ID = 29 - arQAIndex ID = 30 - arSAIndex ID = 31 - arSDIndex ID = 32 - arSOIndex ID = 33 - arSSIndex ID = 34 - arSYIndex ID = 35 - arTDIndex ID = 36 - arTNIndex ID = 37 - arYEIndex ID = 38 - arsIndex ID = 39 - asIndex ID = 40 - asINIndex ID = 41 - asaIndex ID = 42 - asaTZIndex ID = 43 - astIndex ID = 44 - astESIndex ID = 45 - azIndex ID = 46 - azCyrlIndex ID = 47 - azCyrlAZIndex ID = 48 - azLatnIndex ID = 49 - azLatnAZIndex ID = 50 - basIndex ID = 51 - basCMIndex ID = 52 - beIndex ID = 53 - beBYIndex ID = 54 - bemIndex ID = 55 - bemZMIndex ID = 56 - bezIndex ID = 57 - bezTZIndex ID = 58 - bgIndex ID = 59 - bgBGIndex ID = 60 - bhIndex ID = 61 - bmIndex ID = 62 - bmMLIndex ID = 63 - bnIndex ID = 64 - bnBDIndex ID = 65 - bnINIndex ID = 66 - boIndex ID = 67 - boCNIndex ID = 68 - boINIndex ID = 69 - brIndex ID = 70 - brFRIndex ID = 71 - brxIndex ID = 72 - brxINIndex ID = 73 - bsIndex ID = 74 - bsCyrlIndex ID = 75 - bsCyrlBAIndex ID = 76 - bsLatnIndex ID = 77 - bsLatnBAIndex ID = 78 - caIndex ID = 79 - caADIndex ID = 80 - caESIndex ID = 81 - caFRIndex ID = 82 - caITIndex ID = 83 - ccpIndex ID = 84 - ccpBDIndex ID = 85 - ccpINIndex ID = 86 - ceIndex ID = 87 - ceRUIndex ID = 88 - cggIndex ID = 89 - cggUGIndex ID = 90 - chrIndex ID = 91 - chrUSIndex ID = 92 - ckbIndex ID = 93 - ckbIQIndex ID = 94 - ckbIRIndex ID = 95 - csIndex ID = 96 - csCZIndex ID = 97 - cuIndex ID = 98 - cuRUIndex ID = 99 - cyIndex ID = 100 - cyGBIndex ID = 101 - daIndex ID = 102 - daDKIndex ID = 103 - daGLIndex ID = 104 - davIndex ID = 105 - davKEIndex ID = 106 - deIndex ID = 107 - deATIndex ID = 108 - deBEIndex ID = 109 - deCHIndex ID = 110 - deDEIndex ID = 111 - deITIndex ID = 112 - deLIIndex ID = 113 - deLUIndex ID = 114 - djeIndex ID = 115 - djeNEIndex ID = 116 - dsbIndex ID = 117 - dsbDEIndex ID = 118 - duaIndex ID = 119 - duaCMIndex ID = 120 - dvIndex ID = 121 - dyoIndex ID = 122 - dyoSNIndex ID = 123 - dzIndex ID = 124 - dzBTIndex ID = 125 - ebuIndex ID = 126 - ebuKEIndex ID = 127 - eeIndex ID = 128 - eeGHIndex ID = 129 - eeTGIndex ID = 130 - elIndex ID = 131 - elCYIndex ID = 132 - elGRIndex ID = 133 - enIndex ID = 134 - en001Index ID = 135 - en150Index ID = 136 - enAGIndex ID = 137 - enAIIndex ID = 138 - enASIndex ID = 139 - enATIndex ID = 140 - enAUIndex ID = 141 - enBBIndex ID = 142 - enBEIndex ID = 143 - enBIIndex ID = 144 - enBMIndex ID = 145 - enBSIndex ID = 146 - enBWIndex ID = 147 - enBZIndex ID = 148 - enCAIndex ID = 149 - enCCIndex ID = 150 - enCHIndex ID = 151 - enCKIndex ID = 152 - enCMIndex ID = 153 - enCXIndex ID = 154 - enCYIndex ID = 155 - enDEIndex ID = 156 - enDGIndex ID = 157 - enDKIndex ID = 158 - enDMIndex ID = 159 - enERIndex ID = 160 - enFIIndex ID = 161 - enFJIndex ID = 162 - enFKIndex ID = 163 - enFMIndex ID = 164 - enGBIndex ID = 165 - enGDIndex ID = 166 - enGGIndex ID = 167 - enGHIndex ID = 168 - enGIIndex ID = 169 - enGMIndex ID = 170 - enGUIndex ID = 171 - enGYIndex ID = 172 - enHKIndex ID = 173 - enIEIndex ID = 174 - enILIndex ID = 175 - enIMIndex ID = 176 - enINIndex ID = 177 - enIOIndex ID = 178 - enJEIndex ID = 179 - enJMIndex ID = 180 - enKEIndex ID = 181 - enKIIndex ID = 182 - enKNIndex ID = 183 - enKYIndex ID = 184 - enLCIndex ID = 185 - enLRIndex ID = 186 - enLSIndex ID = 187 - enMGIndex ID = 188 - enMHIndex ID = 189 - enMOIndex ID = 190 - enMPIndex ID = 191 - enMSIndex ID = 192 - enMTIndex ID = 193 - enMUIndex ID = 194 - enMWIndex ID = 195 - enMYIndex ID = 196 - enNAIndex ID = 197 - enNFIndex ID = 198 - enNGIndex ID = 199 - enNLIndex ID = 200 - enNRIndex ID = 201 - enNUIndex ID = 202 - enNZIndex ID = 203 - enPGIndex ID = 204 - enPHIndex ID = 205 - enPKIndex ID = 206 - enPNIndex ID = 207 - enPRIndex ID = 208 - enPWIndex ID = 209 - enRWIndex ID = 210 - enSBIndex ID = 211 - enSCIndex ID = 212 - enSDIndex ID = 213 - enSEIndex ID = 214 - enSGIndex ID = 215 - enSHIndex ID = 216 - enSIIndex ID = 217 - enSLIndex ID = 218 - enSSIndex ID = 219 - enSXIndex ID = 220 - enSZIndex ID = 221 - enTCIndex ID = 222 - enTKIndex ID = 223 - enTOIndex ID = 224 - enTTIndex ID = 225 - enTVIndex ID = 226 - enTZIndex ID = 227 - enUGIndex ID = 228 - enUMIndex ID = 229 - enUSIndex ID = 230 - enVCIndex ID = 231 - enVGIndex ID = 232 - enVIIndex ID = 233 - enVUIndex ID = 234 - enWSIndex ID = 235 - enZAIndex ID = 236 - enZMIndex ID = 237 - enZWIndex ID = 238 - eoIndex ID = 239 - eo001Index ID = 240 - esIndex ID = 241 - es419Index ID = 242 - esARIndex ID = 243 - esBOIndex ID = 244 - esBRIndex ID = 245 - esBZIndex ID = 246 - esCLIndex ID = 247 - esCOIndex ID = 248 - esCRIndex ID = 249 - esCUIndex ID = 250 - esDOIndex ID = 251 - esEAIndex ID = 252 - esECIndex ID = 253 - esESIndex ID = 254 - esGQIndex ID = 255 - esGTIndex ID = 256 - esHNIndex ID = 257 - esICIndex ID = 258 - esMXIndex ID = 259 - esNIIndex ID = 260 - esPAIndex ID = 261 - esPEIndex ID = 262 - esPHIndex ID = 263 - esPRIndex ID = 264 - esPYIndex ID = 265 - esSVIndex ID = 266 - esUSIndex ID = 267 - esUYIndex ID = 268 - esVEIndex ID = 269 - etIndex ID = 270 - etEEIndex ID = 271 - euIndex ID = 272 - euESIndex ID = 273 - ewoIndex ID = 274 - ewoCMIndex ID = 275 - faIndex ID = 276 - faAFIndex ID = 277 - faIRIndex ID = 278 - ffIndex ID = 279 - ffCMIndex ID = 280 - ffGNIndex ID = 281 - ffMRIndex ID = 282 - ffSNIndex ID = 283 - fiIndex ID = 284 - fiFIIndex ID = 285 - filIndex ID = 286 - filPHIndex ID = 287 - foIndex ID = 288 - foDKIndex ID = 289 - foFOIndex ID = 290 - frIndex ID = 291 - frBEIndex ID = 292 - frBFIndex ID = 293 - frBIIndex ID = 294 - frBJIndex ID = 295 - frBLIndex ID = 296 - frCAIndex ID = 297 - frCDIndex ID = 298 - frCFIndex ID = 299 - frCGIndex ID = 300 - frCHIndex ID = 301 - frCIIndex ID = 302 - frCMIndex ID = 303 - frDJIndex ID = 304 - frDZIndex ID = 305 - frFRIndex ID = 306 - frGAIndex ID = 307 - frGFIndex ID = 308 - frGNIndex ID = 309 - frGPIndex ID = 310 - frGQIndex ID = 311 - frHTIndex ID = 312 - frKMIndex ID = 313 - frLUIndex ID = 314 - frMAIndex ID = 315 - frMCIndex ID = 316 - frMFIndex ID = 317 - frMGIndex ID = 318 - frMLIndex ID = 319 - frMQIndex ID = 320 - frMRIndex ID = 321 - frMUIndex ID = 322 - frNCIndex ID = 323 - frNEIndex ID = 324 - frPFIndex ID = 325 - frPMIndex ID = 326 - frREIndex ID = 327 - frRWIndex ID = 328 - frSCIndex ID = 329 - frSNIndex ID = 330 - frSYIndex ID = 331 - frTDIndex ID = 332 - frTGIndex ID = 333 - frTNIndex ID = 334 - frVUIndex ID = 335 - frWFIndex ID = 336 - frYTIndex ID = 337 - furIndex ID = 338 - furITIndex ID = 339 - fyIndex ID = 340 - fyNLIndex ID = 341 - gaIndex ID = 342 - gaIEIndex ID = 343 - gdIndex ID = 344 - gdGBIndex ID = 345 - glIndex ID = 346 - glESIndex ID = 347 - gswIndex ID = 348 - gswCHIndex ID = 349 - gswFRIndex ID = 350 - gswLIIndex ID = 351 - guIndex ID = 352 - guINIndex ID = 353 - guwIndex ID = 354 - guzIndex ID = 355 - guzKEIndex ID = 356 - gvIndex ID = 357 - gvIMIndex ID = 358 - haIndex ID = 359 - haGHIndex ID = 360 - haNEIndex ID = 361 - haNGIndex ID = 362 - hawIndex ID = 363 - hawUSIndex ID = 364 - heIndex ID = 365 - heILIndex ID = 366 - hiIndex ID = 367 - hiINIndex ID = 368 - hrIndex ID = 369 - hrBAIndex ID = 370 - hrHRIndex ID = 371 - hsbIndex ID = 372 - hsbDEIndex ID = 373 - huIndex ID = 374 - huHUIndex ID = 375 - hyIndex ID = 376 - hyAMIndex ID = 377 - idIndex ID = 378 - idIDIndex ID = 379 - igIndex ID = 380 - igNGIndex ID = 381 - iiIndex ID = 382 - iiCNIndex ID = 383 - inIndex ID = 384 - ioIndex ID = 385 - isIndex ID = 386 - isISIndex ID = 387 - itIndex ID = 388 - itCHIndex ID = 389 - itITIndex ID = 390 - itSMIndex ID = 391 - itVAIndex ID = 392 - iuIndex ID = 393 - iwIndex ID = 394 - jaIndex ID = 395 - jaJPIndex ID = 396 - jboIndex ID = 397 - jgoIndex ID = 398 - jgoCMIndex ID = 399 - jiIndex ID = 400 - jmcIndex ID = 401 - jmcTZIndex ID = 402 - jvIndex ID = 403 - jwIndex ID = 404 - kaIndex ID = 405 - kaGEIndex ID = 406 - kabIndex ID = 407 - kabDZIndex ID = 408 - kajIndex ID = 409 - kamIndex ID = 410 - kamKEIndex ID = 411 - kcgIndex ID = 412 - kdeIndex ID = 413 - kdeTZIndex ID = 414 - keaIndex ID = 415 - keaCVIndex ID = 416 - khqIndex ID = 417 - khqMLIndex ID = 418 - kiIndex ID = 419 - kiKEIndex ID = 420 - kkIndex ID = 421 - kkKZIndex ID = 422 - kkjIndex ID = 423 - kkjCMIndex ID = 424 - klIndex ID = 425 - klGLIndex ID = 426 - klnIndex ID = 427 - klnKEIndex ID = 428 - kmIndex ID = 429 - kmKHIndex ID = 430 - knIndex ID = 431 - knINIndex ID = 432 - koIndex ID = 433 - koKPIndex ID = 434 - koKRIndex ID = 435 - kokIndex ID = 436 - kokINIndex ID = 437 - ksIndex ID = 438 - ksINIndex ID = 439 - ksbIndex ID = 440 - ksbTZIndex ID = 441 - ksfIndex ID = 442 - ksfCMIndex ID = 443 - kshIndex ID = 444 - kshDEIndex ID = 445 - kuIndex ID = 446 - kwIndex ID = 447 - kwGBIndex ID = 448 - kyIndex ID = 449 - kyKGIndex ID = 450 - lagIndex ID = 451 - lagTZIndex ID = 452 - lbIndex ID = 453 - lbLUIndex ID = 454 - lgIndex ID = 455 - lgUGIndex ID = 456 - lktIndex ID = 457 - lktUSIndex ID = 458 - lnIndex ID = 459 - lnAOIndex ID = 460 - lnCDIndex ID = 461 - lnCFIndex ID = 462 - lnCGIndex ID = 463 - loIndex ID = 464 - loLAIndex ID = 465 - lrcIndex ID = 466 - lrcIQIndex ID = 467 - lrcIRIndex ID = 468 - ltIndex ID = 469 - ltLTIndex ID = 470 - luIndex ID = 471 - luCDIndex ID = 472 - luoIndex ID = 473 - luoKEIndex ID = 474 - luyIndex ID = 475 - luyKEIndex ID = 476 - lvIndex ID = 477 - lvLVIndex ID = 478 - masIndex ID = 479 - masKEIndex ID = 480 - masTZIndex ID = 481 - merIndex ID = 482 - merKEIndex ID = 483 - mfeIndex ID = 484 - mfeMUIndex ID = 485 - mgIndex ID = 486 - mgMGIndex ID = 487 - mghIndex ID = 488 - mghMZIndex ID = 489 - mgoIndex ID = 490 - mgoCMIndex ID = 491 - mkIndex ID = 492 - mkMKIndex ID = 493 - mlIndex ID = 494 - mlINIndex ID = 495 - mnIndex ID = 496 - mnMNIndex ID = 497 - moIndex ID = 498 - mrIndex ID = 499 - mrINIndex ID = 500 - msIndex ID = 501 - msBNIndex ID = 502 - msMYIndex ID = 503 - msSGIndex ID = 504 - mtIndex ID = 505 - mtMTIndex ID = 506 - muaIndex ID = 507 - muaCMIndex ID = 508 - myIndex ID = 509 - myMMIndex ID = 510 - mznIndex ID = 511 - mznIRIndex ID = 512 - nahIndex ID = 513 - naqIndex ID = 514 - naqNAIndex ID = 515 - nbIndex ID = 516 - nbNOIndex ID = 517 - nbSJIndex ID = 518 - ndIndex ID = 519 - ndZWIndex ID = 520 - ndsIndex ID = 521 - ndsDEIndex ID = 522 - ndsNLIndex ID = 523 - neIndex ID = 524 - neINIndex ID = 525 - neNPIndex ID = 526 - nlIndex ID = 527 - nlAWIndex ID = 528 - nlBEIndex ID = 529 - nlBQIndex ID = 530 - nlCWIndex ID = 531 - nlNLIndex ID = 532 - nlSRIndex ID = 533 - nlSXIndex ID = 534 - nmgIndex ID = 535 - nmgCMIndex ID = 536 - nnIndex ID = 537 - nnNOIndex ID = 538 - nnhIndex ID = 539 - nnhCMIndex ID = 540 - noIndex ID = 541 - nqoIndex ID = 542 - nrIndex ID = 543 - nsoIndex ID = 544 - nusIndex ID = 545 - nusSSIndex ID = 546 - nyIndex ID = 547 - nynIndex ID = 548 - nynUGIndex ID = 549 - omIndex ID = 550 - omETIndex ID = 551 - omKEIndex ID = 552 - orIndex ID = 553 - orINIndex ID = 554 - osIndex ID = 555 - osGEIndex ID = 556 - osRUIndex ID = 557 - paIndex ID = 558 - paArabIndex ID = 559 - paArabPKIndex ID = 560 - paGuruIndex ID = 561 - paGuruINIndex ID = 562 - papIndex ID = 563 - plIndex ID = 564 - plPLIndex ID = 565 - prgIndex ID = 566 - prg001Index ID = 567 - psIndex ID = 568 - psAFIndex ID = 569 - ptIndex ID = 570 - ptAOIndex ID = 571 - ptBRIndex ID = 572 - ptCHIndex ID = 573 - ptCVIndex ID = 574 - ptGQIndex ID = 575 - ptGWIndex ID = 576 - ptLUIndex ID = 577 - ptMOIndex ID = 578 - ptMZIndex ID = 579 - ptPTIndex ID = 580 - ptSTIndex ID = 581 - ptTLIndex ID = 582 - quIndex ID = 583 - quBOIndex ID = 584 - quECIndex ID = 585 - quPEIndex ID = 586 - rmIndex ID = 587 - rmCHIndex ID = 588 - rnIndex ID = 589 - rnBIIndex ID = 590 - roIndex ID = 591 - roMDIndex ID = 592 - roROIndex ID = 593 - rofIndex ID = 594 - rofTZIndex ID = 595 - ruIndex ID = 596 - ruBYIndex ID = 597 - ruKGIndex ID = 598 - ruKZIndex ID = 599 - ruMDIndex ID = 600 - ruRUIndex ID = 601 - ruUAIndex ID = 602 - rwIndex ID = 603 - rwRWIndex ID = 604 - rwkIndex ID = 605 - rwkTZIndex ID = 606 - sahIndex ID = 607 - sahRUIndex ID = 608 - saqIndex ID = 609 - saqKEIndex ID = 610 - sbpIndex ID = 611 - sbpTZIndex ID = 612 - sdIndex ID = 613 - sdPKIndex ID = 614 - sdhIndex ID = 615 - seIndex ID = 616 - seFIIndex ID = 617 - seNOIndex ID = 618 - seSEIndex ID = 619 - sehIndex ID = 620 - sehMZIndex ID = 621 - sesIndex ID = 622 - sesMLIndex ID = 623 - sgIndex ID = 624 - sgCFIndex ID = 625 - shIndex ID = 626 - shiIndex ID = 627 - shiLatnIndex ID = 628 - shiLatnMAIndex ID = 629 - shiTfngIndex ID = 630 - shiTfngMAIndex ID = 631 - siIndex ID = 632 - siLKIndex ID = 633 - skIndex ID = 634 - skSKIndex ID = 635 - slIndex ID = 636 - slSIIndex ID = 637 - smaIndex ID = 638 - smiIndex ID = 639 - smjIndex ID = 640 - smnIndex ID = 641 - smnFIIndex ID = 642 - smsIndex ID = 643 - snIndex ID = 644 - snZWIndex ID = 645 - soIndex ID = 646 - soDJIndex ID = 647 - soETIndex ID = 648 - soKEIndex ID = 649 - soSOIndex ID = 650 - sqIndex ID = 651 - sqALIndex ID = 652 - sqMKIndex ID = 653 - sqXKIndex ID = 654 - srIndex ID = 655 - srCyrlIndex ID = 656 - srCyrlBAIndex ID = 657 - srCyrlMEIndex ID = 658 - srCyrlRSIndex ID = 659 - srCyrlXKIndex ID = 660 - srLatnIndex ID = 661 - srLatnBAIndex ID = 662 - srLatnMEIndex ID = 663 - srLatnRSIndex ID = 664 - srLatnXKIndex ID = 665 - ssIndex ID = 666 - ssyIndex ID = 667 - stIndex ID = 668 - svIndex ID = 669 - svAXIndex ID = 670 - svFIIndex ID = 671 - svSEIndex ID = 672 - swIndex ID = 673 - swCDIndex ID = 674 - swKEIndex ID = 675 - swTZIndex ID = 676 - swUGIndex ID = 677 - syrIndex ID = 678 - taIndex ID = 679 - taINIndex ID = 680 - taLKIndex ID = 681 - taMYIndex ID = 682 - taSGIndex ID = 683 - teIndex ID = 684 - teINIndex ID = 685 - teoIndex ID = 686 - teoKEIndex ID = 687 - teoUGIndex ID = 688 - tgIndex ID = 689 - tgTJIndex ID = 690 - thIndex ID = 691 - thTHIndex ID = 692 - tiIndex ID = 693 - tiERIndex ID = 694 - tiETIndex ID = 695 - tigIndex ID = 696 - tkIndex ID = 697 - tkTMIndex ID = 698 - tlIndex ID = 699 - tnIndex ID = 700 - toIndex ID = 701 - toTOIndex ID = 702 - trIndex ID = 703 - trCYIndex ID = 704 - trTRIndex ID = 705 - tsIndex ID = 706 - ttIndex ID = 707 - ttRUIndex ID = 708 - twqIndex ID = 709 - twqNEIndex ID = 710 - tzmIndex ID = 711 - tzmMAIndex ID = 712 - ugIndex ID = 713 - ugCNIndex ID = 714 - ukIndex ID = 715 - ukUAIndex ID = 716 - urIndex ID = 717 - urINIndex ID = 718 - urPKIndex ID = 719 - uzIndex ID = 720 - uzArabIndex ID = 721 - uzArabAFIndex ID = 722 - uzCyrlIndex ID = 723 - uzCyrlUZIndex ID = 724 - uzLatnIndex ID = 725 - uzLatnUZIndex ID = 726 - vaiIndex ID = 727 - vaiLatnIndex ID = 728 - vaiLatnLRIndex ID = 729 - vaiVaiiIndex ID = 730 - vaiVaiiLRIndex ID = 731 - veIndex ID = 732 - viIndex ID = 733 - viVNIndex ID = 734 - voIndex ID = 735 - vo001Index ID = 736 - vunIndex ID = 737 - vunTZIndex ID = 738 - waIndex ID = 739 - waeIndex ID = 740 - waeCHIndex ID = 741 - woIndex ID = 742 - woSNIndex ID = 743 - xhIndex ID = 744 - xogIndex ID = 745 - xogUGIndex ID = 746 - yavIndex ID = 747 - yavCMIndex ID = 748 - yiIndex ID = 749 - yi001Index ID = 750 - yoIndex ID = 751 - yoBJIndex ID = 752 - yoNGIndex ID = 753 - yueIndex ID = 754 - yueHansIndex ID = 755 - yueHansCNIndex ID = 756 - yueHantIndex ID = 757 - yueHantHKIndex ID = 758 - zghIndex ID = 759 - zghMAIndex ID = 760 - zhIndex ID = 761 - zhHansIndex ID = 762 - zhHansCNIndex ID = 763 - zhHansHKIndex ID = 764 - zhHansMOIndex ID = 765 - zhHansSGIndex ID = 766 - zhHantIndex ID = 767 - zhHantHKIndex ID = 768 - zhHantMOIndex ID = 769 - zhHantTWIndex ID = 770 - zuIndex ID = 771 - zuZAIndex ID = 772 - caESvalenciaIndex ID = 773 - enUSuvaposixIndex ID = 774 -) - -var coreTags = []language.CompactCoreInfo{ // 773 elements - // Entry 0 - 1F - 0x00000000, 0x01600000, 0x016000d2, 0x01600161, - 0x01c00000, 0x01c00052, 0x02100000, 0x02100080, - 0x02700000, 0x0270006f, 0x03a00000, 0x03a00001, - 0x03a00023, 0x03a00039, 0x03a00062, 0x03a00067, - 0x03a0006b, 0x03a0006c, 0x03a0006d, 0x03a00097, - 0x03a0009b, 0x03a000a1, 0x03a000a8, 0x03a000ac, - 0x03a000b0, 0x03a000b9, 0x03a000ba, 0x03a000c9, - 0x03a000e1, 0x03a000ed, 0x03a000f3, 0x03a00108, - // Entry 20 - 3F - 0x03a0010b, 0x03a00115, 0x03a00117, 0x03a0011c, - 0x03a00120, 0x03a00128, 0x03a0015e, 0x04000000, - 0x04300000, 0x04300099, 0x04400000, 0x0440012f, - 0x04800000, 0x0480006e, 0x05800000, 0x05820000, - 0x05820032, 0x0585a000, 0x0585a032, 0x05e00000, - 0x05e00052, 0x07100000, 0x07100047, 0x07500000, - 0x07500162, 0x07900000, 0x0790012f, 0x07e00000, - 0x07e00038, 0x08200000, 0x0a000000, 0x0a0000c3, - // Entry 40 - 5F - 0x0a500000, 0x0a500035, 0x0a500099, 0x0a900000, - 0x0a900053, 0x0a900099, 0x0b200000, 0x0b200078, - 0x0b500000, 0x0b500099, 0x0b700000, 0x0b720000, - 0x0b720033, 0x0b75a000, 0x0b75a033, 0x0d700000, - 0x0d700022, 0x0d70006e, 0x0d700078, 0x0d70009e, - 0x0db00000, 0x0db00035, 0x0db00099, 0x0dc00000, - 0x0dc00106, 0x0df00000, 0x0df00131, 0x0e500000, - 0x0e500135, 0x0e900000, 0x0e90009b, 0x0e90009c, - // Entry 60 - 7F - 0x0fa00000, 0x0fa0005e, 0x0fe00000, 0x0fe00106, - 0x10000000, 0x1000007b, 0x10100000, 0x10100063, - 0x10100082, 0x10800000, 0x108000a4, 0x10d00000, - 0x10d0002e, 0x10d00036, 0x10d0004e, 0x10d00060, - 0x10d0009e, 0x10d000b2, 0x10d000b7, 0x11700000, - 0x117000d4, 0x11f00000, 0x11f00060, 0x12400000, - 0x12400052, 0x12800000, 0x12b00000, 0x12b00114, - 0x12d00000, 0x12d00043, 0x12f00000, 0x12f000a4, - // Entry 80 - 9F - 0x13000000, 0x13000080, 0x13000122, 0x13600000, - 0x1360005d, 0x13600087, 0x13900000, 0x13900001, - 0x1390001a, 0x13900025, 0x13900026, 0x1390002d, - 0x1390002e, 0x1390002f, 0x13900034, 0x13900036, - 0x1390003a, 0x1390003d, 0x13900042, 0x13900046, - 0x13900048, 0x13900049, 0x1390004a, 0x1390004e, - 0x13900050, 0x13900052, 0x1390005c, 0x1390005d, - 0x13900060, 0x13900061, 0x13900063, 0x13900064, - // Entry A0 - BF - 0x1390006d, 0x13900072, 0x13900073, 0x13900074, - 0x13900075, 0x1390007b, 0x1390007c, 0x1390007f, - 0x13900080, 0x13900081, 0x13900083, 0x1390008a, - 0x1390008c, 0x1390008d, 0x13900096, 0x13900097, - 0x13900098, 0x13900099, 0x1390009a, 0x1390009f, - 0x139000a0, 0x139000a4, 0x139000a7, 0x139000a9, - 0x139000ad, 0x139000b1, 0x139000b4, 0x139000b5, - 0x139000bf, 0x139000c0, 0x139000c6, 0x139000c7, - // Entry C0 - DF - 0x139000ca, 0x139000cb, 0x139000cc, 0x139000ce, - 0x139000d0, 0x139000d2, 0x139000d5, 0x139000d6, - 0x139000d9, 0x139000dd, 0x139000df, 0x139000e0, - 0x139000e6, 0x139000e7, 0x139000e8, 0x139000eb, - 0x139000ec, 0x139000f0, 0x13900107, 0x13900109, - 0x1390010a, 0x1390010b, 0x1390010c, 0x1390010d, - 0x1390010e, 0x1390010f, 0x13900112, 0x13900117, - 0x1390011b, 0x1390011d, 0x1390011f, 0x13900125, - // Entry E0 - FF - 0x13900129, 0x1390012c, 0x1390012d, 0x1390012f, - 0x13900131, 0x13900133, 0x13900135, 0x13900139, - 0x1390013c, 0x1390013d, 0x1390013f, 0x13900142, - 0x13900161, 0x13900162, 0x13900164, 0x13c00000, - 0x13c00001, 0x13e00000, 0x13e0001f, 0x13e0002c, - 0x13e0003f, 0x13e00041, 0x13e00048, 0x13e00051, - 0x13e00054, 0x13e00056, 0x13e00059, 0x13e00065, - 0x13e00068, 0x13e00069, 0x13e0006e, 0x13e00086, - // Entry 100 - 11F - 0x13e00089, 0x13e0008f, 0x13e00094, 0x13e000cf, - 0x13e000d8, 0x13e000e2, 0x13e000e4, 0x13e000e7, - 0x13e000ec, 0x13e000f1, 0x13e0011a, 0x13e00135, - 0x13e00136, 0x13e0013b, 0x14000000, 0x1400006a, - 0x14500000, 0x1450006e, 0x14600000, 0x14600052, - 0x14800000, 0x14800024, 0x1480009c, 0x14e00000, - 0x14e00052, 0x14e00084, 0x14e000c9, 0x14e00114, - 0x15100000, 0x15100072, 0x15300000, 0x153000e7, - // Entry 120 - 13F - 0x15800000, 0x15800063, 0x15800076, 0x15e00000, - 0x15e00036, 0x15e00037, 0x15e0003a, 0x15e0003b, - 0x15e0003c, 0x15e00049, 0x15e0004b, 0x15e0004c, - 0x15e0004d, 0x15e0004e, 0x15e0004f, 0x15e00052, - 0x15e00062, 0x15e00067, 0x15e00078, 0x15e0007a, - 0x15e0007e, 0x15e00084, 0x15e00085, 0x15e00086, - 0x15e00091, 0x15e000a8, 0x15e000b7, 0x15e000ba, - 0x15e000bb, 0x15e000be, 0x15e000bf, 0x15e000c3, - // Entry 140 - 15F - 0x15e000c8, 0x15e000c9, 0x15e000cc, 0x15e000d3, - 0x15e000d4, 0x15e000e5, 0x15e000ea, 0x15e00102, - 0x15e00107, 0x15e0010a, 0x15e00114, 0x15e0011c, - 0x15e00120, 0x15e00122, 0x15e00128, 0x15e0013f, - 0x15e00140, 0x15e0015f, 0x16900000, 0x1690009e, - 0x16d00000, 0x16d000d9, 0x16e00000, 0x16e00096, - 0x17e00000, 0x17e0007b, 0x19000000, 0x1900006e, - 0x1a300000, 0x1a30004e, 0x1a300078, 0x1a3000b2, - // Entry 160 - 17F - 0x1a400000, 0x1a400099, 0x1a900000, 0x1ab00000, - 0x1ab000a4, 0x1ac00000, 0x1ac00098, 0x1b400000, - 0x1b400080, 0x1b4000d4, 0x1b4000d6, 0x1b800000, - 0x1b800135, 0x1bc00000, 0x1bc00097, 0x1be00000, - 0x1be00099, 0x1d100000, 0x1d100033, 0x1d100090, - 0x1d200000, 0x1d200060, 0x1d500000, 0x1d500092, - 0x1d700000, 0x1d700028, 0x1e100000, 0x1e100095, - 0x1e700000, 0x1e7000d6, 0x1ea00000, 0x1ea00053, - // Entry 180 - 19F - 0x1f300000, 0x1f500000, 0x1f800000, 0x1f80009d, - 0x1f900000, 0x1f90004e, 0x1f90009e, 0x1f900113, - 0x1f900138, 0x1fa00000, 0x1fb00000, 0x20000000, - 0x200000a2, 0x20300000, 0x20700000, 0x20700052, - 0x20800000, 0x20a00000, 0x20a0012f, 0x20e00000, - 0x20f00000, 0x21000000, 0x2100007d, 0x21200000, - 0x21200067, 0x21600000, 0x21700000, 0x217000a4, - 0x21f00000, 0x22300000, 0x2230012f, 0x22700000, - // Entry 1A0 - 1BF - 0x2270005a, 0x23400000, 0x234000c3, 0x23900000, - 0x239000a4, 0x24200000, 0x242000ae, 0x24400000, - 0x24400052, 0x24500000, 0x24500082, 0x24600000, - 0x246000a4, 0x24a00000, 0x24a000a6, 0x25100000, - 0x25100099, 0x25400000, 0x254000aa, 0x254000ab, - 0x25600000, 0x25600099, 0x26a00000, 0x26a00099, - 0x26b00000, 0x26b0012f, 0x26d00000, 0x26d00052, - 0x26e00000, 0x26e00060, 0x27400000, 0x28100000, - // Entry 1C0 - 1DF - 0x2810007b, 0x28a00000, 0x28a000a5, 0x29100000, - 0x2910012f, 0x29500000, 0x295000b7, 0x2a300000, - 0x2a300131, 0x2af00000, 0x2af00135, 0x2b500000, - 0x2b50002a, 0x2b50004b, 0x2b50004c, 0x2b50004d, - 0x2b800000, 0x2b8000af, 0x2bf00000, 0x2bf0009b, - 0x2bf0009c, 0x2c000000, 0x2c0000b6, 0x2c200000, - 0x2c20004b, 0x2c400000, 0x2c4000a4, 0x2c500000, - 0x2c5000a4, 0x2c700000, 0x2c7000b8, 0x2d100000, - // Entry 1E0 - 1FF - 0x2d1000a4, 0x2d10012f, 0x2e900000, 0x2e9000a4, - 0x2ed00000, 0x2ed000cc, 0x2f100000, 0x2f1000bf, - 0x2f200000, 0x2f2000d1, 0x2f400000, 0x2f400052, - 0x2ff00000, 0x2ff000c2, 0x30400000, 0x30400099, - 0x30b00000, 0x30b000c5, 0x31000000, 0x31b00000, - 0x31b00099, 0x31f00000, 0x31f0003e, 0x31f000d0, - 0x31f0010d, 0x32000000, 0x320000cb, 0x32500000, - 0x32500052, 0x33100000, 0x331000c4, 0x33a00000, - // Entry 200 - 21F - 0x33a0009c, 0x34100000, 0x34500000, 0x345000d2, - 0x34700000, 0x347000da, 0x34700110, 0x34e00000, - 0x34e00164, 0x35000000, 0x35000060, 0x350000d9, - 0x35100000, 0x35100099, 0x351000db, 0x36700000, - 0x36700030, 0x36700036, 0x36700040, 0x3670005b, - 0x367000d9, 0x36700116, 0x3670011b, 0x36800000, - 0x36800052, 0x36a00000, 0x36a000da, 0x36c00000, - 0x36c00052, 0x36f00000, 0x37500000, 0x37600000, - // Entry 220 - 23F - 0x37a00000, 0x38000000, 0x38000117, 0x38700000, - 0x38900000, 0x38900131, 0x39000000, 0x3900006f, - 0x390000a4, 0x39500000, 0x39500099, 0x39800000, - 0x3980007d, 0x39800106, 0x39d00000, 0x39d05000, - 0x39d050e8, 0x39d36000, 0x39d36099, 0x3a100000, - 0x3b300000, 0x3b3000e9, 0x3bd00000, 0x3bd00001, - 0x3be00000, 0x3be00024, 0x3c000000, 0x3c00002a, - 0x3c000041, 0x3c00004e, 0x3c00005a, 0x3c000086, - // Entry 240 - 25F - 0x3c00008b, 0x3c0000b7, 0x3c0000c6, 0x3c0000d1, - 0x3c0000ee, 0x3c000118, 0x3c000126, 0x3c400000, - 0x3c40003f, 0x3c400069, 0x3c4000e4, 0x3d400000, - 0x3d40004e, 0x3d900000, 0x3d90003a, 0x3dc00000, - 0x3dc000bc, 0x3dc00104, 0x3de00000, 0x3de0012f, - 0x3e200000, 0x3e200047, 0x3e2000a5, 0x3e2000ae, - 0x3e2000bc, 0x3e200106, 0x3e200130, 0x3e500000, - 0x3e500107, 0x3e600000, 0x3e60012f, 0x3eb00000, - // Entry 260 - 27F - 0x3eb00106, 0x3ec00000, 0x3ec000a4, 0x3f300000, - 0x3f30012f, 0x3fa00000, 0x3fa000e8, 0x3fc00000, - 0x3fd00000, 0x3fd00072, 0x3fd000da, 0x3fd0010c, - 0x3ff00000, 0x3ff000d1, 0x40100000, 0x401000c3, - 0x40200000, 0x4020004c, 0x40700000, 0x40800000, - 0x4085a000, 0x4085a0ba, 0x408e8000, 0x408e80ba, - 0x40c00000, 0x40c000b3, 0x41200000, 0x41200111, - 0x41600000, 0x4160010f, 0x41c00000, 0x41d00000, - // Entry 280 - 29F - 0x41e00000, 0x41f00000, 0x41f00072, 0x42200000, - 0x42300000, 0x42300164, 0x42900000, 0x42900062, - 0x4290006f, 0x429000a4, 0x42900115, 0x43100000, - 0x43100027, 0x431000c2, 0x4310014d, 0x43200000, - 0x43220000, 0x43220033, 0x432200bd, 0x43220105, - 0x4322014d, 0x4325a000, 0x4325a033, 0x4325a0bd, - 0x4325a105, 0x4325a14d, 0x43700000, 0x43a00000, - 0x43b00000, 0x44400000, 0x44400031, 0x44400072, - // Entry 2A0 - 2BF - 0x4440010c, 0x44500000, 0x4450004b, 0x445000a4, - 0x4450012f, 0x44500131, 0x44e00000, 0x45000000, - 0x45000099, 0x450000b3, 0x450000d0, 0x4500010d, - 0x46100000, 0x46100099, 0x46400000, 0x464000a4, - 0x46400131, 0x46700000, 0x46700124, 0x46b00000, - 0x46b00123, 0x46f00000, 0x46f0006d, 0x46f0006f, - 0x47100000, 0x47600000, 0x47600127, 0x47a00000, - 0x48000000, 0x48200000, 0x48200129, 0x48a00000, - // Entry 2C0 - 2DF - 0x48a0005d, 0x48a0012b, 0x48e00000, 0x49400000, - 0x49400106, 0x4a400000, 0x4a4000d4, 0x4a900000, - 0x4a9000ba, 0x4ac00000, 0x4ac00053, 0x4ae00000, - 0x4ae00130, 0x4b400000, 0x4b400099, 0x4b4000e8, - 0x4bc00000, 0x4bc05000, 0x4bc05024, 0x4bc20000, - 0x4bc20137, 0x4bc5a000, 0x4bc5a137, 0x4be00000, - 0x4be5a000, 0x4be5a0b4, 0x4bef1000, 0x4bef10b4, - 0x4c000000, 0x4c300000, 0x4c30013e, 0x4c900000, - // Entry 2E0 - 2FF - 0x4c900001, 0x4cc00000, 0x4cc0012f, 0x4ce00000, - 0x4cf00000, 0x4cf0004e, 0x4e500000, 0x4e500114, - 0x4f200000, 0x4fb00000, 0x4fb00131, 0x50900000, - 0x50900052, 0x51200000, 0x51200001, 0x51800000, - 0x5180003b, 0x518000d6, 0x51f00000, 0x51f3b000, - 0x51f3b053, 0x51f3c000, 0x51f3c08d, 0x52800000, - 0x528000ba, 0x52900000, 0x5293b000, 0x5293b053, - 0x5293b08d, 0x5293b0c6, 0x5293b10d, 0x5293c000, - // Entry 300 - 31F - 0x5293c08d, 0x5293c0c6, 0x5293c12e, 0x52f00000, - 0x52f00161, -} // Size: 3116 bytes - -const specialTagsStr string = "ca-ES-valencia en-US-u-va-posix" - -// Total table size 3147 bytes (3KiB); checksum: 6772C83C diff --git a/vendor/golang.org/x/text/internal/language/compact/tags.go b/vendor/golang.org/x/text/internal/language/compact/tags.go deleted file mode 100644 index ca135d2..0000000 --- a/vendor/golang.org/x/text/internal/language/compact/tags.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2013 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 compact - -var ( - und = Tag{} - - Und Tag = Tag{} - - Afrikaans Tag = Tag{language: afIndex, locale: afIndex} - Amharic Tag = Tag{language: amIndex, locale: amIndex} - Arabic Tag = Tag{language: arIndex, locale: arIndex} - ModernStandardArabic Tag = Tag{language: ar001Index, locale: ar001Index} - Azerbaijani Tag = Tag{language: azIndex, locale: azIndex} - Bulgarian Tag = Tag{language: bgIndex, locale: bgIndex} - Bengali Tag = Tag{language: bnIndex, locale: bnIndex} - Catalan Tag = Tag{language: caIndex, locale: caIndex} - Czech Tag = Tag{language: csIndex, locale: csIndex} - Danish Tag = Tag{language: daIndex, locale: daIndex} - German Tag = Tag{language: deIndex, locale: deIndex} - Greek Tag = Tag{language: elIndex, locale: elIndex} - English Tag = Tag{language: enIndex, locale: enIndex} - AmericanEnglish Tag = Tag{language: enUSIndex, locale: enUSIndex} - BritishEnglish Tag = Tag{language: enGBIndex, locale: enGBIndex} - Spanish Tag = Tag{language: esIndex, locale: esIndex} - EuropeanSpanish Tag = Tag{language: esESIndex, locale: esESIndex} - LatinAmericanSpanish Tag = Tag{language: es419Index, locale: es419Index} - Estonian Tag = Tag{language: etIndex, locale: etIndex} - Persian Tag = Tag{language: faIndex, locale: faIndex} - Finnish Tag = Tag{language: fiIndex, locale: fiIndex} - Filipino Tag = Tag{language: filIndex, locale: filIndex} - French Tag = Tag{language: frIndex, locale: frIndex} - CanadianFrench Tag = Tag{language: frCAIndex, locale: frCAIndex} - Gujarati Tag = Tag{language: guIndex, locale: guIndex} - Hebrew Tag = Tag{language: heIndex, locale: heIndex} - Hindi Tag = Tag{language: hiIndex, locale: hiIndex} - Croatian Tag = Tag{language: hrIndex, locale: hrIndex} - Hungarian Tag = Tag{language: huIndex, locale: huIndex} - Armenian Tag = Tag{language: hyIndex, locale: hyIndex} - Indonesian Tag = Tag{language: idIndex, locale: idIndex} - Icelandic Tag = Tag{language: isIndex, locale: isIndex} - Italian Tag = Tag{language: itIndex, locale: itIndex} - Japanese Tag = Tag{language: jaIndex, locale: jaIndex} - Georgian Tag = Tag{language: kaIndex, locale: kaIndex} - Kazakh Tag = Tag{language: kkIndex, locale: kkIndex} - Khmer Tag = Tag{language: kmIndex, locale: kmIndex} - Kannada Tag = Tag{language: knIndex, locale: knIndex} - Korean Tag = Tag{language: koIndex, locale: koIndex} - Kirghiz Tag = Tag{language: kyIndex, locale: kyIndex} - Lao Tag = Tag{language: loIndex, locale: loIndex} - Lithuanian Tag = Tag{language: ltIndex, locale: ltIndex} - Latvian Tag = Tag{language: lvIndex, locale: lvIndex} - Macedonian Tag = Tag{language: mkIndex, locale: mkIndex} - Malayalam Tag = Tag{language: mlIndex, locale: mlIndex} - Mongolian Tag = Tag{language: mnIndex, locale: mnIndex} - Marathi Tag = Tag{language: mrIndex, locale: mrIndex} - Malay Tag = Tag{language: msIndex, locale: msIndex} - Burmese Tag = Tag{language: myIndex, locale: myIndex} - Nepali Tag = Tag{language: neIndex, locale: neIndex} - Dutch Tag = Tag{language: nlIndex, locale: nlIndex} - Norwegian Tag = Tag{language: noIndex, locale: noIndex} - Punjabi Tag = Tag{language: paIndex, locale: paIndex} - Polish Tag = Tag{language: plIndex, locale: plIndex} - Portuguese Tag = Tag{language: ptIndex, locale: ptIndex} - BrazilianPortuguese Tag = Tag{language: ptBRIndex, locale: ptBRIndex} - EuropeanPortuguese Tag = Tag{language: ptPTIndex, locale: ptPTIndex} - Romanian Tag = Tag{language: roIndex, locale: roIndex} - Russian Tag = Tag{language: ruIndex, locale: ruIndex} - Sinhala Tag = Tag{language: siIndex, locale: siIndex} - Slovak Tag = Tag{language: skIndex, locale: skIndex} - Slovenian Tag = Tag{language: slIndex, locale: slIndex} - Albanian Tag = Tag{language: sqIndex, locale: sqIndex} - Serbian Tag = Tag{language: srIndex, locale: srIndex} - SerbianLatin Tag = Tag{language: srLatnIndex, locale: srLatnIndex} - Swedish Tag = Tag{language: svIndex, locale: svIndex} - Swahili Tag = Tag{language: swIndex, locale: swIndex} - Tamil Tag = Tag{language: taIndex, locale: taIndex} - Telugu Tag = Tag{language: teIndex, locale: teIndex} - Thai Tag = Tag{language: thIndex, locale: thIndex} - Turkish Tag = Tag{language: trIndex, locale: trIndex} - Ukrainian Tag = Tag{language: ukIndex, locale: ukIndex} - Urdu Tag = Tag{language: urIndex, locale: urIndex} - Uzbek Tag = Tag{language: uzIndex, locale: uzIndex} - Vietnamese Tag = Tag{language: viIndex, locale: viIndex} - Chinese Tag = Tag{language: zhIndex, locale: zhIndex} - SimplifiedChinese Tag = Tag{language: zhHansIndex, locale: zhHansIndex} - TraditionalChinese Tag = Tag{language: zhHantIndex, locale: zhHantIndex} - Zulu Tag = Tag{language: zuIndex, locale: zuIndex} -) diff --git a/vendor/golang.org/x/text/internal/language/compose.go b/vendor/golang.org/x/text/internal/language/compose.go deleted file mode 100644 index 4ae78e0..0000000 --- a/vendor/golang.org/x/text/internal/language/compose.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2018 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 language - -import ( - "sort" - "strings" -) - -// A Builder allows constructing a Tag from individual components. -// Its main user is Compose in the top-level language package. -type Builder struct { - Tag Tag - - private string // the x extension - variants []string - extensions []string -} - -// Make returns a new Tag from the current settings. -func (b *Builder) Make() Tag { - t := b.Tag - - if len(b.extensions) > 0 || len(b.variants) > 0 { - sort.Sort(sortVariants(b.variants)) - sort.Strings(b.extensions) - - if b.private != "" { - b.extensions = append(b.extensions, b.private) - } - n := maxCoreSize + tokenLen(b.variants...) + tokenLen(b.extensions...) - buf := make([]byte, n) - p := t.genCoreBytes(buf) - t.pVariant = byte(p) - p += appendTokens(buf[p:], b.variants...) - t.pExt = uint16(p) - p += appendTokens(buf[p:], b.extensions...) - t.str = string(buf[:p]) - // We may not always need to remake the string, but when or when not - // to do so is rather tricky. - scan := makeScanner(buf[:p]) - t, _ = parse(&scan, "") - return t - - } else if b.private != "" { - t.str = b.private - t.RemakeString() - } - return t -} - -// SetTag copies all the settings from a given Tag. Any previously set values -// are discarded. -func (b *Builder) SetTag(t Tag) { - b.Tag.LangID = t.LangID - b.Tag.RegionID = t.RegionID - b.Tag.ScriptID = t.ScriptID - // TODO: optimize - b.variants = b.variants[:0] - if variants := t.Variants(); variants != "" { - for _, vr := range strings.Split(variants[1:], "-") { - b.variants = append(b.variants, vr) - } - } - b.extensions, b.private = b.extensions[:0], "" - for _, e := range t.Extensions() { - b.AddExt(e) - } -} - -// AddExt adds extension e to the tag. e must be a valid extension as returned -// by Tag.Extension. If the extension already exists, it will be discarded, -// except for a -u extension, where non-existing key-type pairs will added. -func (b *Builder) AddExt(e string) { - if e[0] == 'x' { - if b.private == "" { - b.private = e - } - return - } - for i, s := range b.extensions { - if s[0] == e[0] { - if e[0] == 'u' { - b.extensions[i] += e[1:] - } - return - } - } - b.extensions = append(b.extensions, e) -} - -// SetExt sets the extension e to the tag. e must be a valid extension as -// returned by Tag.Extension. If the extension already exists, it will be -// overwritten, except for a -u extension, where the individual key-type pairs -// will be set. -func (b *Builder) SetExt(e string) { - if e[0] == 'x' { - b.private = e - return - } - for i, s := range b.extensions { - if s[0] == e[0] { - if e[0] == 'u' { - b.extensions[i] = e + s[1:] - } else { - b.extensions[i] = e - } - return - } - } - b.extensions = append(b.extensions, e) -} - -// AddVariant adds any number of variants. -func (b *Builder) AddVariant(v ...string) { - for _, v := range v { - if v != "" { - b.variants = append(b.variants, v) - } - } -} - -// ClearVariants removes any variants previously added, including those -// copied from a Tag in SetTag. -func (b *Builder) ClearVariants() { - b.variants = b.variants[:0] -} - -// ClearExtensions removes any extensions previously added, including those -// copied from a Tag in SetTag. -func (b *Builder) ClearExtensions() { - b.private = "" - b.extensions = b.extensions[:0] -} - -func tokenLen(token ...string) (n int) { - for _, t := range token { - n += len(t) + 1 - } - return -} - -func appendTokens(b []byte, token ...string) int { - p := 0 - for _, t := range token { - b[p] = '-' - copy(b[p+1:], t) - p += 1 + len(t) - } - return p -} - -type sortVariants []string - -func (s sortVariants) Len() int { - return len(s) -} - -func (s sortVariants) Swap(i, j int) { - s[j], s[i] = s[i], s[j] -} - -func (s sortVariants) Less(i, j int) bool { - return variantIndex[s[i]] < variantIndex[s[j]] -} diff --git a/vendor/golang.org/x/text/internal/language/coverage.go b/vendor/golang.org/x/text/internal/language/coverage.go deleted file mode 100644 index 9b20b88..0000000 --- a/vendor/golang.org/x/text/internal/language/coverage.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2014 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 language - -// BaseLanguages returns the list of all supported base languages. It generates -// the list by traversing the internal structures. -func BaseLanguages() []Language { - base := make([]Language, 0, NumLanguages) - for i := 0; i < langNoIndexOffset; i++ { - // We included "und" already for the value 0. - if i != nonCanonicalUnd { - base = append(base, Language(i)) - } - } - i := langNoIndexOffset - for _, v := range langNoIndex { - for k := 0; k < 8; k++ { - if v&1 == 1 { - base = append(base, Language(i)) - } - v >>= 1 - i++ - } - } - return base -} diff --git a/vendor/golang.org/x/text/internal/language/language.go b/vendor/golang.org/x/text/internal/language/language.go deleted file mode 100644 index 6105bc7..0000000 --- a/vendor/golang.org/x/text/internal/language/language.go +++ /dev/null @@ -1,627 +0,0 @@ -// Copyright 2013 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. - -//go:generate go run gen.go gen_common.go -output tables.go - -package language // import "golang.org/x/text/internal/language" - -// TODO: Remove above NOTE after: -// - verifying that tables are dropped correctly (most notably matcher tables). - -import ( - "errors" - "fmt" - "strings" -) - -const ( - // maxCoreSize is the maximum size of a BCP 47 tag without variants and - // extensions. Equals max lang (3) + script (4) + max reg (3) + 2 dashes. - maxCoreSize = 12 - - // max99thPercentileSize is a somewhat arbitrary buffer size that presumably - // is large enough to hold at least 99% of the BCP 47 tags. - max99thPercentileSize = 32 - - // maxSimpleUExtensionSize is the maximum size of a -u extension with one - // key-type pair. Equals len("-u-") + key (2) + dash + max value (8). - maxSimpleUExtensionSize = 14 -) - -// Tag represents a BCP 47 language tag. It is used to specify an instance of a -// specific language or locale. All language tag values are guaranteed to be -// well-formed. The zero value of Tag is Und. -type Tag struct { - // TODO: the following fields have the form TagTypeID. This name is chosen - // to allow refactoring the public package without conflicting with its - // Base, Script, and Region methods. Once the transition is fully completed - // the ID can be stripped from the name. - - LangID Language - RegionID Region - // TODO: we will soon run out of positions for ScriptID. Idea: instead of - // storing lang, region, and ScriptID codes, store only the compact index and - // have a lookup table from this code to its expansion. This greatly speeds - // up table lookup, speed up common variant cases. - // This will also immediately free up 3 extra bytes. Also, the pVariant - // field can now be moved to the lookup table, as the compact index uniquely - // determines the offset of a possible variant. - ScriptID Script - pVariant byte // offset in str, includes preceding '-' - pExt uint16 // offset of first extension, includes preceding '-' - - // str is the string representation of the Tag. It will only be used if the - // tag has variants or extensions. - str string -} - -// Make is a convenience wrapper for Parse that omits the error. -// In case of an error, a sensible default is returned. -func Make(s string) Tag { - t, _ := Parse(s) - return t -} - -// Raw returns the raw base language, script and region, without making an -// attempt to infer their values. -// TODO: consider removing -func (t Tag) Raw() (b Language, s Script, r Region) { - return t.LangID, t.ScriptID, t.RegionID -} - -// equalTags compares language, script and region subtags only. -func (t Tag) equalTags(a Tag) bool { - return t.LangID == a.LangID && t.ScriptID == a.ScriptID && t.RegionID == a.RegionID -} - -// IsRoot returns true if t is equal to language "und". -func (t Tag) IsRoot() bool { - if int(t.pVariant) < len(t.str) { - return false - } - return t.equalTags(Und) -} - -// IsPrivateUse reports whether the Tag consists solely of an IsPrivateUse use -// tag. -func (t Tag) IsPrivateUse() bool { - return t.str != "" && t.pVariant == 0 -} - -// RemakeString is used to update t.str in case lang, script or region changed. -// It is assumed that pExt and pVariant still point to the start of the -// respective parts. -func (t *Tag) RemakeString() { - if t.str == "" { - return - } - extra := t.str[t.pVariant:] - if t.pVariant > 0 { - extra = extra[1:] - } - if t.equalTags(Und) && strings.HasPrefix(extra, "x-") { - t.str = extra - t.pVariant = 0 - t.pExt = 0 - return - } - var buf [max99thPercentileSize]byte // avoid extra memory allocation in most cases. - b := buf[:t.genCoreBytes(buf[:])] - if extra != "" { - diff := len(b) - int(t.pVariant) - b = append(b, '-') - b = append(b, extra...) - t.pVariant = uint8(int(t.pVariant) + diff) - t.pExt = uint16(int(t.pExt) + diff) - } else { - t.pVariant = uint8(len(b)) - t.pExt = uint16(len(b)) - } - t.str = string(b) -} - -// genCoreBytes writes a string for the base languages, script and region tags -// to the given buffer and returns the number of bytes written. It will never -// write more than maxCoreSize bytes. -func (t *Tag) genCoreBytes(buf []byte) int { - n := t.LangID.StringToBuf(buf[:]) - if t.ScriptID != 0 { - n += copy(buf[n:], "-") - n += copy(buf[n:], t.ScriptID.String()) - } - if t.RegionID != 0 { - n += copy(buf[n:], "-") - n += copy(buf[n:], t.RegionID.String()) - } - return n -} - -// String returns the canonical string representation of the language tag. -func (t Tag) String() string { - if t.str != "" { - return t.str - } - if t.ScriptID == 0 && t.RegionID == 0 { - return t.LangID.String() - } - buf := [maxCoreSize]byte{} - return string(buf[:t.genCoreBytes(buf[:])]) -} - -// MarshalText implements encoding.TextMarshaler. -func (t Tag) MarshalText() (text []byte, err error) { - if t.str != "" { - text = append(text, t.str...) - } else if t.ScriptID == 0 && t.RegionID == 0 { - text = append(text, t.LangID.String()...) - } else { - buf := [maxCoreSize]byte{} - text = buf[:t.genCoreBytes(buf[:])] - } - return text, nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (t *Tag) UnmarshalText(text []byte) error { - tag, err := Parse(string(text)) - *t = tag - return err -} - -// Variants returns the part of the tag holding all variants or the empty string -// if there are no variants defined. -func (t Tag) Variants() string { - if t.pVariant == 0 { - return "" - } - return t.str[t.pVariant:t.pExt] -} - -// VariantOrPrivateUseTags returns variants or private use tags. -func (t Tag) VariantOrPrivateUseTags() string { - if t.pExt > 0 { - return t.str[t.pVariant:t.pExt] - } - return t.str[t.pVariant:] -} - -// HasString reports whether this tag defines more than just the raw -// components. -func (t Tag) HasString() bool { - return t.str != "" -} - -// Parent returns the CLDR parent of t. In CLDR, missing fields in data for a -// specific language are substituted with fields from the parent language. -// The parent for a language may change for newer versions of CLDR. -func (t Tag) Parent() Tag { - if t.str != "" { - // Strip the variants and extensions. - b, s, r := t.Raw() - t = Tag{LangID: b, ScriptID: s, RegionID: r} - if t.RegionID == 0 && t.ScriptID != 0 && t.LangID != 0 { - base, _ := addTags(Tag{LangID: t.LangID}) - if base.ScriptID == t.ScriptID { - return Tag{LangID: t.LangID} - } - } - return t - } - if t.LangID != 0 { - if t.RegionID != 0 { - maxScript := t.ScriptID - if maxScript == 0 { - max, _ := addTags(t) - maxScript = max.ScriptID - } - - for i := range parents { - if Language(parents[i].lang) == t.LangID && Script(parents[i].maxScript) == maxScript { - for _, r := range parents[i].fromRegion { - if Region(r) == t.RegionID { - return Tag{ - LangID: t.LangID, - ScriptID: Script(parents[i].script), - RegionID: Region(parents[i].toRegion), - } - } - } - } - } - - // Strip the script if it is the default one. - base, _ := addTags(Tag{LangID: t.LangID}) - if base.ScriptID != maxScript { - return Tag{LangID: t.LangID, ScriptID: maxScript} - } - return Tag{LangID: t.LangID} - } else if t.ScriptID != 0 { - // The parent for an base-script pair with a non-default script is - // "und" instead of the base language. - base, _ := addTags(Tag{LangID: t.LangID}) - if base.ScriptID != t.ScriptID { - return Und - } - return Tag{LangID: t.LangID} - } - } - return Und -} - -// ParseExtension parses s as an extension and returns it on success. -func ParseExtension(s string) (ext string, err error) { - defer func() { - if recover() != nil { - ext = "" - err = ErrSyntax - } - }() - - scan := makeScannerString(s) - var end int - if n := len(scan.token); n != 1 { - return "", ErrSyntax - } - scan.toLower(0, len(scan.b)) - end = parseExtension(&scan) - if end != len(s) { - return "", ErrSyntax - } - return string(scan.b), nil -} - -// HasVariants reports whether t has variants. -func (t Tag) HasVariants() bool { - return uint16(t.pVariant) < t.pExt -} - -// HasExtensions reports whether t has extensions. -func (t Tag) HasExtensions() bool { - return int(t.pExt) < len(t.str) -} - -// Extension returns the extension of type x for tag t. It will return -// false for ok if t does not have the requested extension. The returned -// extension will be invalid in this case. -func (t Tag) Extension(x byte) (ext string, ok bool) { - for i := int(t.pExt); i < len(t.str)-1; { - var ext string - i, ext = getExtension(t.str, i) - if ext[0] == x { - return ext, true - } - } - return "", false -} - -// Extensions returns all extensions of t. -func (t Tag) Extensions() []string { - e := []string{} - for i := int(t.pExt); i < len(t.str)-1; { - var ext string - i, ext = getExtension(t.str, i) - e = append(e, ext) - } - return e -} - -// TypeForKey returns the type associated with the given key, where key and type -// are of the allowed values defined for the Unicode locale extension ('u') in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -// TypeForKey will traverse the inheritance chain to get the correct value. -// -// If there are multiple types associated with a key, only the first will be -// returned. If there is no type associated with a key, it returns the empty -// string. -func (t Tag) TypeForKey(key string) string { - if _, start, end, _ := t.findTypeForKey(key); end != start { - s := t.str[start:end] - if p := strings.IndexByte(s, '-'); p >= 0 { - s = s[:p] - } - return s - } - return "" -} - -var ( - errPrivateUse = errors.New("cannot set a key on a private use tag") - errInvalidArguments = errors.New("invalid key or type") -) - -// SetTypeForKey returns a new Tag with the key set to type, where key and type -// are of the allowed values defined for the Unicode locale extension ('u') in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -// An empty value removes an existing pair with the same key. -func (t Tag) SetTypeForKey(key, value string) (Tag, error) { - if t.IsPrivateUse() { - return t, errPrivateUse - } - if len(key) != 2 { - return t, errInvalidArguments - } - - // Remove the setting if value is "". - if value == "" { - start, sep, end, _ := t.findTypeForKey(key) - if start != sep { - // Remove a possible empty extension. - switch { - case t.str[start-2] != '-': // has previous elements. - case end == len(t.str), // end of string - end+2 < len(t.str) && t.str[end+2] == '-': // end of extension - start -= 2 - } - if start == int(t.pVariant) && end == len(t.str) { - t.str = "" - t.pVariant, t.pExt = 0, 0 - } else { - t.str = fmt.Sprintf("%s%s", t.str[:start], t.str[end:]) - } - } - return t, nil - } - - if len(value) < 3 || len(value) > 8 { - return t, errInvalidArguments - } - - var ( - buf [maxCoreSize + maxSimpleUExtensionSize]byte - uStart int // start of the -u extension. - ) - - // Generate the tag string if needed. - if t.str == "" { - uStart = t.genCoreBytes(buf[:]) - buf[uStart] = '-' - uStart++ - } - - // Create new key-type pair and parse it to verify. - b := buf[uStart:] - copy(b, "u-") - copy(b[2:], key) - b[4] = '-' - b = b[:5+copy(b[5:], value)] - scan := makeScanner(b) - if parseExtensions(&scan); scan.err != nil { - return t, scan.err - } - - // Assemble the replacement string. - if t.str == "" { - t.pVariant, t.pExt = byte(uStart-1), uint16(uStart-1) - t.str = string(buf[:uStart+len(b)]) - } else { - s := t.str - start, sep, end, hasExt := t.findTypeForKey(key) - if start == sep { - if hasExt { - b = b[2:] - } - t.str = fmt.Sprintf("%s-%s%s", s[:sep], b, s[end:]) - } else { - t.str = fmt.Sprintf("%s-%s%s", s[:start+3], value, s[end:]) - } - } - return t, nil -} - -// findKeyAndType returns the start and end position for the type corresponding -// to key or the point at which to insert the key-value pair if the type -// wasn't found. The hasExt return value reports whether an -u extension was present. -// Note: the extensions are typically very small and are likely to contain -// only one key-type pair. -func (t Tag) findTypeForKey(key string) (start, sep, end int, hasExt bool) { - p := int(t.pExt) - if len(key) != 2 || p == len(t.str) || p == 0 { - return p, p, p, false - } - s := t.str - - // Find the correct extension. - for p++; s[p] != 'u'; p++ { - if s[p] > 'u' { - p-- - return p, p, p, false - } - if p = nextExtension(s, p); p == len(s) { - return len(s), len(s), len(s), false - } - } - // Proceed to the hyphen following the extension name. - p++ - - // curKey is the key currently being processed. - curKey := "" - - // Iterate over keys until we get the end of a section. - for { - end = p - for p++; p < len(s) && s[p] != '-'; p++ { - } - n := p - end - 1 - if n <= 2 && curKey == key { - if sep < end { - sep++ - } - return start, sep, end, true - } - switch n { - case 0, // invalid string - 1: // next extension - return end, end, end, true - case 2: - // next key - curKey = s[end+1 : p] - if curKey > key { - return end, end, end, true - } - start = end - sep = p - } - } -} - -// ParseBase parses a 2- or 3-letter ISO 639 code. -// It returns a ValueError if s is a well-formed but unknown language identifier -// or another error if another error occurred. -func ParseBase(s string) (l Language, err error) { - defer func() { - if recover() != nil { - l = 0 - err = ErrSyntax - } - }() - - if n := len(s); n < 2 || 3 < n { - return 0, ErrSyntax - } - var buf [3]byte - return getLangID(buf[:copy(buf[:], s)]) -} - -// ParseScript parses a 4-letter ISO 15924 code. -// It returns a ValueError if s is a well-formed but unknown script identifier -// or another error if another error occurred. -func ParseScript(s string) (scr Script, err error) { - defer func() { - if recover() != nil { - scr = 0 - err = ErrSyntax - } - }() - - if len(s) != 4 { - return 0, ErrSyntax - } - var buf [4]byte - return getScriptID(script, buf[:copy(buf[:], s)]) -} - -// EncodeM49 returns the Region for the given UN M.49 code. -// It returns an error if r is not a valid code. -func EncodeM49(r int) (Region, error) { - return getRegionM49(r) -} - -// ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code. -// It returns a ValueError if s is a well-formed but unknown region identifier -// or another error if another error occurred. -func ParseRegion(s string) (r Region, err error) { - defer func() { - if recover() != nil { - r = 0 - err = ErrSyntax - } - }() - - if n := len(s); n < 2 || 3 < n { - return 0, ErrSyntax - } - var buf [3]byte - return getRegionID(buf[:copy(buf[:], s)]) -} - -// IsCountry returns whether this region is a country or autonomous area. This -// includes non-standard definitions from CLDR. -func (r Region) IsCountry() bool { - if r == 0 || r.IsGroup() || r.IsPrivateUse() && r != _XK { - return false - } - return true -} - -// IsGroup returns whether this region defines a collection of regions. This -// includes non-standard definitions from CLDR. -func (r Region) IsGroup() bool { - if r == 0 { - return false - } - return int(regionInclusion[r]) < len(regionContainment) -} - -// Contains returns whether Region c is contained by Region r. It returns true -// if c == r. -func (r Region) Contains(c Region) bool { - if r == c { - return true - } - g := regionInclusion[r] - if g >= nRegionGroups { - return false - } - m := regionContainment[g] - - d := regionInclusion[c] - b := regionInclusionBits[d] - - // A contained country may belong to multiple disjoint groups. Matching any - // of these indicates containment. If the contained region is a group, it - // must strictly be a subset. - if d >= nRegionGroups { - return b&m != 0 - } - return b&^m == 0 -} - -var errNoTLD = errors.New("language: region is not a valid ccTLD") - -// TLD returns the country code top-level domain (ccTLD). UK is returned for GB. -// In all other cases it returns either the region itself or an error. -// -// This method may return an error for a region for which there exists a -// canonical form with a ccTLD. To get that ccTLD canonicalize r first. The -// region will already be canonicalized it was obtained from a Tag that was -// obtained using any of the default methods. -func (r Region) TLD() (Region, error) { - // See http://en.wikipedia.org/wiki/Country_code_top-level_domain for the - // difference between ISO 3166-1 and IANA ccTLD. - if r == _GB { - r = _UK - } - if (r.typ() & ccTLD) == 0 { - return 0, errNoTLD - } - return r, nil -} - -// Canonicalize returns the region or a possible replacement if the region is -// deprecated. It will not return a replacement for deprecated regions that -// are split into multiple regions. -func (r Region) Canonicalize() Region { - if cr := normRegion(r); cr != 0 { - return cr - } - return r -} - -// Variant represents a registered variant of a language as defined by BCP 47. -type Variant struct { - ID uint8 - str string -} - -// ParseVariant parses and returns a Variant. An error is returned if s is not -// a valid variant. -func ParseVariant(s string) (v Variant, err error) { - defer func() { - if recover() != nil { - v = Variant{} - err = ErrSyntax - } - }() - - s = strings.ToLower(s) - if id, ok := variantIndex[s]; ok { - return Variant{id, s}, nil - } - return Variant{}, NewValueError([]byte(s)) -} - -// String returns the string representation of the variant. -func (v Variant) String() string { - return v.str -} diff --git a/vendor/golang.org/x/text/internal/language/lookup.go b/vendor/golang.org/x/text/internal/language/lookup.go deleted file mode 100644 index 231b4fb..0000000 --- a/vendor/golang.org/x/text/internal/language/lookup.go +++ /dev/null @@ -1,412 +0,0 @@ -// Copyright 2013 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 language - -import ( - "bytes" - "fmt" - "sort" - "strconv" - - "golang.org/x/text/internal/tag" -) - -// findIndex tries to find the given tag in idx and returns a standardized error -// if it could not be found. -func findIndex(idx tag.Index, key []byte, form string) (index int, err error) { - if !tag.FixCase(form, key) { - return 0, ErrSyntax - } - i := idx.Index(key) - if i == -1 { - return 0, NewValueError(key) - } - return i, nil -} - -func searchUint(imap []uint16, key uint16) int { - return sort.Search(len(imap), func(i int) bool { - return imap[i] >= key - }) -} - -type Language uint16 - -// getLangID returns the langID of s if s is a canonical subtag -// or langUnknown if s is not a canonical subtag. -func getLangID(s []byte) (Language, error) { - if len(s) == 2 { - return getLangISO2(s) - } - return getLangISO3(s) -} - -// TODO language normalization as well as the AliasMaps could be moved to the -// higher level package, but it is a bit tricky to separate the generation. - -func (id Language) Canonicalize() (Language, AliasType) { - return normLang(id) -} - -// normLang returns the mapped langID of id according to mapping m. -func normLang(id Language) (Language, AliasType) { - k := sort.Search(len(AliasMap), func(i int) bool { - return AliasMap[i].From >= uint16(id) - }) - if k < len(AliasMap) && AliasMap[k].From == uint16(id) { - return Language(AliasMap[k].To), AliasTypes[k] - } - return id, AliasTypeUnknown -} - -// getLangISO2 returns the langID for the given 2-letter ISO language code -// or unknownLang if this does not exist. -func getLangISO2(s []byte) (Language, error) { - if !tag.FixCase("zz", s) { - return 0, ErrSyntax - } - if i := lang.Index(s); i != -1 && lang.Elem(i)[3] != 0 { - return Language(i), nil - } - return 0, NewValueError(s) -} - -const base = 'z' - 'a' + 1 - -func strToInt(s []byte) uint { - v := uint(0) - for i := 0; i < len(s); i++ { - v *= base - v += uint(s[i] - 'a') - } - return v -} - -// converts the given integer to the original ASCII string passed to strToInt. -// len(s) must match the number of characters obtained. -func intToStr(v uint, s []byte) { - for i := len(s) - 1; i >= 0; i-- { - s[i] = byte(v%base) + 'a' - v /= base - } -} - -// getLangISO3 returns the langID for the given 3-letter ISO language code -// or unknownLang if this does not exist. -func getLangISO3(s []byte) (Language, error) { - if tag.FixCase("und", s) { - // first try to match canonical 3-letter entries - for i := lang.Index(s[:2]); i != -1; i = lang.Next(s[:2], i) { - if e := lang.Elem(i); e[3] == 0 && e[2] == s[2] { - // We treat "und" as special and always translate it to "unspecified". - // Note that ZZ and Zzzz are private use and are not treated as - // unspecified by default. - id := Language(i) - if id == nonCanonicalUnd { - return 0, nil - } - return id, nil - } - } - if i := altLangISO3.Index(s); i != -1 { - return Language(altLangIndex[altLangISO3.Elem(i)[3]]), nil - } - n := strToInt(s) - if langNoIndex[n/8]&(1<<(n%8)) != 0 { - return Language(n) + langNoIndexOffset, nil - } - // Check for non-canonical uses of ISO3. - for i := lang.Index(s[:1]); i != -1; i = lang.Next(s[:1], i) { - if e := lang.Elem(i); e[2] == s[1] && e[3] == s[2] { - return Language(i), nil - } - } - return 0, NewValueError(s) - } - return 0, ErrSyntax -} - -// StringToBuf writes the string to b and returns the number of bytes -// written. cap(b) must be >= 3. -func (id Language) StringToBuf(b []byte) int { - if id >= langNoIndexOffset { - intToStr(uint(id)-langNoIndexOffset, b[:3]) - return 3 - } else if id == 0 { - return copy(b, "und") - } - l := lang[id<<2:] - if l[3] == 0 { - return copy(b, l[:3]) - } - return copy(b, l[:2]) -} - -// String returns the BCP 47 representation of the langID. -// Use b as variable name, instead of id, to ensure the variable -// used is consistent with that of Base in which this type is embedded. -func (b Language) String() string { - if b == 0 { - return "und" - } else if b >= langNoIndexOffset { - b -= langNoIndexOffset - buf := [3]byte{} - intToStr(uint(b), buf[:]) - return string(buf[:]) - } - l := lang.Elem(int(b)) - if l[3] == 0 { - return l[:3] - } - return l[:2] -} - -// ISO3 returns the ISO 639-3 language code. -func (b Language) ISO3() string { - if b == 0 || b >= langNoIndexOffset { - return b.String() - } - l := lang.Elem(int(b)) - if l[3] == 0 { - return l[:3] - } else if l[2] == 0 { - return altLangISO3.Elem(int(l[3]))[:3] - } - // This allocation will only happen for 3-letter ISO codes - // that are non-canonical BCP 47 language identifiers. - return l[0:1] + l[2:4] -} - -// IsPrivateUse reports whether this language code is reserved for private use. -func (b Language) IsPrivateUse() bool { - return langPrivateStart <= b && b <= langPrivateEnd -} - -// SuppressScript returns the script marked as SuppressScript in the IANA -// language tag repository, or 0 if there is no such script. -func (b Language) SuppressScript() Script { - if b < langNoIndexOffset { - return Script(suppressScript[b]) - } - return 0 -} - -type Region uint16 - -// getRegionID returns the region id for s if s is a valid 2-letter region code -// or unknownRegion. -func getRegionID(s []byte) (Region, error) { - if len(s) == 3 { - if isAlpha(s[0]) { - return getRegionISO3(s) - } - if i, err := strconv.ParseUint(string(s), 10, 10); err == nil { - return getRegionM49(int(i)) - } - } - return getRegionISO2(s) -} - -// getRegionISO2 returns the regionID for the given 2-letter ISO country code -// or unknownRegion if this does not exist. -func getRegionISO2(s []byte) (Region, error) { - i, err := findIndex(regionISO, s, "ZZ") - if err != nil { - return 0, err - } - return Region(i) + isoRegionOffset, nil -} - -// getRegionISO3 returns the regionID for the given 3-letter ISO country code -// or unknownRegion if this does not exist. -func getRegionISO3(s []byte) (Region, error) { - if tag.FixCase("ZZZ", s) { - for i := regionISO.Index(s[:1]); i != -1; i = regionISO.Next(s[:1], i) { - if e := regionISO.Elem(i); e[2] == s[1] && e[3] == s[2] { - return Region(i) + isoRegionOffset, nil - } - } - for i := 0; i < len(altRegionISO3); i += 3 { - if tag.Compare(altRegionISO3[i:i+3], s) == 0 { - return Region(altRegionIDs[i/3]), nil - } - } - return 0, NewValueError(s) - } - return 0, ErrSyntax -} - -func getRegionM49(n int) (Region, error) { - if 0 < n && n <= 999 { - const ( - searchBits = 7 - regionBits = 9 - regionMask = 1<> searchBits - buf := fromM49[m49Index[idx]:m49Index[idx+1]] - val := uint16(n) << regionBits // we rely on bits shifting out - i := sort.Search(len(buf), func(i int) bool { - return buf[i] >= val - }) - if r := fromM49[int(m49Index[idx])+i]; r&^regionMask == val { - return Region(r & regionMask), nil - } - } - var e ValueError - fmt.Fprint(bytes.NewBuffer([]byte(e.v[:])), n) - return 0, e -} - -// normRegion returns a region if r is deprecated or 0 otherwise. -// TODO: consider supporting BYS (-> BLR), CSK (-> 200 or CZ), PHI (-> PHL) and AFI (-> DJ). -// TODO: consider mapping split up regions to new most populous one (like CLDR). -func normRegion(r Region) Region { - m := regionOldMap - k := sort.Search(len(m), func(i int) bool { - return m[i].From >= uint16(r) - }) - if k < len(m) && m[k].From == uint16(r) { - return Region(m[k].To) - } - return 0 -} - -const ( - iso3166UserAssigned = 1 << iota - ccTLD - bcp47Region -) - -func (r Region) typ() byte { - return regionTypes[r] -} - -// String returns the BCP 47 representation for the region. -// It returns "ZZ" for an unspecified region. -func (r Region) String() string { - if r < isoRegionOffset { - if r == 0 { - return "ZZ" - } - return fmt.Sprintf("%03d", r.M49()) - } - r -= isoRegionOffset - return regionISO.Elem(int(r))[:2] -} - -// ISO3 returns the 3-letter ISO code of r. -// Note that not all regions have a 3-letter ISO code. -// In such cases this method returns "ZZZ". -func (r Region) ISO3() string { - if r < isoRegionOffset { - return "ZZZ" - } - r -= isoRegionOffset - reg := regionISO.Elem(int(r)) - switch reg[2] { - case 0: - return altRegionISO3[reg[3]:][:3] - case ' ': - return "ZZZ" - } - return reg[0:1] + reg[2:4] -} - -// M49 returns the UN M.49 encoding of r, or 0 if this encoding -// is not defined for r. -func (r Region) M49() int { - return int(m49[r]) -} - -// IsPrivateUse reports whether r has the ISO 3166 User-assigned status. This -// may include private-use tags that are assigned by CLDR and used in this -// implementation. So IsPrivateUse and IsCountry can be simultaneously true. -func (r Region) IsPrivateUse() bool { - return r.typ()&iso3166UserAssigned != 0 -} - -type Script uint16 - -// getScriptID returns the script id for string s. It assumes that s -// is of the format [A-Z][a-z]{3}. -func getScriptID(idx tag.Index, s []byte) (Script, error) { - i, err := findIndex(idx, s, "Zzzz") - return Script(i), err -} - -// String returns the script code in title case. -// It returns "Zzzz" for an unspecified script. -func (s Script) String() string { - if s == 0 { - return "Zzzz" - } - return script.Elem(int(s)) -} - -// IsPrivateUse reports whether this script code is reserved for private use. -func (s Script) IsPrivateUse() bool { - return _Qaaa <= s && s <= _Qabx -} - -const ( - maxAltTaglen = len("en-US-POSIX") - maxLen = maxAltTaglen -) - -var ( - // grandfatheredMap holds a mapping from legacy and grandfathered tags to - // their base language or index to more elaborate tag. - grandfatheredMap = map[[maxLen]byte]int16{ - [maxLen]byte{'a', 'r', 't', '-', 'l', 'o', 'j', 'b', 'a', 'n'}: _jbo, // art-lojban - [maxLen]byte{'i', '-', 'a', 'm', 'i'}: _ami, // i-ami - [maxLen]byte{'i', '-', 'b', 'n', 'n'}: _bnn, // i-bnn - [maxLen]byte{'i', '-', 'h', 'a', 'k'}: _hak, // i-hak - [maxLen]byte{'i', '-', 'k', 'l', 'i', 'n', 'g', 'o', 'n'}: _tlh, // i-klingon - [maxLen]byte{'i', '-', 'l', 'u', 'x'}: _lb, // i-lux - [maxLen]byte{'i', '-', 'n', 'a', 'v', 'a', 'j', 'o'}: _nv, // i-navajo - [maxLen]byte{'i', '-', 'p', 'w', 'n'}: _pwn, // i-pwn - [maxLen]byte{'i', '-', 't', 'a', 'o'}: _tao, // i-tao - [maxLen]byte{'i', '-', 't', 'a', 'y'}: _tay, // i-tay - [maxLen]byte{'i', '-', 't', 's', 'u'}: _tsu, // i-tsu - [maxLen]byte{'n', 'o', '-', 'b', 'o', 'k'}: _nb, // no-bok - [maxLen]byte{'n', 'o', '-', 'n', 'y', 'n'}: _nn, // no-nyn - [maxLen]byte{'s', 'g', 'n', '-', 'b', 'e', '-', 'f', 'r'}: _sfb, // sgn-BE-FR - [maxLen]byte{'s', 'g', 'n', '-', 'b', 'e', '-', 'n', 'l'}: _vgt, // sgn-BE-NL - [maxLen]byte{'s', 'g', 'n', '-', 'c', 'h', '-', 'd', 'e'}: _sgg, // sgn-CH-DE - [maxLen]byte{'z', 'h', '-', 'g', 'u', 'o', 'y', 'u'}: _cmn, // zh-guoyu - [maxLen]byte{'z', 'h', '-', 'h', 'a', 'k', 'k', 'a'}: _hak, // zh-hakka - [maxLen]byte{'z', 'h', '-', 'm', 'i', 'n', '-', 'n', 'a', 'n'}: _nan, // zh-min-nan - [maxLen]byte{'z', 'h', '-', 'x', 'i', 'a', 'n', 'g'}: _hsn, // zh-xiang - - // Grandfathered tags with no modern replacement will be converted as - // follows: - [maxLen]byte{'c', 'e', 'l', '-', 'g', 'a', 'u', 'l', 'i', 's', 'h'}: -1, // cel-gaulish - [maxLen]byte{'e', 'n', '-', 'g', 'b', '-', 'o', 'e', 'd'}: -2, // en-GB-oed - [maxLen]byte{'i', '-', 'd', 'e', 'f', 'a', 'u', 'l', 't'}: -3, // i-default - [maxLen]byte{'i', '-', 'e', 'n', 'o', 'c', 'h', 'i', 'a', 'n'}: -4, // i-enochian - [maxLen]byte{'i', '-', 'm', 'i', 'n', 'g', 'o'}: -5, // i-mingo - [maxLen]byte{'z', 'h', '-', 'm', 'i', 'n'}: -6, // zh-min - - // CLDR-specific tag. - [maxLen]byte{'r', 'o', 'o', 't'}: 0, // root - [maxLen]byte{'e', 'n', '-', 'u', 's', '-', 'p', 'o', 's', 'i', 'x'}: -7, // en_US_POSIX" - } - - altTagIndex = [...]uint8{0, 17, 31, 45, 61, 74, 86, 102} - - altTags = "xtg-x-cel-gaulishen-GB-oxendicten-x-i-defaultund-x-i-enochiansee-x-i-mingonan-x-zh-minen-US-u-va-posix" -) - -func grandfathered(s [maxAltTaglen]byte) (t Tag, ok bool) { - if v, ok := grandfatheredMap[s]; ok { - if v < 0 { - return Make(altTags[altTagIndex[-v-1]:altTagIndex[-v]]), true - } - t.LangID = Language(v) - return t, true - } - return t, false -} diff --git a/vendor/golang.org/x/text/internal/language/match.go b/vendor/golang.org/x/text/internal/language/match.go deleted file mode 100644 index 75a2dbc..0000000 --- a/vendor/golang.org/x/text/internal/language/match.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2013 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 language - -import "errors" - -type scriptRegionFlags uint8 - -const ( - isList = 1 << iota - scriptInFrom - regionInFrom -) - -func (t *Tag) setUndefinedLang(id Language) { - if t.LangID == 0 { - t.LangID = id - } -} - -func (t *Tag) setUndefinedScript(id Script) { - if t.ScriptID == 0 { - t.ScriptID = id - } -} - -func (t *Tag) setUndefinedRegion(id Region) { - if t.RegionID == 0 || t.RegionID.Contains(id) { - t.RegionID = id - } -} - -// ErrMissingLikelyTagsData indicates no information was available -// to compute likely values of missing tags. -var ErrMissingLikelyTagsData = errors.New("missing likely tags data") - -// addLikelySubtags sets subtags to their most likely value, given the locale. -// In most cases this means setting fields for unknown values, but in some -// cases it may alter a value. It returns an ErrMissingLikelyTagsData error -// if the given locale cannot be expanded. -func (t Tag) addLikelySubtags() (Tag, error) { - id, err := addTags(t) - if err != nil { - return t, err - } else if id.equalTags(t) { - return t, nil - } - id.RemakeString() - return id, nil -} - -// specializeRegion attempts to specialize a group region. -func specializeRegion(t *Tag) bool { - if i := regionInclusion[t.RegionID]; i < nRegionGroups { - x := likelyRegionGroup[i] - if Language(x.lang) == t.LangID && Script(x.script) == t.ScriptID { - t.RegionID = Region(x.region) - } - return true - } - return false -} - -// Maximize returns a new tag with missing tags filled in. -func (t Tag) Maximize() (Tag, error) { - return addTags(t) -} - -func addTags(t Tag) (Tag, error) { - // We leave private use identifiers alone. - if t.IsPrivateUse() { - return t, nil - } - if t.ScriptID != 0 && t.RegionID != 0 { - if t.LangID != 0 { - // already fully specified - specializeRegion(&t) - return t, nil - } - // Search matches for und-script-region. Note that for these cases - // region will never be a group so there is no need to check for this. - list := likelyRegion[t.RegionID : t.RegionID+1] - if x := list[0]; x.flags&isList != 0 { - list = likelyRegionList[x.lang : x.lang+uint16(x.script)] - } - for _, x := range list { - // Deviating from the spec. See match_test.go for details. - if Script(x.script) == t.ScriptID { - t.setUndefinedLang(Language(x.lang)) - return t, nil - } - } - } - if t.LangID != 0 { - // Search matches for lang-script and lang-region, where lang != und. - if t.LangID < langNoIndexOffset { - x := likelyLang[t.LangID] - if x.flags&isList != 0 { - list := likelyLangList[x.region : x.region+uint16(x.script)] - if t.ScriptID != 0 { - for _, x := range list { - if Script(x.script) == t.ScriptID && x.flags&scriptInFrom != 0 { - t.setUndefinedRegion(Region(x.region)) - return t, nil - } - } - } else if t.RegionID != 0 { - count := 0 - goodScript := true - tt := t - for _, x := range list { - // We visit all entries for which the script was not - // defined, including the ones where the region was not - // defined. This allows for proper disambiguation within - // regions. - if x.flags&scriptInFrom == 0 && t.RegionID.Contains(Region(x.region)) { - tt.RegionID = Region(x.region) - tt.setUndefinedScript(Script(x.script)) - goodScript = goodScript && tt.ScriptID == Script(x.script) - count++ - } - } - if count == 1 { - return tt, nil - } - // Even if we fail to find a unique Region, we might have - // an unambiguous script. - if goodScript { - t.ScriptID = tt.ScriptID - } - } - } - } - } else { - // Search matches for und-script. - if t.ScriptID != 0 { - x := likelyScript[t.ScriptID] - if x.region != 0 { - t.setUndefinedRegion(Region(x.region)) - t.setUndefinedLang(Language(x.lang)) - return t, nil - } - } - // Search matches for und-region. If und-script-region exists, it would - // have been found earlier. - if t.RegionID != 0 { - if i := regionInclusion[t.RegionID]; i < nRegionGroups { - x := likelyRegionGroup[i] - if x.region != 0 { - t.setUndefinedLang(Language(x.lang)) - t.setUndefinedScript(Script(x.script)) - t.RegionID = Region(x.region) - } - } else { - x := likelyRegion[t.RegionID] - if x.flags&isList != 0 { - x = likelyRegionList[x.lang] - } - if x.script != 0 && x.flags != scriptInFrom { - t.setUndefinedLang(Language(x.lang)) - t.setUndefinedScript(Script(x.script)) - return t, nil - } - } - } - } - - // Search matches for lang. - if t.LangID < langNoIndexOffset { - x := likelyLang[t.LangID] - if x.flags&isList != 0 { - x = likelyLangList[x.region] - } - if x.region != 0 { - t.setUndefinedScript(Script(x.script)) - t.setUndefinedRegion(Region(x.region)) - } - specializeRegion(&t) - if t.LangID == 0 { - t.LangID = _en // default language - } - return t, nil - } - return t, ErrMissingLikelyTagsData -} - -func (t *Tag) setTagsFrom(id Tag) { - t.LangID = id.LangID - t.ScriptID = id.ScriptID - t.RegionID = id.RegionID -} - -// minimize removes the region or script subtags from t such that -// t.addLikelySubtags() == t.minimize().addLikelySubtags(). -func (t Tag) minimize() (Tag, error) { - t, err := minimizeTags(t) - if err != nil { - return t, err - } - t.RemakeString() - return t, nil -} - -// minimizeTags mimics the behavior of the ICU 51 C implementation. -func minimizeTags(t Tag) (Tag, error) { - if t.equalTags(Und) { - return t, nil - } - max, err := addTags(t) - if err != nil { - return t, err - } - for _, id := range [...]Tag{ - {LangID: t.LangID}, - {LangID: t.LangID, RegionID: t.RegionID}, - {LangID: t.LangID, ScriptID: t.ScriptID}, - } { - if x, err := addTags(id); err == nil && max.equalTags(x) { - t.setTagsFrom(id) - break - } - } - return t, nil -} diff --git a/vendor/golang.org/x/text/internal/language/parse.go b/vendor/golang.org/x/text/internal/language/parse.go deleted file mode 100644 index aad1e0a..0000000 --- a/vendor/golang.org/x/text/internal/language/parse.go +++ /dev/null @@ -1,608 +0,0 @@ -// Copyright 2013 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 language - -import ( - "bytes" - "errors" - "fmt" - "sort" - - "golang.org/x/text/internal/tag" -) - -// isAlpha returns true if the byte is not a digit. -// b must be an ASCII letter or digit. -func isAlpha(b byte) bool { - return b > '9' -} - -// isAlphaNum returns true if the string contains only ASCII letters or digits. -func isAlphaNum(s []byte) bool { - for _, c := range s { - if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9') { - return false - } - } - return true -} - -// ErrSyntax is returned by any of the parsing functions when the -// input is not well-formed, according to BCP 47. -// TODO: return the position at which the syntax error occurred? -var ErrSyntax = errors.New("language: tag is not well-formed") - -// ErrDuplicateKey is returned when a tag contains the same key twice with -// different values in the -u section. -var ErrDuplicateKey = errors.New("language: different values for same key in -u extension") - -// ValueError is returned by any of the parsing functions when the -// input is well-formed but the respective subtag is not recognized -// as a valid value. -type ValueError struct { - v [8]byte -} - -// NewValueError creates a new ValueError. -func NewValueError(tag []byte) ValueError { - var e ValueError - copy(e.v[:], tag) - return e -} - -func (e ValueError) tag() []byte { - n := bytes.IndexByte(e.v[:], 0) - if n == -1 { - n = 8 - } - return e.v[:n] -} - -// Error implements the error interface. -func (e ValueError) Error() string { - return fmt.Sprintf("language: subtag %q is well-formed but unknown", e.tag()) -} - -// Subtag returns the subtag for which the error occurred. -func (e ValueError) Subtag() string { - return string(e.tag()) -} - -// scanner is used to scan BCP 47 tokens, which are separated by _ or -. -type scanner struct { - b []byte - bytes [max99thPercentileSize]byte - token []byte - start int // start position of the current token - end int // end position of the current token - next int // next point for scan - err error - done bool -} - -func makeScannerString(s string) scanner { - scan := scanner{} - if len(s) <= len(scan.bytes) { - scan.b = scan.bytes[:copy(scan.bytes[:], s)] - } else { - scan.b = []byte(s) - } - scan.init() - return scan -} - -// makeScanner returns a scanner using b as the input buffer. -// b is not copied and may be modified by the scanner routines. -func makeScanner(b []byte) scanner { - scan := scanner{b: b} - scan.init() - return scan -} - -func (s *scanner) init() { - for i, c := range s.b { - if c == '_' { - s.b[i] = '-' - } - } - s.scan() -} - -// restToLower converts the string between start and end to lower case. -func (s *scanner) toLower(start, end int) { - for i := start; i < end; i++ { - c := s.b[i] - if 'A' <= c && c <= 'Z' { - s.b[i] += 'a' - 'A' - } - } -} - -func (s *scanner) setError(e error) { - if s.err == nil || (e == ErrSyntax && s.err != ErrSyntax) { - s.err = e - } -} - -// resizeRange shrinks or grows the array at position oldStart such that -// a new string of size newSize can fit between oldStart and oldEnd. -// Sets the scan point to after the resized range. -func (s *scanner) resizeRange(oldStart, oldEnd, newSize int) { - s.start = oldStart - if end := oldStart + newSize; end != oldEnd { - diff := end - oldEnd - var b []byte - if n := len(s.b) + diff; n > cap(s.b) { - b = make([]byte, n) - copy(b, s.b[:oldStart]) - } else { - b = s.b[:n] - } - copy(b[end:], s.b[oldEnd:]) - s.b = b - s.next = end + (s.next - s.end) - s.end = end - } -} - -// replace replaces the current token with repl. -func (s *scanner) replace(repl string) { - s.resizeRange(s.start, s.end, len(repl)) - copy(s.b[s.start:], repl) -} - -// gobble removes the current token from the input. -// Caller must call scan after calling gobble. -func (s *scanner) gobble(e error) { - s.setError(e) - if s.start == 0 { - s.b = s.b[:+copy(s.b, s.b[s.next:])] - s.end = 0 - } else { - s.b = s.b[:s.start-1+copy(s.b[s.start-1:], s.b[s.end:])] - s.end = s.start - 1 - } - s.next = s.start -} - -// deleteRange removes the given range from s.b before the current token. -func (s *scanner) deleteRange(start, end int) { - s.b = s.b[:start+copy(s.b[start:], s.b[end:])] - diff := end - start - s.next -= diff - s.start -= diff - s.end -= diff -} - -// scan parses the next token of a BCP 47 string. Tokens that are larger -// than 8 characters or include non-alphanumeric characters result in an error -// and are gobbled and removed from the output. -// It returns the end position of the last token consumed. -func (s *scanner) scan() (end int) { - end = s.end - s.token = nil - for s.start = s.next; s.next < len(s.b); { - i := bytes.IndexByte(s.b[s.next:], '-') - if i == -1 { - s.end = len(s.b) - s.next = len(s.b) - i = s.end - s.start - } else { - s.end = s.next + i - s.next = s.end + 1 - } - token := s.b[s.start:s.end] - if i < 1 || i > 8 || !isAlphaNum(token) { - s.gobble(ErrSyntax) - continue - } - s.token = token - return end - } - if n := len(s.b); n > 0 && s.b[n-1] == '-' { - s.setError(ErrSyntax) - s.b = s.b[:len(s.b)-1] - } - s.done = true - return end -} - -// acceptMinSize parses multiple tokens of the given size or greater. -// It returns the end position of the last token consumed. -func (s *scanner) acceptMinSize(min int) (end int) { - end = s.end - s.scan() - for ; len(s.token) >= min; s.scan() { - end = s.end - } - return end -} - -// Parse parses the given BCP 47 string and returns a valid Tag. If parsing -// failed it returns an error and any part of the tag that could be parsed. -// If parsing succeeded but an unknown value was found, it returns -// ValueError. The Tag returned in this case is just stripped of the unknown -// value. All other values are preserved. It accepts tags in the BCP 47 format -// and extensions to this standard defined in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -func Parse(s string) (t Tag, err error) { - // TODO: consider supporting old-style locale key-value pairs. - if s == "" { - return Und, ErrSyntax - } - defer func() { - if recover() != nil { - t = Und - err = ErrSyntax - return - } - }() - if len(s) <= maxAltTaglen { - b := [maxAltTaglen]byte{} - for i, c := range s { - // Generating invalid UTF-8 is okay as it won't match. - if 'A' <= c && c <= 'Z' { - c += 'a' - 'A' - } else if c == '_' { - c = '-' - } - b[i] = byte(c) - } - if t, ok := grandfathered(b); ok { - return t, nil - } - } - scan := makeScannerString(s) - return parse(&scan, s) -} - -func parse(scan *scanner, s string) (t Tag, err error) { - t = Und - var end int - if n := len(scan.token); n <= 1 { - scan.toLower(0, len(scan.b)) - if n == 0 || scan.token[0] != 'x' { - return t, ErrSyntax - } - end = parseExtensions(scan) - } else if n >= 4 { - return Und, ErrSyntax - } else { // the usual case - t, end = parseTag(scan, true) - if n := len(scan.token); n == 1 { - t.pExt = uint16(end) - end = parseExtensions(scan) - } else if end < len(scan.b) { - scan.setError(ErrSyntax) - scan.b = scan.b[:end] - } - } - if int(t.pVariant) < len(scan.b) { - if end < len(s) { - s = s[:end] - } - if len(s) > 0 && tag.Compare(s, scan.b) == 0 { - t.str = s - } else { - t.str = string(scan.b) - } - } else { - t.pVariant, t.pExt = 0, 0 - } - return t, scan.err -} - -// parseTag parses language, script, region and variants. -// It returns a Tag and the end position in the input that was parsed. -// If doNorm is true, then - will be normalized to . -func parseTag(scan *scanner, doNorm bool) (t Tag, end int) { - var e error - // TODO: set an error if an unknown lang, script or region is encountered. - t.LangID, e = getLangID(scan.token) - scan.setError(e) - scan.replace(t.LangID.String()) - langStart := scan.start - end = scan.scan() - for len(scan.token) == 3 && isAlpha(scan.token[0]) { - // From http://tools.ietf.org/html/bcp47, - tags are equivalent - // to a tag of the form . - if doNorm { - lang, e := getLangID(scan.token) - if lang != 0 { - t.LangID = lang - langStr := lang.String() - copy(scan.b[langStart:], langStr) - scan.b[langStart+len(langStr)] = '-' - scan.start = langStart + len(langStr) + 1 - } - scan.gobble(e) - } - end = scan.scan() - } - if len(scan.token) == 4 && isAlpha(scan.token[0]) { - t.ScriptID, e = getScriptID(script, scan.token) - if t.ScriptID == 0 { - scan.gobble(e) - } - end = scan.scan() - } - if n := len(scan.token); n >= 2 && n <= 3 { - t.RegionID, e = getRegionID(scan.token) - if t.RegionID == 0 { - scan.gobble(e) - } else { - scan.replace(t.RegionID.String()) - } - end = scan.scan() - } - scan.toLower(scan.start, len(scan.b)) - t.pVariant = byte(end) - end = parseVariants(scan, end, t) - t.pExt = uint16(end) - return t, end -} - -var separator = []byte{'-'} - -// parseVariants scans tokens as long as each token is a valid variant string. -// Duplicate variants are removed. -func parseVariants(scan *scanner, end int, t Tag) int { - start := scan.start - varIDBuf := [4]uint8{} - variantBuf := [4][]byte{} - varID := varIDBuf[:0] - variant := variantBuf[:0] - last := -1 - needSort := false - for ; len(scan.token) >= 4; scan.scan() { - // TODO: measure the impact of needing this conversion and redesign - // the data structure if there is an issue. - v, ok := variantIndex[string(scan.token)] - if !ok { - // unknown variant - // TODO: allow user-defined variants? - scan.gobble(NewValueError(scan.token)) - continue - } - varID = append(varID, v) - variant = append(variant, scan.token) - if !needSort { - if last < int(v) { - last = int(v) - } else { - needSort = true - // There is no legal combinations of more than 7 variants - // (and this is by no means a useful sequence). - const maxVariants = 8 - if len(varID) > maxVariants { - break - } - } - } - end = scan.end - } - if needSort { - sort.Sort(variantsSort{varID, variant}) - k, l := 0, -1 - for i, v := range varID { - w := int(v) - if l == w { - // Remove duplicates. - continue - } - varID[k] = varID[i] - variant[k] = variant[i] - k++ - l = w - } - if str := bytes.Join(variant[:k], separator); len(str) == 0 { - end = start - 1 - } else { - scan.resizeRange(start, end, len(str)) - copy(scan.b[scan.start:], str) - end = scan.end - } - } - return end -} - -type variantsSort struct { - i []uint8 - v [][]byte -} - -func (s variantsSort) Len() int { - return len(s.i) -} - -func (s variantsSort) Swap(i, j int) { - s.i[i], s.i[j] = s.i[j], s.i[i] - s.v[i], s.v[j] = s.v[j], s.v[i] -} - -func (s variantsSort) Less(i, j int) bool { - return s.i[i] < s.i[j] -} - -type bytesSort struct { - b [][]byte - n int // first n bytes to compare -} - -func (b bytesSort) Len() int { - return len(b.b) -} - -func (b bytesSort) Swap(i, j int) { - b.b[i], b.b[j] = b.b[j], b.b[i] -} - -func (b bytesSort) Less(i, j int) bool { - for k := 0; k < b.n; k++ { - if b.b[i][k] == b.b[j][k] { - continue - } - return b.b[i][k] < b.b[j][k] - } - return false -} - -// parseExtensions parses and normalizes the extensions in the buffer. -// It returns the last position of scan.b that is part of any extension. -// It also trims scan.b to remove excess parts accordingly. -func parseExtensions(scan *scanner) int { - start := scan.start - exts := [][]byte{} - private := []byte{} - end := scan.end - for len(scan.token) == 1 { - extStart := scan.start - ext := scan.token[0] - end = parseExtension(scan) - extension := scan.b[extStart:end] - if len(extension) < 3 || (ext != 'x' && len(extension) < 4) { - scan.setError(ErrSyntax) - end = extStart - continue - } else if start == extStart && (ext == 'x' || scan.start == len(scan.b)) { - scan.b = scan.b[:end] - return end - } else if ext == 'x' { - private = extension - break - } - exts = append(exts, extension) - } - sort.Sort(bytesSort{exts, 1}) - if len(private) > 0 { - exts = append(exts, private) - } - scan.b = scan.b[:start] - if len(exts) > 0 { - scan.b = append(scan.b, bytes.Join(exts, separator)...) - } else if start > 0 { - // Strip trailing '-'. - scan.b = scan.b[:start-1] - } - return end -} - -// parseExtension parses a single extension and returns the position of -// the extension end. -func parseExtension(scan *scanner) int { - start, end := scan.start, scan.end - switch scan.token[0] { - case 'u': // https://www.ietf.org/rfc/rfc6067.txt - attrStart := end - scan.scan() - for last := []byte{}; len(scan.token) > 2; scan.scan() { - if bytes.Compare(scan.token, last) != -1 { - // Attributes are unsorted. Start over from scratch. - p := attrStart + 1 - scan.next = p - attrs := [][]byte{} - for scan.scan(); len(scan.token) > 2; scan.scan() { - attrs = append(attrs, scan.token) - end = scan.end - } - sort.Sort(bytesSort{attrs, 3}) - copy(scan.b[p:], bytes.Join(attrs, separator)) - break - } - last = scan.token - end = scan.end - } - // Scan key-type sequences. A key is of length 2 and may be followed - // by 0 or more "type" subtags from 3 to the maximum of 8 letters. - var last, key []byte - for attrEnd := end; len(scan.token) == 2; last = key { - key = scan.token - end = scan.end - for scan.scan(); end < scan.end && len(scan.token) > 2; scan.scan() { - end = scan.end - } - // TODO: check key value validity - if bytes.Compare(key, last) != 1 || scan.err != nil { - // We have an invalid key or the keys are not sorted. - // Start scanning keys from scratch and reorder. - p := attrEnd + 1 - scan.next = p - keys := [][]byte{} - for scan.scan(); len(scan.token) == 2; { - keyStart := scan.start - end = scan.end - for scan.scan(); end < scan.end && len(scan.token) > 2; scan.scan() { - end = scan.end - } - keys = append(keys, scan.b[keyStart:end]) - } - sort.Stable(bytesSort{keys, 2}) - if n := len(keys); n > 0 { - k := 0 - for i := 1; i < n; i++ { - if !bytes.Equal(keys[k][:2], keys[i][:2]) { - k++ - keys[k] = keys[i] - } else if !bytes.Equal(keys[k], keys[i]) { - scan.setError(ErrDuplicateKey) - } - } - keys = keys[:k+1] - } - reordered := bytes.Join(keys, separator) - if e := p + len(reordered); e < end { - scan.deleteRange(e, end) - end = e - } - copy(scan.b[p:], reordered) - break - } - } - case 't': // https://www.ietf.org/rfc/rfc6497.txt - scan.scan() - if n := len(scan.token); n >= 2 && n <= 3 && isAlpha(scan.token[1]) { - _, end = parseTag(scan, false) - scan.toLower(start, end) - } - for len(scan.token) == 2 && !isAlpha(scan.token[1]) { - end = scan.acceptMinSize(3) - } - case 'x': - end = scan.acceptMinSize(1) - default: - end = scan.acceptMinSize(2) - } - return end -} - -// getExtension returns the name, body and end position of the extension. -func getExtension(s string, p int) (end int, ext string) { - if s[p] == '-' { - p++ - } - if s[p] == 'x' { - return len(s), s[p:] - } - end = nextExtension(s, p) - return end, s[p:end] -} - -// nextExtension finds the next extension within the string, searching -// for the -- pattern from position p. -// In the fast majority of cases, language tags will have at most -// one extension and extensions tend to be small. -func nextExtension(s string, p int) int { - for n := len(s) - 3; p < n; { - if s[p] == '-' { - if s[p+2] == '-' { - return p - } - p += 3 - } else { - p++ - } - } - return len(s) -} diff --git a/vendor/golang.org/x/text/internal/language/tables.go b/vendor/golang.org/x/text/internal/language/tables.go deleted file mode 100644 index fb6b583..0000000 --- a/vendor/golang.org/x/text/internal/language/tables.go +++ /dev/null @@ -1,3472 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -package language - -import "golang.org/x/text/internal/tag" - -// CLDRVersion is the CLDR version from which the tables in this package are derived. -const CLDRVersion = "32" - -const NumLanguages = 8752 - -const NumScripts = 258 - -const NumRegions = 357 - -type FromTo struct { - From uint16 - To uint16 -} - -const nonCanonicalUnd = 1201 -const ( - _af = 22 - _am = 39 - _ar = 58 - _az = 88 - _bg = 126 - _bn = 165 - _ca = 215 - _cs = 250 - _da = 257 - _de = 269 - _el = 310 - _en = 313 - _es = 318 - _et = 320 - _fa = 328 - _fi = 337 - _fil = 339 - _fr = 350 - _gu = 420 - _he = 444 - _hi = 446 - _hr = 465 - _hu = 469 - _hy = 471 - _id = 481 - _is = 504 - _it = 505 - _ja = 512 - _ka = 528 - _kk = 578 - _km = 586 - _kn = 593 - _ko = 596 - _ky = 650 - _lo = 696 - _lt = 704 - _lv = 711 - _mk = 767 - _ml = 772 - _mn = 779 - _mo = 784 - _mr = 795 - _ms = 799 - _mul = 806 - _my = 817 - _nb = 839 - _ne = 849 - _nl = 871 - _no = 879 - _pa = 925 - _pl = 947 - _pt = 960 - _ro = 988 - _ru = 994 - _sh = 1031 - _si = 1036 - _sk = 1042 - _sl = 1046 - _sq = 1073 - _sr = 1074 - _sv = 1092 - _sw = 1093 - _ta = 1104 - _te = 1121 - _th = 1131 - _tl = 1146 - _tn = 1152 - _tr = 1162 - _uk = 1198 - _ur = 1204 - _uz = 1212 - _vi = 1219 - _zh = 1321 - _zu = 1327 - _jbo = 515 - _ami = 1650 - _bnn = 2357 - _hak = 438 - _tlh = 14467 - _lb = 661 - _nv = 899 - _pwn = 12055 - _tao = 14188 - _tay = 14198 - _tsu = 14662 - _nn = 874 - _sfb = 13629 - _vgt = 15701 - _sgg = 13660 - _cmn = 3007 - _nan = 835 - _hsn = 467 -) - -const langPrivateStart = 0x2f72 - -const langPrivateEnd = 0x3179 - -// lang holds an alphabetically sorted list of ISO-639 language identifiers. -// All entries are 4 bytes. The index of the identifier (divided by 4) is the language tag. -// For 2-byte language identifiers, the two successive bytes have the following meaning: -// - if the first letter of the 2- and 3-letter ISO codes are the same: -// the second and third letter of the 3-letter ISO code. -// - otherwise: a 0 and a by 2 bits right-shifted index into altLangISO3. -// -// For 3-byte language identifiers the 4th byte is 0. -const lang tag.Index = "" + // Size: 5324 bytes - "---\x00aaaraai\x00aak\x00aau\x00abbkabi\x00abq\x00abr\x00abt\x00aby\x00a" + - "cd\x00ace\x00ach\x00ada\x00ade\x00adj\x00ady\x00adz\x00aeveaeb\x00aey" + - "\x00affragc\x00agd\x00agg\x00agm\x00ago\x00agq\x00aha\x00ahl\x00aho\x00a" + - "jg\x00akkaakk\x00ala\x00ali\x00aln\x00alt\x00ammhamm\x00amn\x00amo\x00am" + - "p\x00anrganc\x00ank\x00ann\x00any\x00aoj\x00aom\x00aoz\x00apc\x00apd\x00" + - "ape\x00apr\x00aps\x00apz\x00arraarc\x00arh\x00arn\x00aro\x00arq\x00ars" + - "\x00ary\x00arz\x00assmasa\x00ase\x00asg\x00aso\x00ast\x00ata\x00atg\x00a" + - "tj\x00auy\x00avvaavl\x00avn\x00avt\x00avu\x00awa\x00awb\x00awo\x00awx" + - "\x00ayymayb\x00azzebaakbal\x00ban\x00bap\x00bar\x00bas\x00bav\x00bax\x00" + - "bba\x00bbb\x00bbc\x00bbd\x00bbj\x00bbp\x00bbr\x00bcf\x00bch\x00bci\x00bc" + - "m\x00bcn\x00bco\x00bcq\x00bcu\x00bdd\x00beelbef\x00beh\x00bej\x00bem\x00" + - "bet\x00bew\x00bex\x00bez\x00bfd\x00bfq\x00bft\x00bfy\x00bgulbgc\x00bgn" + - "\x00bgx\x00bhihbhb\x00bhg\x00bhi\x00bhk\x00bhl\x00bho\x00bhy\x00biisbib" + - "\x00big\x00bik\x00bim\x00bin\x00bio\x00biq\x00bjh\x00bji\x00bjj\x00bjn" + - "\x00bjo\x00bjr\x00bjt\x00bjz\x00bkc\x00bkm\x00bkq\x00bku\x00bkv\x00blt" + - "\x00bmambmh\x00bmk\x00bmq\x00bmu\x00bnenbng\x00bnm\x00bnp\x00boodboj\x00" + - "bom\x00bon\x00bpy\x00bqc\x00bqi\x00bqp\x00bqv\x00brrebra\x00brh\x00brx" + - "\x00brz\x00bsosbsj\x00bsq\x00bss\x00bst\x00bto\x00btt\x00btv\x00bua\x00b" + - "uc\x00bud\x00bug\x00buk\x00bum\x00buo\x00bus\x00buu\x00bvb\x00bwd\x00bwr" + - "\x00bxh\x00bye\x00byn\x00byr\x00bys\x00byv\x00byx\x00bza\x00bze\x00bzf" + - "\x00bzh\x00bzw\x00caatcan\x00cbj\x00cch\x00ccp\x00ceheceb\x00cfa\x00cgg" + - "\x00chhachk\x00chm\x00cho\x00chp\x00chr\x00cja\x00cjm\x00cjv\x00ckb\x00c" + - "kl\x00cko\x00cky\x00cla\x00cme\x00cmg\x00cooscop\x00cps\x00crrecrh\x00cr" + - "j\x00crk\x00crl\x00crm\x00crs\x00csescsb\x00csw\x00ctd\x00cuhucvhvcyymda" + - "andad\x00daf\x00dag\x00dah\x00dak\x00dar\x00dav\x00dbd\x00dbq\x00dcc\x00" + - "ddn\x00deeuded\x00den\x00dga\x00dgh\x00dgi\x00dgl\x00dgr\x00dgz\x00dia" + - "\x00dje\x00dnj\x00dob\x00doi\x00dop\x00dow\x00dri\x00drs\x00dsb\x00dtm" + - "\x00dtp\x00dts\x00dty\x00dua\x00duc\x00dud\x00dug\x00dvivdva\x00dww\x00d" + - "yo\x00dyu\x00dzzodzg\x00ebu\x00eeweefi\x00egl\x00egy\x00eka\x00eky\x00el" + - "llema\x00emi\x00enngenn\x00enq\x00eopoeri\x00es\x00\x05esu\x00etstetr" + - "\x00ett\x00etu\x00etx\x00euusewo\x00ext\x00faasfaa\x00fab\x00fag\x00fai" + - "\x00fan\x00ffulffi\x00ffm\x00fiinfia\x00fil\x00fit\x00fjijflr\x00fmp\x00" + - "foaofod\x00fon\x00for\x00fpe\x00fqs\x00frrafrc\x00frp\x00frr\x00frs\x00f" + - "ub\x00fud\x00fue\x00fuf\x00fuh\x00fuq\x00fur\x00fuv\x00fuy\x00fvr\x00fyr" + - "ygalegaa\x00gaf\x00gag\x00gah\x00gaj\x00gam\x00gan\x00gaw\x00gay\x00gba" + - "\x00gbf\x00gbm\x00gby\x00gbz\x00gcr\x00gdlagde\x00gdn\x00gdr\x00geb\x00g" + - "ej\x00gel\x00gez\x00gfk\x00ggn\x00ghs\x00gil\x00gim\x00gjk\x00gjn\x00gju" + - "\x00gkn\x00gkp\x00gllgglk\x00gmm\x00gmv\x00gnrngnd\x00gng\x00god\x00gof" + - "\x00goi\x00gom\x00gon\x00gor\x00gos\x00got\x00grb\x00grc\x00grt\x00grw" + - "\x00gsw\x00guujgub\x00guc\x00gud\x00gur\x00guw\x00gux\x00guz\x00gvlvgvf" + - "\x00gvr\x00gvs\x00gwc\x00gwi\x00gwt\x00gyi\x00haauhag\x00hak\x00ham\x00h" + - "aw\x00haz\x00hbb\x00hdy\x00heebhhy\x00hiinhia\x00hif\x00hig\x00hih\x00hi" + - "l\x00hla\x00hlu\x00hmd\x00hmt\x00hnd\x00hne\x00hnj\x00hnn\x00hno\x00homo" + - "hoc\x00hoj\x00hot\x00hrrvhsb\x00hsn\x00htathuunhui\x00hyyehzerianaian" + - "\x00iar\x00iba\x00ibb\x00iby\x00ica\x00ich\x00idndidd\x00idi\x00idu\x00i" + - "eleife\x00igboigb\x00ige\x00iiiiijj\x00ikpkikk\x00ikt\x00ikw\x00ikx\x00i" + - "lo\x00imo\x00inndinh\x00iodoiou\x00iri\x00isslittaiukuiw\x00\x03iwm\x00i" + - "ws\x00izh\x00izi\x00japnjab\x00jam\x00jbo\x00jbu\x00jen\x00jgk\x00jgo" + - "\x00ji\x00\x06jib\x00jmc\x00jml\x00jra\x00jut\x00jvavjwavkaatkaa\x00kab" + - "\x00kac\x00kad\x00kai\x00kaj\x00kam\x00kao\x00kbd\x00kbm\x00kbp\x00kbq" + - "\x00kbx\x00kby\x00kcg\x00kck\x00kcl\x00kct\x00kde\x00kdh\x00kdl\x00kdt" + - "\x00kea\x00ken\x00kez\x00kfo\x00kfr\x00kfy\x00kgonkge\x00kgf\x00kgp\x00k" + - "ha\x00khb\x00khn\x00khq\x00khs\x00kht\x00khw\x00khz\x00kiikkij\x00kiu" + - "\x00kiw\x00kjuakjd\x00kjg\x00kjs\x00kjy\x00kkazkkc\x00kkj\x00klalkln\x00" + - "klq\x00klt\x00klx\x00kmhmkmb\x00kmh\x00kmo\x00kms\x00kmu\x00kmw\x00knank" + - "nf\x00knp\x00koorkoi\x00kok\x00kol\x00kos\x00koz\x00kpe\x00kpf\x00kpo" + - "\x00kpr\x00kpx\x00kqb\x00kqf\x00kqs\x00kqy\x00kraukrc\x00kri\x00krj\x00k" + - "rl\x00krs\x00kru\x00ksasksb\x00ksd\x00ksf\x00ksh\x00ksj\x00ksr\x00ktb" + - "\x00ktm\x00kto\x00kuurkub\x00kud\x00kue\x00kuj\x00kum\x00kun\x00kup\x00k" + - "us\x00kvomkvg\x00kvr\x00kvx\x00kw\x00\x01kwj\x00kwo\x00kxa\x00kxc\x00kxm" + - "\x00kxp\x00kxw\x00kxz\x00kyirkye\x00kyx\x00kzr\x00laatlab\x00lad\x00lag" + - "\x00lah\x00laj\x00las\x00lbtzlbe\x00lbu\x00lbw\x00lcm\x00lcp\x00ldb\x00l" + - "ed\x00lee\x00lem\x00lep\x00leq\x00leu\x00lez\x00lguglgg\x00liimlia\x00li" + - "d\x00lif\x00lig\x00lih\x00lij\x00lis\x00ljp\x00lki\x00lkt\x00lle\x00lln" + - "\x00lmn\x00lmo\x00lmp\x00lninlns\x00lnu\x00loaoloj\x00lok\x00lol\x00lor" + - "\x00los\x00loz\x00lrc\x00ltitltg\x00luublua\x00luo\x00luy\x00luz\x00lvav" + - "lwl\x00lzh\x00lzz\x00mad\x00maf\x00mag\x00mai\x00mak\x00man\x00mas\x00ma" + - "w\x00maz\x00mbh\x00mbo\x00mbq\x00mbu\x00mbw\x00mci\x00mcp\x00mcq\x00mcr" + - "\x00mcu\x00mda\x00mde\x00mdf\x00mdh\x00mdj\x00mdr\x00mdx\x00med\x00mee" + - "\x00mek\x00men\x00mer\x00met\x00meu\x00mfa\x00mfe\x00mfn\x00mfo\x00mfq" + - "\x00mglgmgh\x00mgl\x00mgo\x00mgp\x00mgy\x00mhahmhi\x00mhl\x00mirimif\x00" + - "min\x00mis\x00miw\x00mkkdmki\x00mkl\x00mkp\x00mkw\x00mlalmle\x00mlp\x00m" + - "ls\x00mmo\x00mmu\x00mmx\x00mnonmna\x00mnf\x00mni\x00mnw\x00moolmoa\x00mo" + - "e\x00moh\x00mos\x00mox\x00mpp\x00mps\x00mpt\x00mpx\x00mql\x00mrarmrd\x00" + - "mrj\x00mro\x00mssamtltmtc\x00mtf\x00mti\x00mtr\x00mua\x00mul\x00mur\x00m" + - "us\x00mva\x00mvn\x00mvy\x00mwk\x00mwr\x00mwv\x00mxc\x00mxm\x00myyamyk" + - "\x00mym\x00myv\x00myw\x00myx\x00myz\x00mzk\x00mzm\x00mzn\x00mzp\x00mzw" + - "\x00mzz\x00naaunac\x00naf\x00nah\x00nak\x00nan\x00nap\x00naq\x00nas\x00n" + - "bobnca\x00nce\x00ncf\x00nch\x00nco\x00ncu\x00nddendc\x00nds\x00neepneb" + - "\x00new\x00nex\x00nfr\x00ngdonga\x00ngb\x00ngl\x00nhb\x00nhe\x00nhw\x00n" + - "if\x00nii\x00nij\x00nin\x00niu\x00niy\x00niz\x00njo\x00nkg\x00nko\x00nll" + - "dnmg\x00nmz\x00nnnonnf\x00nnh\x00nnk\x00nnm\x00noornod\x00noe\x00non\x00" + - "nop\x00nou\x00nqo\x00nrblnrb\x00nsk\x00nsn\x00nso\x00nss\x00ntm\x00ntr" + - "\x00nui\x00nup\x00nus\x00nuv\x00nux\x00nvavnwb\x00nxq\x00nxr\x00nyyanym" + - "\x00nyn\x00nzi\x00occiogc\x00ojjiokr\x00okv\x00omrmong\x00onn\x00ons\x00" + - "opm\x00orrioro\x00oru\x00osssosa\x00ota\x00otk\x00ozm\x00paanpag\x00pal" + - "\x00pam\x00pap\x00pau\x00pbi\x00pcd\x00pcm\x00pdc\x00pdt\x00ped\x00peo" + - "\x00pex\x00pfl\x00phl\x00phn\x00pilipil\x00pip\x00pka\x00pko\x00plolpla" + - "\x00pms\x00png\x00pnn\x00pnt\x00pon\x00ppo\x00pra\x00prd\x00prg\x00psusp" + - "ss\x00ptorptp\x00puu\x00pwa\x00quuequc\x00qug\x00rai\x00raj\x00rao\x00rc" + - "f\x00rej\x00rel\x00res\x00rgn\x00rhg\x00ria\x00rif\x00rjs\x00rkt\x00rmoh" + - "rmf\x00rmo\x00rmt\x00rmu\x00rnunrna\x00rng\x00roonrob\x00rof\x00roo\x00r" + - "ro\x00rtm\x00ruusrue\x00rug\x00rw\x00\x04rwk\x00rwo\x00ryu\x00saansaf" + - "\x00sah\x00saq\x00sas\x00sat\x00sav\x00saz\x00sba\x00sbe\x00sbp\x00scrds" + - "ck\x00scl\x00scn\x00sco\x00scs\x00sdndsdc\x00sdh\x00semesef\x00seh\x00se" + - "i\x00ses\x00sgagsga\x00sgs\x00sgw\x00sgz\x00sh\x00\x02shi\x00shk\x00shn" + - "\x00shu\x00siinsid\x00sig\x00sil\x00sim\x00sjr\x00sklkskc\x00skr\x00sks" + - "\x00sllvsld\x00sli\x00sll\x00sly\x00smmosma\x00smi\x00smj\x00smn\x00smp" + - "\x00smq\x00sms\x00snnasnc\x00snk\x00snp\x00snx\x00sny\x00soomsok\x00soq" + - "\x00sou\x00soy\x00spd\x00spl\x00sps\x00sqqisrrpsrb\x00srn\x00srr\x00srx" + - "\x00ssswssd\x00ssg\x00ssy\x00stotstk\x00stq\x00suunsua\x00sue\x00suk\x00" + - "sur\x00sus\x00svweswwaswb\x00swc\x00swg\x00swp\x00swv\x00sxn\x00sxw\x00s" + - "yl\x00syr\x00szl\x00taamtaj\x00tal\x00tan\x00taq\x00tbc\x00tbd\x00tbf" + - "\x00tbg\x00tbo\x00tbw\x00tbz\x00tci\x00tcy\x00tdd\x00tdg\x00tdh\x00teelt" + - "ed\x00tem\x00teo\x00tet\x00tfi\x00tggktgc\x00tgo\x00tgu\x00thhathl\x00th" + - "q\x00thr\x00tiirtif\x00tig\x00tik\x00tim\x00tio\x00tiv\x00tkuktkl\x00tkr" + - "\x00tkt\x00tlgltlf\x00tlx\x00tly\x00tmh\x00tmy\x00tnsntnh\x00toontof\x00" + - "tog\x00toq\x00tpi\x00tpm\x00tpz\x00tqo\x00trurtru\x00trv\x00trw\x00tssot" + - "sd\x00tsf\x00tsg\x00tsj\x00tsw\x00ttatttd\x00tte\x00ttj\x00ttr\x00tts" + - "\x00ttt\x00tuh\x00tul\x00tum\x00tuq\x00tvd\x00tvl\x00tvu\x00twwitwh\x00t" + - "wq\x00txg\x00tyahtya\x00tyv\x00tzm\x00ubu\x00udm\x00ugiguga\x00ukkruli" + - "\x00umb\x00und\x00unr\x00unx\x00urrduri\x00urt\x00urw\x00usa\x00utr\x00u" + - "vh\x00uvl\x00uzzbvag\x00vai\x00van\x00veenvec\x00vep\x00viievic\x00viv" + - "\x00vls\x00vmf\x00vmw\x00voolvot\x00vro\x00vun\x00vut\x00walnwae\x00waj" + - "\x00wal\x00wan\x00war\x00wbp\x00wbq\x00wbr\x00wci\x00wer\x00wgi\x00whg" + - "\x00wib\x00wiu\x00wiv\x00wja\x00wji\x00wls\x00wmo\x00wnc\x00wni\x00wnu" + - "\x00woolwob\x00wos\x00wrs\x00wsk\x00wtm\x00wuu\x00wuv\x00wwa\x00xav\x00x" + - "bi\x00xcr\x00xes\x00xhhoxla\x00xlc\x00xld\x00xmf\x00xmn\x00xmr\x00xna" + - "\x00xnr\x00xog\x00xon\x00xpr\x00xrb\x00xsa\x00xsi\x00xsm\x00xsr\x00xwe" + - "\x00yam\x00yao\x00yap\x00yas\x00yat\x00yav\x00yay\x00yaz\x00yba\x00ybb" + - "\x00yby\x00yer\x00ygr\x00ygw\x00yiidyko\x00yle\x00ylg\x00yll\x00yml\x00y" + - "ooryon\x00yrb\x00yre\x00yrl\x00yss\x00yua\x00yue\x00yuj\x00yut\x00yuw" + - "\x00zahazag\x00zbl\x00zdj\x00zea\x00zgh\x00zhhozhx\x00zia\x00zlm\x00zmi" + - "\x00zne\x00zuulzxx\x00zza\x00\xff\xff\xff\xff" - -const langNoIndexOffset = 1330 - -// langNoIndex is a bit vector of all 3-letter language codes that are not used as an index -// in lookup tables. The language ids for these language codes are derived directly -// from the letters and are not consecutive. -// Size: 2197 bytes, 2197 elements -var langNoIndex = [2197]uint8{ - // Entry 0 - 3F - 0xff, 0xf8, 0xed, 0xfe, 0xeb, 0xd3, 0x3b, 0xd2, - 0xfb, 0xbf, 0x7a, 0xfa, 0x37, 0x1d, 0x3c, 0x57, - 0x6e, 0x97, 0x73, 0x38, 0xfb, 0xea, 0xbf, 0x70, - 0xad, 0x03, 0xff, 0xff, 0xcf, 0x05, 0x84, 0x62, - 0xe9, 0xbf, 0xfd, 0xbf, 0xbf, 0xf7, 0xfd, 0x77, - 0x0f, 0xff, 0xef, 0x6f, 0xff, 0xfb, 0xdf, 0xe2, - 0xc9, 0xf8, 0x7f, 0x7e, 0x4d, 0xbc, 0x0a, 0x6a, - 0x7c, 0xea, 0xe3, 0xfa, 0x7a, 0xbf, 0x67, 0xff, - // Entry 40 - 7F - 0xff, 0xff, 0xff, 0xdf, 0x2a, 0x54, 0x91, 0xc0, - 0x5d, 0xe3, 0x97, 0x14, 0x07, 0x20, 0xdd, 0xed, - 0x9f, 0x3f, 0xc9, 0x21, 0xf8, 0x3f, 0x94, 0x35, - 0x7c, 0x5f, 0xff, 0x5f, 0x8e, 0x6e, 0xdf, 0xff, - 0xff, 0xff, 0x55, 0x7c, 0xd3, 0xfd, 0xbf, 0xb5, - 0x7b, 0xdf, 0x7f, 0xf7, 0xca, 0xfe, 0xdb, 0xa3, - 0xa8, 0xff, 0x1f, 0x67, 0x7d, 0xeb, 0xef, 0xce, - 0xff, 0xff, 0x9f, 0xff, 0xb7, 0xef, 0xfe, 0xcf, - // Entry 80 - BF - 0xdb, 0xff, 0xf3, 0xcd, 0xfb, 0x6f, 0xff, 0xff, - 0xbb, 0xee, 0xf7, 0xbd, 0xdb, 0xff, 0x5f, 0xf7, - 0xfd, 0xf2, 0xfd, 0xff, 0x5e, 0x2f, 0x3b, 0xba, - 0x7e, 0xff, 0xff, 0xfe, 0xf7, 0xff, 0xdd, 0xff, - 0xfd, 0xdf, 0xfb, 0xfe, 0x9d, 0xb4, 0xd3, 0xff, - 0xef, 0xff, 0xdf, 0xf7, 0x7f, 0xb7, 0xfd, 0xd5, - 0xa5, 0x77, 0x40, 0xff, 0x9c, 0xc1, 0x41, 0x2c, - 0x08, 0x21, 0x41, 0x00, 0x50, 0x40, 0x00, 0x80, - // Entry C0 - FF - 0xfb, 0x4a, 0xf2, 0x9f, 0xb4, 0x42, 0x41, 0x96, - 0x1b, 0x14, 0x08, 0xf3, 0x2b, 0xe7, 0x17, 0x56, - 0x05, 0x7d, 0x0e, 0x1c, 0x37, 0x7b, 0xf3, 0xef, - 0x97, 0xff, 0x5d, 0x38, 0x64, 0x08, 0x00, 0x10, - 0xbc, 0x85, 0xaf, 0xdf, 0xff, 0xff, 0x7b, 0x35, - 0x3e, 0xc7, 0xc7, 0xdf, 0xff, 0x01, 0x81, 0x00, - 0xb0, 0x05, 0x80, 0x00, 0x00, 0x00, 0x00, 0x03, - 0x40, 0x00, 0x40, 0x92, 0x21, 0x50, 0xb1, 0x5d, - // Entry 100 - 13F - 0xfd, 0xdc, 0xbe, 0x5e, 0x00, 0x00, 0x02, 0x64, - 0x0d, 0x19, 0x41, 0xdf, 0x79, 0x22, 0x00, 0x00, - 0x00, 0x5e, 0x64, 0xdc, 0x24, 0xe5, 0xd9, 0xe3, - 0xfe, 0xff, 0xfd, 0xcb, 0x9f, 0x14, 0x41, 0x0c, - 0x86, 0x00, 0xd1, 0x00, 0xf0, 0xc7, 0x67, 0x5f, - 0x56, 0x99, 0x5e, 0xb5, 0x6c, 0xaf, 0x03, 0x00, - 0x02, 0x00, 0x00, 0x00, 0xc0, 0x37, 0xda, 0x56, - 0x90, 0x69, 0x01, 0x2c, 0x96, 0x69, 0x20, 0xfb, - // Entry 140 - 17F - 0xff, 0x3f, 0x00, 0x00, 0x00, 0x01, 0x0c, 0x16, - 0x03, 0x00, 0x00, 0xb0, 0x14, 0x03, 0x50, 0x06, - 0x0a, 0x00, 0x01, 0x00, 0x00, 0x10, 0x11, 0x09, - 0x00, 0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x10, - 0x00, 0x00, 0x44, 0x00, 0x00, 0x10, 0x00, 0x04, - 0x08, 0x00, 0x00, 0x05, 0x00, 0x80, 0x28, 0x04, - 0x00, 0x00, 0x40, 0xd5, 0x2d, 0x00, 0x64, 0x35, - 0x24, 0x52, 0xf4, 0xd5, 0xbf, 0x62, 0xc9, 0x03, - // Entry 180 - 1BF - 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x13, 0x39, 0x01, 0xdd, 0x57, 0x98, - 0x21, 0x18, 0x81, 0x00, 0x00, 0x01, 0x40, 0x82, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x40, 0x00, 0x44, 0x00, 0x00, 0x80, 0xea, - 0xa9, 0x39, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, - // Entry 1C0 - 1FF - 0x00, 0x03, 0x28, 0x05, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x20, 0x04, 0xa6, 0x00, 0x04, 0x00, 0x00, - 0x81, 0x50, 0x00, 0x00, 0x00, 0x11, 0x84, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x55, - 0x02, 0x10, 0x08, 0x04, 0x00, 0x00, 0x00, 0x40, - 0x30, 0x83, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x1e, 0xcd, 0xbf, 0x7a, 0xbf, - // Entry 200 - 23F - 0xdf, 0xc3, 0x83, 0x82, 0xc0, 0xfb, 0x57, 0x27, - 0xed, 0x55, 0xe7, 0x01, 0x00, 0x20, 0xb2, 0xc5, - 0xa4, 0x45, 0x25, 0x9b, 0x02, 0xdf, 0xe1, 0xdf, - 0x03, 0x44, 0x08, 0x90, 0x01, 0x04, 0x81, 0xe3, - 0x92, 0x54, 0xdb, 0x28, 0xd3, 0x5f, 0xfe, 0x6d, - 0x79, 0xed, 0x1c, 0x7d, 0x04, 0x08, 0x00, 0x01, - 0x21, 0x12, 0x64, 0x5f, 0xdd, 0x0e, 0x85, 0x4f, - 0x40, 0x40, 0x00, 0x04, 0xf1, 0xfd, 0x3d, 0x54, - // Entry 240 - 27F - 0xe8, 0x03, 0xb4, 0x27, 0x23, 0x0d, 0x00, 0x00, - 0x20, 0x7b, 0x78, 0x02, 0x07, 0x84, 0x00, 0xf0, - 0xbb, 0x7e, 0x5a, 0x00, 0x18, 0x04, 0x81, 0x00, - 0x00, 0x00, 0x80, 0x10, 0x90, 0x1c, 0x01, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x10, 0x40, 0x00, 0x04, - 0x08, 0xa0, 0x70, 0xa5, 0x0c, 0x40, 0x00, 0x00, - 0x91, 0x24, 0x04, 0x68, 0x00, 0x20, 0x70, 0xff, - 0x7b, 0x7f, 0x70, 0x00, 0x05, 0x9b, 0xdd, 0x66, - // Entry 280 - 2BF - 0x03, 0x00, 0x11, 0x00, 0x00, 0x00, 0x40, 0x05, - 0xb5, 0xb6, 0x80, 0x08, 0x04, 0x00, 0x04, 0x51, - 0xe2, 0xef, 0xfd, 0x3f, 0x05, 0x09, 0x08, 0x05, - 0x40, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, - 0x0c, 0x00, 0x00, 0x00, 0x00, 0x81, 0x00, 0x60, - 0xe7, 0x48, 0x00, 0x81, 0x20, 0xc0, 0x05, 0x80, - 0x03, 0x00, 0x00, 0x00, 0x8c, 0x50, 0x40, 0x04, - 0x84, 0x47, 0x84, 0x40, 0x20, 0x10, 0x00, 0x20, - // Entry 2C0 - 2FF - 0x02, 0x50, 0x80, 0x11, 0x00, 0x91, 0x6c, 0xe2, - 0x50, 0x27, 0x1d, 0x11, 0x29, 0x06, 0x59, 0xe9, - 0x33, 0x08, 0x00, 0x20, 0x04, 0x40, 0x10, 0x00, - 0x00, 0x00, 0x50, 0x44, 0x92, 0x49, 0xd6, 0x5d, - 0xa7, 0x81, 0x47, 0x97, 0xfb, 0x00, 0x10, 0x00, - 0x08, 0x00, 0x80, 0x00, 0x40, 0x04, 0x00, 0x01, - 0x02, 0x00, 0x01, 0x40, 0x80, 0x00, 0x00, 0x08, - 0xd8, 0xeb, 0xf6, 0x39, 0xc4, 0x8d, 0x12, 0x00, - // Entry 300 - 33F - 0x00, 0x0c, 0x04, 0x01, 0x20, 0x20, 0xdd, 0xa0, - 0x01, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, - 0x04, 0x10, 0xd0, 0x9d, 0x95, 0x13, 0x04, 0x80, - 0x00, 0x01, 0xd0, 0x16, 0x40, 0x00, 0x10, 0xb0, - 0x10, 0x62, 0x4c, 0xd2, 0x02, 0x01, 0x4a, 0x00, - 0x46, 0x04, 0x00, 0x08, 0x02, 0x00, 0x20, 0x80, - 0x00, 0x80, 0x06, 0x00, 0x08, 0x00, 0x00, 0x00, - 0x00, 0xf0, 0xd8, 0x6f, 0x15, 0x02, 0x08, 0x00, - // Entry 340 - 37F - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x10, 0x01, - 0x00, 0x10, 0x00, 0x00, 0x00, 0xf0, 0x84, 0xe3, - 0xdd, 0xbf, 0xf9, 0xf9, 0x3b, 0x7f, 0x7f, 0xdb, - 0xfd, 0xfc, 0xfe, 0xdf, 0xff, 0xfd, 0xff, 0xf6, - 0xfb, 0xfc, 0xf7, 0x1f, 0xff, 0xb3, 0x6c, 0xff, - 0xd9, 0xad, 0xdf, 0xfe, 0xef, 0xba, 0xdf, 0xff, - 0xff, 0xff, 0xb7, 0xdd, 0x7d, 0xbf, 0xab, 0x7f, - 0xfd, 0xfd, 0xdf, 0x2f, 0x9c, 0xdf, 0xf3, 0x6f, - // Entry 380 - 3BF - 0xdf, 0xdd, 0xff, 0xfb, 0xee, 0xd2, 0xab, 0x5f, - 0xd5, 0xdf, 0x7f, 0xff, 0xeb, 0xff, 0xe4, 0x4d, - 0xf9, 0xff, 0xfe, 0xf7, 0xfd, 0xdf, 0xfb, 0xbf, - 0xee, 0xdb, 0x6f, 0xef, 0xff, 0x7f, 0xff, 0xff, - 0xf7, 0x5f, 0xd3, 0x3b, 0xfd, 0xd9, 0xdf, 0xeb, - 0xbc, 0x08, 0x05, 0x24, 0xff, 0x07, 0x70, 0xfe, - 0xe6, 0x5e, 0x00, 0x08, 0x00, 0x83, 0x3d, 0x1b, - 0x06, 0xe6, 0x72, 0x60, 0xd1, 0x3c, 0x7f, 0x44, - // Entry 3C0 - 3FF - 0x02, 0x30, 0x9f, 0x7a, 0x16, 0xbd, 0x7f, 0x57, - 0xf2, 0xff, 0x31, 0xff, 0xf2, 0x1e, 0x90, 0xf7, - 0xf1, 0xf9, 0x45, 0x80, 0x01, 0x02, 0x00, 0x00, - 0x40, 0x54, 0x9f, 0x8a, 0xdb, 0xf9, 0x2e, 0x11, - 0x86, 0x51, 0xc0, 0xf3, 0xfb, 0x47, 0x40, 0x01, - 0x05, 0xd1, 0x50, 0x5c, 0x00, 0x40, 0x00, 0x10, - 0x04, 0x02, 0x00, 0x00, 0x0a, 0x00, 0x17, 0xd2, - 0xb9, 0xfd, 0xfc, 0xba, 0xfe, 0xef, 0xc7, 0xbe, - // Entry 400 - 43F - 0x53, 0x6f, 0xdf, 0xe7, 0xdb, 0x65, 0xbb, 0x7f, - 0xfa, 0xff, 0x77, 0xf3, 0xef, 0xbf, 0xfd, 0xf7, - 0xdf, 0xdf, 0x9b, 0x7f, 0xff, 0xff, 0x7f, 0x6f, - 0xf7, 0xfb, 0xeb, 0xdf, 0xbc, 0xff, 0xbf, 0x6b, - 0x7b, 0xfb, 0xff, 0xce, 0x76, 0xbd, 0xf7, 0xf7, - 0xdf, 0xdc, 0xf7, 0xf7, 0xff, 0xdf, 0xf3, 0xfe, - 0xef, 0xff, 0xff, 0xff, 0xb6, 0x7f, 0x7f, 0xde, - 0xf7, 0xb9, 0xeb, 0x77, 0xff, 0xfb, 0xbf, 0xdf, - // Entry 440 - 47F - 0xfd, 0xfe, 0xfb, 0xff, 0xfe, 0xeb, 0x1f, 0x7d, - 0x2f, 0xfd, 0xb6, 0xb5, 0xa5, 0xfc, 0xff, 0xfd, - 0x7f, 0x4e, 0xbf, 0x8f, 0xae, 0xff, 0xee, 0xdf, - 0x7f, 0xf7, 0x73, 0x02, 0x02, 0x04, 0xfc, 0xf7, - 0xff, 0xb7, 0xd7, 0xef, 0xfe, 0xcd, 0xf5, 0xce, - 0xe2, 0x8e, 0xe7, 0xbf, 0xb7, 0xff, 0x56, 0xfd, - 0xcd, 0xff, 0xfb, 0xff, 0xdf, 0xd7, 0xea, 0xff, - 0xe5, 0x5f, 0x6d, 0x0f, 0xa7, 0x51, 0x06, 0xc4, - // Entry 480 - 4BF - 0x93, 0x50, 0x5d, 0xaf, 0xa6, 0xff, 0x99, 0xfb, - 0x63, 0x1d, 0x53, 0xff, 0xef, 0xb7, 0x35, 0x20, - 0x14, 0x00, 0x55, 0x51, 0x82, 0x65, 0xf5, 0x41, - 0xe2, 0xff, 0xfc, 0xdf, 0x02, 0x05, 0xc5, 0x05, - 0x00, 0x22, 0x00, 0x74, 0x69, 0x10, 0x08, 0x05, - 0x41, 0x00, 0x01, 0x06, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x51, 0x20, 0x05, 0x04, 0x01, 0x00, 0x00, - 0x06, 0x01, 0x20, 0x00, 0x18, 0x01, 0x92, 0xf1, - // Entry 4C0 - 4FF - 0xfd, 0x47, 0x69, 0x06, 0x95, 0x06, 0x57, 0xed, - 0xfb, 0x4d, 0x1c, 0x6b, 0x83, 0x04, 0x62, 0x40, - 0x00, 0x11, 0x42, 0x00, 0x00, 0x00, 0x54, 0x83, - 0xb8, 0x4f, 0x10, 0x8e, 0x89, 0x46, 0xde, 0xf7, - 0x13, 0x31, 0x00, 0x20, 0x00, 0x00, 0x00, 0x90, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x10, 0x00, - 0x01, 0x00, 0x00, 0xf0, 0x5b, 0xf4, 0xbe, 0x3d, - 0xbe, 0xcf, 0xf7, 0xaf, 0x42, 0x04, 0x84, 0x41, - // Entry 500 - 53F - 0x30, 0xff, 0x79, 0x72, 0x04, 0x00, 0x00, 0x49, - 0x2d, 0x14, 0x27, 0x57, 0xed, 0xf1, 0x3f, 0xe7, - 0x3f, 0x00, 0x00, 0x02, 0xc6, 0xa0, 0x1e, 0xf8, - 0xbb, 0xff, 0xfd, 0xfb, 0xb7, 0xfd, 0xe7, 0xf7, - 0xfd, 0xfc, 0xd5, 0xed, 0x47, 0xf4, 0x7e, 0x10, - 0x01, 0x01, 0x84, 0x6d, 0xff, 0xf7, 0xdd, 0xf9, - 0x5b, 0x05, 0x86, 0xed, 0xf5, 0x77, 0xbd, 0x3c, - 0x00, 0x00, 0x00, 0x42, 0x71, 0x42, 0x00, 0x40, - // Entry 540 - 57F - 0x00, 0x00, 0x01, 0x43, 0x19, 0x00, 0x08, 0x00, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - // Entry 580 - 5BF - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xab, 0xbd, 0xe7, 0x57, 0xee, 0x13, 0x5d, - 0x09, 0xc1, 0x40, 0x21, 0xfa, 0x17, 0x01, 0x80, - 0x00, 0x00, 0x00, 0x00, 0xf0, 0xce, 0xfb, 0xbf, - 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, - 0x00, 0x30, 0x15, 0xa3, 0x10, 0x00, 0x00, 0x00, - 0x11, 0x04, 0x16, 0x00, 0x00, 0x02, 0x00, 0x81, - 0xa3, 0x01, 0x50, 0x00, 0x00, 0x83, 0x11, 0x40, - // Entry 5C0 - 5FF - 0x00, 0x00, 0x00, 0xf0, 0xdd, 0x7b, 0x3e, 0x02, - 0xaa, 0x10, 0x5d, 0x98, 0x52, 0x00, 0x80, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x02, 0x02, - 0x19, 0x00, 0x10, 0x02, 0x10, 0x61, 0x5a, 0x9d, - 0x31, 0x00, 0x00, 0x00, 0x01, 0x18, 0x02, 0x20, - 0x00, 0x00, 0x01, 0x00, 0x42, 0x00, 0x20, 0x00, - 0x00, 0x1f, 0xdf, 0xd2, 0xb9, 0xff, 0xfd, 0x3f, - 0x1f, 0x98, 0xcf, 0x9c, 0xff, 0xaf, 0x5f, 0xfe, - // Entry 600 - 63F - 0x7b, 0x4b, 0x40, 0x10, 0xe1, 0xfd, 0xaf, 0xd9, - 0xb7, 0xf6, 0xfb, 0xb3, 0xc7, 0xff, 0x6f, 0xf1, - 0x73, 0xb1, 0x7f, 0x9f, 0x7f, 0xbd, 0xfc, 0xb7, - 0xee, 0x1c, 0xfa, 0xcb, 0xef, 0xdd, 0xf9, 0xbd, - 0x6e, 0xae, 0x55, 0xfd, 0x6e, 0x81, 0x76, 0x9f, - 0xd4, 0x77, 0xf5, 0x7d, 0xfb, 0xff, 0xeb, 0xfe, - 0xbe, 0x5f, 0x46, 0x5b, 0xe9, 0x5f, 0x50, 0x18, - 0x02, 0xfa, 0xf7, 0x9d, 0x15, 0x97, 0x05, 0x0f, - // Entry 640 - 67F - 0x75, 0xc4, 0x7d, 0x81, 0x92, 0xf5, 0x57, 0x6c, - 0xff, 0xe4, 0xef, 0x6f, 0xff, 0xfc, 0xdd, 0xde, - 0xfc, 0xfd, 0x76, 0x5f, 0x7a, 0x3f, 0x00, 0x98, - 0x02, 0xfb, 0xa3, 0xef, 0xf3, 0xd6, 0xf2, 0xff, - 0xb9, 0xda, 0x7d, 0xd0, 0x3e, 0x15, 0x7b, 0xb4, - 0xf5, 0x3e, 0xff, 0xff, 0xf1, 0xf7, 0xff, 0xe7, - 0x5f, 0xff, 0xff, 0x9e, 0xdb, 0xf6, 0xd7, 0xb9, - 0xef, 0x27, 0x80, 0xbb, 0xc5, 0xff, 0xff, 0xe3, - // Entry 680 - 6BF - 0x97, 0x9d, 0xbf, 0x9f, 0xf7, 0xc7, 0xfd, 0x37, - 0xce, 0x7f, 0x04, 0x1d, 0x73, 0x7f, 0xf8, 0xda, - 0x5d, 0xce, 0x7d, 0x06, 0xb9, 0xea, 0x79, 0xa0, - 0x1a, 0x20, 0x00, 0x30, 0x02, 0x04, 0x24, 0x08, - 0x04, 0x00, 0x00, 0x40, 0xd4, 0x02, 0x04, 0x00, - 0x00, 0x04, 0x00, 0x04, 0x00, 0x20, 0x01, 0x06, - 0x50, 0x00, 0x08, 0x00, 0x00, 0x00, 0x24, 0x00, - 0x04, 0x00, 0x10, 0xdc, 0x58, 0xd7, 0x0d, 0x0f, - // Entry 6C0 - 6FF - 0x14, 0x4d, 0xf1, 0x16, 0x44, 0xd5, 0x42, 0x08, - 0x40, 0x00, 0x00, 0x40, 0x00, 0x08, 0x00, 0x00, - 0x00, 0xdc, 0xfb, 0xcb, 0x0e, 0x58, 0x48, 0x41, - 0x24, 0x20, 0x04, 0x00, 0x30, 0x12, 0x40, 0x00, - 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x80, 0x10, 0x10, 0xab, - 0x6d, 0x93, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x80, 0x80, 0x25, 0x00, 0x00, - // Entry 700 - 73F - 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, - 0x80, 0x86, 0xc2, 0x00, 0x00, 0x00, 0x00, 0x01, - 0xff, 0x18, 0x02, 0x00, 0x02, 0xf0, 0xfd, 0x79, - 0x3b, 0x00, 0x25, 0x00, 0x00, 0x00, 0x02, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, - 0x03, 0x00, 0x09, 0x20, 0x00, 0x00, 0x01, 0x00, - 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 740 - 77F - 0x00, 0x00, 0x00, 0xef, 0xd5, 0xfd, 0xcf, 0x7e, - 0xb0, 0x11, 0x00, 0x00, 0x00, 0x92, 0x01, 0x44, - 0xcd, 0xf9, 0x5c, 0x00, 0x01, 0x00, 0x30, 0x04, - 0x04, 0x55, 0x00, 0x01, 0x04, 0xf4, 0x3f, 0x4a, - 0x01, 0x00, 0x00, 0xb0, 0x80, 0x20, 0x55, 0x75, - 0x97, 0x7c, 0xdf, 0x31, 0xcc, 0x68, 0xd1, 0x03, - 0xd5, 0x57, 0x27, 0x14, 0x01, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x2c, 0xf7, 0xcb, 0x1f, 0x14, 0x60, - // Entry 780 - 7BF - 0x03, 0x68, 0x01, 0x10, 0x8b, 0x38, 0x8a, 0x01, - 0x00, 0x00, 0x20, 0x00, 0x24, 0x44, 0x00, 0x00, - 0x10, 0x03, 0x11, 0x02, 0x01, 0x00, 0x00, 0xf0, - 0xf5, 0xff, 0xd5, 0x97, 0xbc, 0x70, 0xd6, 0x78, - 0x78, 0x15, 0x50, 0x01, 0xa4, 0x84, 0xa9, 0x41, - 0x00, 0x00, 0x00, 0x6b, 0x39, 0x52, 0x74, 0x00, - 0xe8, 0x30, 0x90, 0x6a, 0x92, 0x00, 0x00, 0x02, - 0xff, 0xef, 0xff, 0x4b, 0x85, 0x53, 0xf4, 0xed, - // Entry 7C0 - 7FF - 0xdd, 0xbf, 0xf2, 0x5d, 0xc7, 0x0c, 0xd5, 0x42, - 0xfc, 0xff, 0xf7, 0x1f, 0x00, 0x80, 0x40, 0x56, - 0xcc, 0x16, 0x9e, 0xea, 0x35, 0x7d, 0xef, 0xff, - 0xbd, 0xa4, 0xaf, 0x01, 0x44, 0x18, 0x01, 0x4d, - 0x4e, 0x4a, 0x08, 0x50, 0x28, 0x30, 0xe0, 0x80, - 0x10, 0x20, 0x24, 0x00, 0xff, 0x2f, 0xd3, 0x60, - 0xfe, 0x01, 0x02, 0x88, 0x0a, 0x40, 0x16, 0x01, - 0x01, 0x15, 0x2b, 0x3c, 0x01, 0x00, 0x00, 0x10, - // Entry 800 - 83F - 0x90, 0x49, 0x41, 0x02, 0x02, 0x01, 0xe1, 0xbf, - 0xbf, 0x03, 0x00, 0x00, 0x10, 0xd4, 0xa3, 0xd1, - 0x40, 0x9c, 0x44, 0xdf, 0xf5, 0x8f, 0x66, 0xb3, - 0x55, 0x20, 0xd4, 0xc1, 0xd8, 0x30, 0x3d, 0x80, - 0x00, 0x00, 0x00, 0x04, 0xd4, 0x11, 0xc5, 0x84, - 0x2f, 0x50, 0x00, 0x22, 0x50, 0x6e, 0xbd, 0x93, - 0x07, 0x00, 0x20, 0x10, 0x84, 0xb2, 0x45, 0x10, - 0x06, 0x44, 0x00, 0x00, 0x12, 0x02, 0x11, 0x00, - // Entry 840 - 87F - 0xf0, 0xfb, 0xfd, 0x7f, 0x05, 0x00, 0x16, 0x81, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x02, - 0x00, 0x00, 0x00, 0x00, 0x03, 0x30, 0x02, 0x28, - 0x84, 0x00, 0x21, 0xc0, 0x23, 0x24, 0x00, 0x00, - 0x00, 0xcb, 0xe4, 0x3a, 0x46, 0x88, 0x14, 0xf1, - 0xef, 0xff, 0x7f, 0x12, 0x01, 0x01, 0x84, 0x50, - 0x07, 0xfc, 0xff, 0xff, 0x0f, 0x01, 0x00, 0x40, - 0x10, 0x38, 0x01, 0x01, 0x1c, 0x12, 0x40, 0xe1, - // Entry 880 - 8BF - 0x76, 0x16, 0x08, 0x03, 0x10, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x24, - 0x0a, 0x00, 0x80, 0x00, 0x00, -} - -// altLangISO3 holds an alphabetically sorted list of 3-letter language code alternatives -// to 2-letter language codes that cannot be derived using the method described above. -// Each 3-letter code is followed by its 1-byte langID. -const altLangISO3 tag.Index = "---\x00cor\x00hbs\x01heb\x02kin\x03spa\x04yid\x05\xff\xff\xff\xff" - -// altLangIndex is used to convert indexes in altLangISO3 to langIDs. -// Size: 12 bytes, 6 elements -var altLangIndex = [6]uint16{ - 0x0281, 0x0407, 0x01fb, 0x03e5, 0x013e, 0x0208, -} - -// AliasMap maps langIDs to their suggested replacements. -// Size: 716 bytes, 179 elements -var AliasMap = [179]FromTo{ - 0: {From: 0x82, To: 0x88}, - 1: {From: 0x187, To: 0x1ae}, - 2: {From: 0x1f3, To: 0x1e1}, - 3: {From: 0x1fb, To: 0x1bc}, - 4: {From: 0x208, To: 0x512}, - 5: {From: 0x20f, To: 0x20e}, - 6: {From: 0x310, To: 0x3dc}, - 7: {From: 0x347, To: 0x36f}, - 8: {From: 0x407, To: 0x432}, - 9: {From: 0x47a, To: 0x153}, - 10: {From: 0x490, To: 0x451}, - 11: {From: 0x4a2, To: 0x21}, - 12: {From: 0x53e, To: 0x544}, - 13: {From: 0x58f, To: 0x12d}, - 14: {From: 0x630, To: 0x1eb1}, - 15: {From: 0x651, To: 0x431}, - 16: {From: 0x662, To: 0x431}, - 17: {From: 0x6ed, To: 0x3a}, - 18: {From: 0x6f8, To: 0x1d7}, - 19: {From: 0x709, To: 0x3625}, - 20: {From: 0x73e, To: 0x21a1}, - 21: {From: 0x7b3, To: 0x56}, - 22: {From: 0x7b9, To: 0x299b}, - 23: {From: 0x7c5, To: 0x58}, - 24: {From: 0x7e6, To: 0x145}, - 25: {From: 0x80c, To: 0x5a}, - 26: {From: 0x815, To: 0x8d}, - 27: {From: 0x87e, To: 0x810}, - 28: {From: 0x8a8, To: 0x8b7}, - 29: {From: 0x8c3, To: 0xee3}, - 30: {From: 0x8fa, To: 0x1dc}, - 31: {From: 0x9ef, To: 0x331}, - 32: {From: 0xa36, To: 0x2c5}, - 33: {From: 0xa3d, To: 0xbf}, - 34: {From: 0xabe, To: 0x3322}, - 35: {From: 0xb38, To: 0x529}, - 36: {From: 0xb75, To: 0x265a}, - 37: {From: 0xb7e, To: 0xbc3}, - 38: {From: 0xb9b, To: 0x44e}, - 39: {From: 0xbbc, To: 0x4229}, - 40: {From: 0xbbf, To: 0x529}, - 41: {From: 0xbfe, To: 0x2da7}, - 42: {From: 0xc2e, To: 0x3181}, - 43: {From: 0xcb9, To: 0xf3}, - 44: {From: 0xd08, To: 0xfa}, - 45: {From: 0xdc8, To: 0x11a}, - 46: {From: 0xdd7, To: 0x32d}, - 47: {From: 0xdf8, To: 0xdfb}, - 48: {From: 0xdfe, To: 0x531}, - 49: {From: 0xe01, To: 0xdf3}, - 50: {From: 0xedf, To: 0x205a}, - 51: {From: 0xee9, To: 0x222e}, - 52: {From: 0xeee, To: 0x2e9a}, - 53: {From: 0xf39, To: 0x367}, - 54: {From: 0x10d0, To: 0x140}, - 55: {From: 0x1104, To: 0x2d0}, - 56: {From: 0x11a0, To: 0x1ec}, - 57: {From: 0x1279, To: 0x21}, - 58: {From: 0x1424, To: 0x15e}, - 59: {From: 0x1470, To: 0x14e}, - 60: {From: 0x151f, To: 0xd9b}, - 61: {From: 0x1523, To: 0x390}, - 62: {From: 0x1532, To: 0x19f}, - 63: {From: 0x1580, To: 0x210}, - 64: {From: 0x1583, To: 0x10d}, - 65: {From: 0x15a3, To: 0x3caf}, - 66: {From: 0x1630, To: 0x222e}, - 67: {From: 0x166a, To: 0x19b}, - 68: {From: 0x16c8, To: 0x136}, - 69: {From: 0x1700, To: 0x29f8}, - 70: {From: 0x1718, To: 0x194}, - 71: {From: 0x1727, To: 0xf3f}, - 72: {From: 0x177a, To: 0x178}, - 73: {From: 0x1809, To: 0x17b6}, - 74: {From: 0x1816, To: 0x18f3}, - 75: {From: 0x188a, To: 0x436}, - 76: {From: 0x1979, To: 0x1d01}, - 77: {From: 0x1a74, To: 0x2bb0}, - 78: {From: 0x1a8a, To: 0x1f8}, - 79: {From: 0x1b5a, To: 0x1fa}, - 80: {From: 0x1b86, To: 0x1515}, - 81: {From: 0x1d64, To: 0x2c9b}, - 82: {From: 0x2038, To: 0x37b1}, - 83: {From: 0x203d, To: 0x20dd}, - 84: {From: 0x205a, To: 0x30b}, - 85: {From: 0x20e3, To: 0x274}, - 86: {From: 0x20ee, To: 0x263}, - 87: {From: 0x20f2, To: 0x22d}, - 88: {From: 0x20f9, To: 0x256}, - 89: {From: 0x210f, To: 0x21eb}, - 90: {From: 0x2135, To: 0x27d}, - 91: {From: 0x2160, To: 0x913}, - 92: {From: 0x2199, To: 0x121}, - 93: {From: 0x21ce, To: 0x1561}, - 94: {From: 0x21e6, To: 0x504}, - 95: {From: 0x21f4, To: 0x49f}, - 96: {From: 0x21fb, To: 0x269}, - 97: {From: 0x222d, To: 0x121}, - 98: {From: 0x2237, To: 0x121}, - 99: {From: 0x2262, To: 0x92a}, - 100: {From: 0x2316, To: 0x3226}, - 101: {From: 0x236a, To: 0x2835}, - 102: {From: 0x2382, To: 0x3365}, - 103: {From: 0x2472, To: 0x2c7}, - 104: {From: 0x24e4, To: 0x2ff}, - 105: {From: 0x24f0, To: 0x2fa}, - 106: {From: 0x24fa, To: 0x31f}, - 107: {From: 0x2550, To: 0xb5b}, - 108: {From: 0x25a9, To: 0xe2}, - 109: {From: 0x263e, To: 0x2d0}, - 110: {From: 0x26c9, To: 0x26b4}, - 111: {From: 0x26f9, To: 0x3c8}, - 112: {From: 0x2727, To: 0x3caf}, - 113: {From: 0x2755, To: 0x6a4}, - 114: {From: 0x2765, To: 0x26b4}, - 115: {From: 0x2789, To: 0x4358}, - 116: {From: 0x27c9, To: 0x2001}, - 117: {From: 0x28ea, To: 0x27b1}, - 118: {From: 0x28ef, To: 0x2837}, - 119: {From: 0x2914, To: 0x351}, - 120: {From: 0x2986, To: 0x2da7}, - 121: {From: 0x29f0, To: 0x96b}, - 122: {From: 0x2b1a, To: 0x38d}, - 123: {From: 0x2bfc, To: 0x395}, - 124: {From: 0x2c3f, To: 0x3caf}, - 125: {From: 0x2ce1, To: 0x2201}, - 126: {From: 0x2cfc, To: 0x3be}, - 127: {From: 0x2d13, To: 0x597}, - 128: {From: 0x2d47, To: 0x148}, - 129: {From: 0x2d48, To: 0x148}, - 130: {From: 0x2dff, To: 0x2f1}, - 131: {From: 0x2e08, To: 0x19cc}, - 132: {From: 0x2e1a, To: 0x2d95}, - 133: {From: 0x2e21, To: 0x292}, - 134: {From: 0x2e54, To: 0x7d}, - 135: {From: 0x2e65, To: 0x2282}, - 136: {From: 0x2ea0, To: 0x2e9b}, - 137: {From: 0x2eef, To: 0x2ed7}, - 138: {From: 0x3193, To: 0x3c4}, - 139: {From: 0x3366, To: 0x338e}, - 140: {From: 0x342a, To: 0x3dc}, - 141: {From: 0x34ee, To: 0x18d0}, - 142: {From: 0x35c8, To: 0x2c9b}, - 143: {From: 0x35e6, To: 0x412}, - 144: {From: 0x3658, To: 0x246}, - 145: {From: 0x3676, To: 0x3f4}, - 146: {From: 0x36fd, To: 0x445}, - 147: {From: 0x37c0, To: 0x121}, - 148: {From: 0x3816, To: 0x38f2}, - 149: {From: 0x382a, To: 0x2b48}, - 150: {From: 0x382b, To: 0x2c9b}, - 151: {From: 0x382f, To: 0xa9}, - 152: {From: 0x3832, To: 0x3228}, - 153: {From: 0x386c, To: 0x39a6}, - 154: {From: 0x3892, To: 0x3fc0}, - 155: {From: 0x38a5, To: 0x39d7}, - 156: {From: 0x38b4, To: 0x1fa4}, - 157: {From: 0x38b5, To: 0x2e9a}, - 158: {From: 0x395c, To: 0x47e}, - 159: {From: 0x3b4e, To: 0xd91}, - 160: {From: 0x3b78, To: 0x137}, - 161: {From: 0x3c99, To: 0x4bc}, - 162: {From: 0x3fbd, To: 0x100}, - 163: {From: 0x4208, To: 0xa91}, - 164: {From: 0x42be, To: 0x573}, - 165: {From: 0x42f9, To: 0x3f60}, - 166: {From: 0x4378, To: 0x25a}, - 167: {From: 0x43b8, To: 0xe6c}, - 168: {From: 0x43cd, To: 0x10f}, - 169: {From: 0x44af, To: 0x3322}, - 170: {From: 0x44e3, To: 0x512}, - 171: {From: 0x45ca, To: 0x2409}, - 172: {From: 0x45dd, To: 0x26dc}, - 173: {From: 0x4610, To: 0x48ae}, - 174: {From: 0x46ae, To: 0x46a0}, - 175: {From: 0x473e, To: 0x4745}, - 176: {From: 0x4817, To: 0x3503}, - 177: {From: 0x4916, To: 0x31f}, - 178: {From: 0x49a7, To: 0x523}, -} - -// Size: 179 bytes, 179 elements -var AliasTypes = [179]AliasType{ - // Entry 0 - 3F - 1, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 1, 0, 0, 1, 2, - 1, 1, 2, 0, 0, 1, 0, 1, 2, 1, 1, 0, 0, 0, 0, 2, - 1, 1, 0, 2, 0, 0, 1, 0, 1, 0, 0, 1, 2, 1, 1, 1, - 1, 0, 0, 0, 0, 2, 1, 1, 1, 1, 2, 1, 0, 1, 1, 2, - // Entry 40 - 7F - 2, 0, 0, 1, 2, 0, 1, 0, 1, 1, 1, 1, 0, 0, 2, 1, - 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, - 0, 0, 0, 1, 0, 0, 0, 1, 2, 2, 2, 0, 1, 1, 0, 1, - 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, - // Entry 80 - BF - 2, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 2, 0, 0, 2, - 1, 1, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 1, - 0, 1, 2, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, - 0, 1, 1, -} - -const ( - _Latn = 90 - _Hani = 57 - _Hans = 59 - _Hant = 60 - _Qaaa = 147 - _Qaai = 155 - _Qabx = 196 - _Zinh = 252 - _Zyyy = 257 - _Zzzz = 258 -) - -// script is an alphabetically sorted list of ISO 15924 codes. The index -// of the script in the string, divided by 4, is the internal scriptID. -const script tag.Index = "" + // Size: 1040 bytes - "----AdlmAfakAghbAhomArabAranArmiArmnAvstBaliBamuBassBatkBengBhksBlisBopo" + - "BrahBraiBugiBuhdCakmCansCariChamCherChrsCirtCoptCpmnCprtCyrlCyrsDevaDiak" + - "DogrDsrtDuplEgydEgyhEgypElbaElymEthiGeokGeorGlagGongGonmGothGranGrekGujr" + - "GuruHanbHangHaniHanoHansHantHatrHebrHiraHluwHmngHmnpHrktHungIndsItalJamo" + - "JavaJpanJurcKaliKanaKharKhmrKhojKitlKitsKndaKoreKpelKthiLanaLaooLatfLatg" + - "LatnLekeLepcLimbLinaLinbLisuLomaLyciLydiMahjMakaMandManiMarcMayaMedfMend" + - "MercMeroMlymModiMongMoonMrooMteiMultMymrNandNarbNbatNewaNkdbNkgbNkooNshu" + - "OgamOlckOrkhOryaOsgeOsmaOugrPalmPaucPcunPelmPermPhagPhliPhlpPhlvPhnxPiqd" + - "PlrdPrtiPsinQaaaQaabQaacQaadQaaeQaafQaagQaahQaaiQaajQaakQaalQaamQaanQaao" + - "QaapQaaqQaarQaasQaatQaauQaavQaawQaaxQaayQaazQabaQabbQabcQabdQabeQabfQabg" + - "QabhQabiQabjQabkQablQabmQabnQaboQabpQabqQabrQabsQabtQabuQabvQabwQabxRanj" + - "RjngRohgRoroRunrSamrSaraSarbSaurSgnwShawShrdShuiSiddSindSinhSogdSogoSora" + - "SoyoSundSyloSyrcSyreSyrjSyrnTagbTakrTaleTaluTamlTangTavtTeluTengTfngTglg" + - "ThaaThaiTibtTirhTnsaTotoUgarVaiiVispVithWaraWchoWoleXpeoXsuxYeziYiiiZanb" + - "ZinhZmthZsyeZsymZxxxZyyyZzzz\xff\xff\xff\xff" - -// suppressScript is an index from langID to the dominant script for that language, -// if it exists. If a script is given, it should be suppressed from the language tag. -// Size: 1330 bytes, 1330 elements -var suppressScript = [1330]uint8{ - // Entry 0 - 3F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 40 - 7F - 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, - // Entry 80 - BF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry C0 - FF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 100 - 13F - 0x5a, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xea, 0x00, 0x00, 0x00, 0x00, 0xec, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x5a, 0x00, 0x5a, 0x00, - // Entry 140 - 17F - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x5a, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x5a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 180 - 1BF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x5a, 0x35, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x22, 0x00, - // Entry 1C0 - 1FF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x5a, 0x00, 0x5a, 0x5a, 0x00, 0x08, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x5a, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00, - // Entry 200 - 23F - 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x2e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 240 - 27F - 0x00, 0x00, 0x20, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x00, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x52, 0x00, 0x00, 0x53, 0x00, 0x22, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 280 - 2BF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 2C0 - 2FF - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, - // Entry 300 - 33F - 0x00, 0x00, 0x00, 0x00, 0x6e, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x5a, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x75, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, - // Entry 340 - 37F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x5a, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x5a, 0x00, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 380 - 3BF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, - // Entry 3C0 - 3FF - 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x20, 0x00, 0x00, 0x5a, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 400 - 43F - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0xd4, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, - // Entry 440 - 47F - 0x00, 0x00, 0x00, 0x00, 0x5a, 0x5a, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xe3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0xe6, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0xeb, 0x00, 0x00, 0x00, 0x2c, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, - // Entry 480 - 4BF - 0x5a, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x5a, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 4C0 - 4FF - 0x5a, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 500 - 53F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, - 0x00, 0x00, -} - -const ( - _001 = 1 - _419 = 31 - _BR = 65 - _CA = 73 - _ES = 110 - _GB = 123 - _MD = 188 - _PT = 238 - _UK = 306 - _US = 309 - _ZZ = 357 - _XA = 323 - _XC = 325 - _XK = 333 -) - -// isoRegionOffset needs to be added to the index of regionISO to obtain the regionID -// for 2-letter ISO codes. (The first isoRegionOffset regionIDs are reserved for -// the UN.M49 codes used for groups.) -const isoRegionOffset = 32 - -// regionTypes defines the status of a region for various standards. -// Size: 358 bytes, 358 elements -var regionTypes = [358]uint8{ - // Entry 0 - 3F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - // Entry 40 - 7F - 0x06, 0x06, 0x06, 0x06, 0x04, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x04, 0x06, 0x04, - 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x04, - 0x06, 0x04, 0x06, 0x06, 0x06, 0x06, 0x00, 0x06, - 0x04, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x04, 0x06, 0x06, 0x06, 0x06, 0x06, 0x00, - 0x06, 0x04, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - // Entry 80 - BF - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x00, 0x04, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x00, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - // Entry C0 - FF - 0x06, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x00, - 0x06, 0x06, 0x06, 0x06, 0x00, 0x06, 0x04, 0x06, - 0x06, 0x06, 0x06, 0x00, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x00, - 0x06, 0x06, 0x00, 0x06, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - // Entry 100 - 13F - 0x05, 0x05, 0x06, 0x00, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x04, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x02, 0x06, 0x04, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x00, 0x06, 0x06, 0x06, 0x06, 0x06, - // Entry 140 - 17F - 0x06, 0x00, 0x06, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x04, 0x06, 0x06, - 0x04, 0x06, 0x06, 0x04, 0x06, 0x05, -} - -// regionISO holds a list of alphabetically sorted 2-letter ISO region codes. -// Each 2-letter codes is followed by two bytes with the following meaning: -// - [A-Z}{2}: the first letter of the 2-letter code plus these two -// letters form the 3-letter ISO code. -// - 0, n: index into altRegionISO3. -const regionISO tag.Index = "" + // Size: 1308 bytes - "AAAAACSCADNDAEREAFFGAGTGAIIAALLBAMRMANNTAOGOAQTAARRGASSMATUTAUUSAWBWAXLA" + - "AZZEBAIHBBRBBDGDBEELBFFABGGRBHHRBIDIBJENBLLMBMMUBNRNBOOLBQESBRRABSHSBTTN" + - "BUURBVVTBWWABYLRBZLZCAANCCCKCDODCFAFCGOGCHHECIIVCKOKCLHLCMMRCNHNCOOLCPPT" + - "CRRICS\x00\x00CTTECUUBCVPVCWUWCXXRCYYPCZZEDDDRDEEUDGGADJJIDKNKDMMADOOMDY" + - "HYDZZAEA ECCUEESTEGGYEHSHERRIESSPETTHEU\x00\x03EZ FIINFJJIFKLKFMSMFORO" + - "FQ\x00\x18FRRAFXXXGAABGBBRGDRDGEEOGFUFGGGYGHHAGIIBGLRLGMMBGNINGPLPGQNQGR" + - "RCGS\x00\x06GTTMGUUMGWNBGYUYHKKGHMMDHNNDHRRVHTTIHUUNHVVOIC IDDNIERLILSR" + - "IMMNINNDIOOTIQRQIRRNISSLITTAJEEYJMAMJOORJPPNJTTNKEENKGGZKHHMKIIRKM\x00" + - "\x09KNNAKP\x00\x0cKRORKWWTKY\x00\x0fKZAZLAAOLBBNLCCALIIELKKALRBRLSSOLTTU" + - "LUUXLVVALYBYMAARMCCOMDDAMENEMFAFMGDGMHHLMIIDMKKDMLLIMMMRMNNGMOACMPNPMQTQ" + - "MRRTMSSRMTLTMUUSMVDVMWWIMXEXMYYSMZOZNAAMNCCLNEERNFFKNGGANHHBNIICNLLDNOOR" + - "NPPLNQ\x00\x1eNRRUNTTZNUIUNZZLOMMNPAANPCCIPEERPFYFPGNGPHHLPKAKPLOLPM\x00" + - "\x12PNCNPRRIPSSEPTRTPUUSPWLWPYRYPZCZQAATQMMMQNNNQOOOQPPPQQQQQRRRQSSSQTTT" + - "QU\x00\x03QVVVQWWWQXXXQYYYQZZZREEURHHOROOURS\x00\x15RUUSRWWASAAUSBLBSCYC" + - "SDDNSEWESGGPSHHNSIVNSJJMSKVKSLLESMMRSNENSOOMSRURSSSDSTTPSUUNSVLVSXXMSYYR" + - "SZWZTAAATCCATDCDTF\x00\x18TGGOTHHATJJKTKKLTLLSTMKMTNUNTOONTPMPTRURTTTOTV" + - "UVTWWNTZZAUAKRUGGAUK UMMIUN USSAUYRYUZZBVAATVCCTVDDRVEENVGGBVIIRVNNMVU" + - "UTWFLFWKAKWSSMXAAAXBBBXCCCXDDDXEEEXFFFXGGGXHHHXIIIXJJJXKKKXLLLXMMMXNNNXO" + - "OOXPPPXQQQXRRRXSSSXTTTXUUUXVVVXWWWXXXXXYYYXZZZYDMDYEEMYT\x00\x1bYUUGZAAF" + - "ZMMBZRARZWWEZZZZ\xff\xff\xff\xff" - -// altRegionISO3 holds a list of 3-letter region codes that cannot be -// mapped to 2-letter codes using the default algorithm. This is a short list. -const altRegionISO3 string = "SCGQUUSGSCOMPRKCYMSPMSRBATFMYTATN" - -// altRegionIDs holds a list of regionIDs the positions of which match those -// of the 3-letter ISO codes in altRegionISO3. -// Size: 22 bytes, 11 elements -var altRegionIDs = [11]uint16{ - 0x0057, 0x0070, 0x0088, 0x00a8, 0x00aa, 0x00ad, 0x00ea, 0x0105, - 0x0121, 0x015f, 0x00dc, -} - -// Size: 80 bytes, 20 elements -var regionOldMap = [20]FromTo{ - 0: {From: 0x44, To: 0xc4}, - 1: {From: 0x58, To: 0xa7}, - 2: {From: 0x5f, To: 0x60}, - 3: {From: 0x66, To: 0x3b}, - 4: {From: 0x79, To: 0x78}, - 5: {From: 0x93, To: 0x37}, - 6: {From: 0xa3, To: 0x133}, - 7: {From: 0xc1, To: 0x133}, - 8: {From: 0xd7, To: 0x13f}, - 9: {From: 0xdc, To: 0x2b}, - 10: {From: 0xef, To: 0x133}, - 11: {From: 0xf2, To: 0xe2}, - 12: {From: 0xfc, To: 0x70}, - 13: {From: 0x103, To: 0x164}, - 14: {From: 0x12a, To: 0x126}, - 15: {From: 0x132, To: 0x7b}, - 16: {From: 0x13a, To: 0x13e}, - 17: {From: 0x141, To: 0x133}, - 18: {From: 0x15d, To: 0x15e}, - 19: {From: 0x163, To: 0x4b}, -} - -// m49 maps regionIDs to UN.M49 codes. The first isoRegionOffset entries are -// codes indicating collections of regions. -// Size: 716 bytes, 358 elements -var m49 = [358]int16{ - // Entry 0 - 3F - 0, 1, 2, 3, 5, 9, 11, 13, - 14, 15, 17, 18, 19, 21, 29, 30, - 34, 35, 39, 53, 54, 57, 61, 142, - 143, 145, 150, 151, 154, 155, 202, 419, - 958, 0, 20, 784, 4, 28, 660, 8, - 51, 530, 24, 10, 32, 16, 40, 36, - 533, 248, 31, 70, 52, 50, 56, 854, - 100, 48, 108, 204, 652, 60, 96, 68, - // Entry 40 - 7F - 535, 76, 44, 64, 104, 74, 72, 112, - 84, 124, 166, 180, 140, 178, 756, 384, - 184, 152, 120, 156, 170, 0, 188, 891, - 296, 192, 132, 531, 162, 196, 203, 278, - 276, 0, 262, 208, 212, 214, 204, 12, - 0, 218, 233, 818, 732, 232, 724, 231, - 967, 0, 246, 242, 238, 583, 234, 0, - 250, 249, 266, 826, 308, 268, 254, 831, - // Entry 80 - BF - 288, 292, 304, 270, 324, 312, 226, 300, - 239, 320, 316, 624, 328, 344, 334, 340, - 191, 332, 348, 854, 0, 360, 372, 376, - 833, 356, 86, 368, 364, 352, 380, 832, - 388, 400, 392, 581, 404, 417, 116, 296, - 174, 659, 408, 410, 414, 136, 398, 418, - 422, 662, 438, 144, 430, 426, 440, 442, - 428, 434, 504, 492, 498, 499, 663, 450, - // Entry C0 - FF - 584, 581, 807, 466, 104, 496, 446, 580, - 474, 478, 500, 470, 480, 462, 454, 484, - 458, 508, 516, 540, 562, 574, 566, 548, - 558, 528, 578, 524, 10, 520, 536, 570, - 554, 512, 591, 0, 604, 258, 598, 608, - 586, 616, 666, 612, 630, 275, 620, 581, - 585, 600, 591, 634, 959, 960, 961, 962, - 963, 964, 965, 966, 967, 968, 969, 970, - // Entry 100 - 13F - 971, 972, 638, 716, 642, 688, 643, 646, - 682, 90, 690, 729, 752, 702, 654, 705, - 744, 703, 694, 674, 686, 706, 740, 728, - 678, 810, 222, 534, 760, 748, 0, 796, - 148, 260, 768, 764, 762, 772, 626, 795, - 788, 776, 626, 792, 780, 798, 158, 834, - 804, 800, 826, 581, 0, 840, 858, 860, - 336, 670, 704, 862, 92, 850, 704, 548, - // Entry 140 - 17F - 876, 581, 882, 973, 974, 975, 976, 977, - 978, 979, 980, 981, 982, 983, 984, 985, - 986, 987, 988, 989, 990, 991, 992, 993, - 994, 995, 996, 997, 998, 720, 887, 175, - 891, 710, 894, 180, 716, 999, -} - -// m49Index gives indexes into fromM49 based on the three most significant bits -// of a 10-bit UN.M49 code. To search an UN.M49 code in fromM49, search in -// -// fromM49[m49Index[msb39(code)]:m49Index[msb3(code)+1]] -// -// for an entry where the first 7 bits match the 7 lsb of the UN.M49 code. -// The region code is stored in the 9 lsb of the indexed value. -// Size: 18 bytes, 9 elements -var m49Index = [9]int16{ - 0, 59, 108, 143, 181, 220, 259, 291, - 333, -} - -// fromM49 contains entries to map UN.M49 codes to regions. See m49Index for details. -// Size: 666 bytes, 333 elements -var fromM49 = [333]uint16{ - // Entry 0 - 3F - 0x0201, 0x0402, 0x0603, 0x0824, 0x0a04, 0x1027, 0x1205, 0x142b, - 0x1606, 0x1867, 0x1a07, 0x1c08, 0x1e09, 0x202d, 0x220a, 0x240b, - 0x260c, 0x2822, 0x2a0d, 0x302a, 0x3825, 0x3a0e, 0x3c0f, 0x3e32, - 0x402c, 0x4410, 0x4611, 0x482f, 0x4e12, 0x502e, 0x5842, 0x6039, - 0x6435, 0x6628, 0x6834, 0x6a13, 0x6c14, 0x7036, 0x7215, 0x783d, - 0x7a16, 0x8043, 0x883f, 0x8c33, 0x9046, 0x9445, 0x9841, 0xa848, - 0xac9a, 0xb509, 0xb93c, 0xc03e, 0xc838, 0xd0c4, 0xd83a, 0xe047, - 0xe8a6, 0xf052, 0xf849, 0x085a, 0x10ad, 0x184c, 0x1c17, 0x1e18, - // Entry 40 - 7F - 0x20b3, 0x2219, 0x2920, 0x2c1a, 0x2e1b, 0x3051, 0x341c, 0x361d, - 0x3853, 0x3d2e, 0x445c, 0x4c4a, 0x5454, 0x5ca8, 0x5f5f, 0x644d, - 0x684b, 0x7050, 0x7856, 0x7e90, 0x8059, 0x885d, 0x941e, 0x965e, - 0x983b, 0xa063, 0xa864, 0xac65, 0xb469, 0xbd1a, 0xc486, 0xcc6f, - 0xce6f, 0xd06d, 0xd26a, 0xd476, 0xdc74, 0xde88, 0xe473, 0xec72, - 0xf031, 0xf279, 0xf478, 0xfc7e, 0x04e5, 0x0921, 0x0c62, 0x147a, - 0x187d, 0x1c83, 0x26ed, 0x2860, 0x2c5f, 0x3060, 0x4080, 0x4881, - 0x50a7, 0x5887, 0x6082, 0x687c, 0x7085, 0x788a, 0x8089, 0x8884, - // Entry 80 - BF - 0x908c, 0x9891, 0x9c8e, 0xa138, 0xa88f, 0xb08d, 0xb892, 0xc09d, - 0xc899, 0xd095, 0xd89c, 0xe09b, 0xe896, 0xf097, 0xf89e, 0x004f, - 0x08a0, 0x10a2, 0x1cae, 0x20a1, 0x28a4, 0x30aa, 0x34ab, 0x3cac, - 0x42a5, 0x44af, 0x461f, 0x4cb0, 0x54b5, 0x58b8, 0x5cb4, 0x64b9, - 0x6cb2, 0x70b6, 0x74b7, 0x7cc6, 0x84bf, 0x8cce, 0x94d0, 0x9ccd, - 0xa4c3, 0xaccb, 0xb4c8, 0xbcc9, 0xc0cc, 0xc8cf, 0xd8bb, 0xe0c5, - 0xe4bc, 0xe6bd, 0xe8ca, 0xf0ba, 0xf8d1, 0x00e1, 0x08d2, 0x10dd, - 0x18db, 0x20d9, 0x2429, 0x265b, 0x2a30, 0x2d1b, 0x2e40, 0x30de, - // Entry C0 - FF - 0x38d3, 0x493f, 0x54e0, 0x5cd8, 0x64d4, 0x6cd6, 0x74df, 0x7cd5, - 0x84da, 0x88c7, 0x8b33, 0x8e75, 0x90c0, 0x92f0, 0x94e8, 0x9ee2, - 0xace6, 0xb0f1, 0xb8e4, 0xc0e7, 0xc8eb, 0xd0e9, 0xd8ee, 0xe08b, - 0xe526, 0xecec, 0xf4f3, 0xfd02, 0x0504, 0x0706, 0x0d07, 0x183c, - 0x1d0e, 0x26a9, 0x2826, 0x2cb1, 0x2ebe, 0x34ea, 0x3d39, 0x4513, - 0x4d18, 0x5508, 0x5d14, 0x6105, 0x650a, 0x6d12, 0x7d0d, 0x7f11, - 0x813e, 0x830f, 0x8515, 0x8d61, 0x9964, 0xa15d, 0xa86e, 0xb117, - 0xb30b, 0xb86c, 0xc10b, 0xc916, 0xd110, 0xd91d, 0xe10c, 0xe84e, - // Entry 100 - 13F - 0xf11c, 0xf524, 0xf923, 0x0122, 0x0925, 0x1129, 0x192c, 0x2023, - 0x2928, 0x312b, 0x3727, 0x391f, 0x3d2d, 0x4131, 0x4930, 0x4ec2, - 0x5519, 0x646b, 0x747b, 0x7e7f, 0x809f, 0x8298, 0x852f, 0x9135, - 0xa53d, 0xac37, 0xb536, 0xb937, 0xbd3b, 0xd940, 0xe542, 0xed5e, - 0xef5e, 0xf657, 0xfd62, 0x7c20, 0x7ef4, 0x80f5, 0x82f6, 0x84f7, - 0x86f8, 0x88f9, 0x8afa, 0x8cfb, 0x8e70, 0x90fd, 0x92fe, 0x94ff, - 0x9700, 0x9901, 0x9b43, 0x9d44, 0x9f45, 0xa146, 0xa347, 0xa548, - 0xa749, 0xa94a, 0xab4b, 0xad4c, 0xaf4d, 0xb14e, 0xb34f, 0xb550, - // Entry 140 - 17F - 0xb751, 0xb952, 0xbb53, 0xbd54, 0xbf55, 0xc156, 0xc357, 0xc558, - 0xc759, 0xc95a, 0xcb5b, 0xcd5c, 0xcf65, -} - -// Size: 2014 bytes -var variantIndex = map[string]uint8{ - "1606nict": 0x0, - "1694acad": 0x1, - "1901": 0x2, - "1959acad": 0x3, - "1994": 0x61, - "1996": 0x4, - "abl1943": 0x5, - "akuapem": 0x6, - "alalc97": 0x63, - "aluku": 0x7, - "ao1990": 0x8, - "aranes": 0x9, - "arevela": 0xa, - "arevmda": 0xb, - "arkaika": 0xc, - "asante": 0xd, - "auvern": 0xe, - "baku1926": 0xf, - "balanka": 0x10, - "barla": 0x11, - "basiceng": 0x12, - "bauddha": 0x13, - "biscayan": 0x14, - "biske": 0x5c, - "bohoric": 0x15, - "boont": 0x16, - "bornholm": 0x17, - "cisaup": 0x18, - "colb1945": 0x19, - "cornu": 0x1a, - "creiss": 0x1b, - "dajnko": 0x1c, - "ekavsk": 0x1d, - "emodeng": 0x1e, - "fonipa": 0x64, - "fonkirsh": 0x65, - "fonnapa": 0x66, - "fonupa": 0x67, - "fonxsamp": 0x68, - "gascon": 0x1f, - "grclass": 0x20, - "grital": 0x21, - "grmistr": 0x22, - "hepburn": 0x23, - "heploc": 0x62, - "hognorsk": 0x24, - "hsistemo": 0x25, - "ijekavsk": 0x26, - "itihasa": 0x27, - "ivanchov": 0x28, - "jauer": 0x29, - "jyutping": 0x2a, - "kkcor": 0x2b, - "kociewie": 0x2c, - "kscor": 0x2d, - "laukika": 0x2e, - "lemosin": 0x2f, - "lengadoc": 0x30, - "lipaw": 0x5d, - "luna1918": 0x31, - "metelko": 0x32, - "monoton": 0x33, - "ndyuka": 0x34, - "nedis": 0x35, - "newfound": 0x36, - "nicard": 0x37, - "njiva": 0x5e, - "nulik": 0x38, - "osojs": 0x5f, - "oxendict": 0x39, - "pahawh2": 0x3a, - "pahawh3": 0x3b, - "pahawh4": 0x3c, - "pamaka": 0x3d, - "peano": 0x3e, - "petr1708": 0x3f, - "pinyin": 0x40, - "polyton": 0x41, - "provenc": 0x42, - "puter": 0x43, - "rigik": 0x44, - "rozaj": 0x45, - "rumgr": 0x46, - "scotland": 0x47, - "scouse": 0x48, - "simple": 0x69, - "solba": 0x60, - "sotav": 0x49, - "spanglis": 0x4a, - "surmiran": 0x4b, - "sursilv": 0x4c, - "sutsilv": 0x4d, - "tarask": 0x4e, - "tongyong": 0x4f, - "tunumiit": 0x50, - "uccor": 0x51, - "ucrcor": 0x52, - "ulster": 0x53, - "unifon": 0x54, - "vaidika": 0x55, - "valencia": 0x56, - "vallader": 0x57, - "vecdruka": 0x58, - "vivaraup": 0x59, - "wadegile": 0x5a, - "xsistemo": 0x5b, -} - -// variantNumSpecialized is the number of specialized variants in variants. -const variantNumSpecialized = 99 - -// nRegionGroups is the number of region groups. -const nRegionGroups = 33 - -type likelyLangRegion struct { - lang uint16 - region uint16 -} - -// likelyScript is a lookup table, indexed by scriptID, for the most likely -// languages and regions given a script. -// Size: 1040 bytes, 260 elements -var likelyScript = [260]likelyLangRegion{ - 1: {lang: 0x14e, region: 0x84}, - 3: {lang: 0x2a2, region: 0x106}, - 4: {lang: 0x1f, region: 0x99}, - 5: {lang: 0x3a, region: 0x6b}, - 7: {lang: 0x3b, region: 0x9c}, - 8: {lang: 0x1d7, region: 0x28}, - 9: {lang: 0x13, region: 0x9c}, - 10: {lang: 0x5b, region: 0x95}, - 11: {lang: 0x60, region: 0x52}, - 12: {lang: 0xb9, region: 0xb4}, - 13: {lang: 0x63, region: 0x95}, - 14: {lang: 0xa5, region: 0x35}, - 15: {lang: 0x3e9, region: 0x99}, - 17: {lang: 0x529, region: 0x12e}, - 18: {lang: 0x3b1, region: 0x99}, - 19: {lang: 0x15e, region: 0x78}, - 20: {lang: 0xc2, region: 0x95}, - 21: {lang: 0x9d, region: 0xe7}, - 22: {lang: 0xdb, region: 0x35}, - 23: {lang: 0xf3, region: 0x49}, - 24: {lang: 0x4f0, region: 0x12b}, - 25: {lang: 0xe7, region: 0x13e}, - 26: {lang: 0xe5, region: 0x135}, - 29: {lang: 0xf1, region: 0x6b}, - 31: {lang: 0x1a0, region: 0x5d}, - 32: {lang: 0x3e2, region: 0x106}, - 34: {lang: 0x1be, region: 0x99}, - 38: {lang: 0x15e, region: 0x78}, - 41: {lang: 0x133, region: 0x6b}, - 42: {lang: 0x431, region: 0x27}, - 44: {lang: 0x27, region: 0x6f}, - 46: {lang: 0x210, region: 0x7d}, - 47: {lang: 0xfe, region: 0x38}, - 49: {lang: 0x19b, region: 0x99}, - 50: {lang: 0x19e, region: 0x130}, - 51: {lang: 0x3e9, region: 0x99}, - 52: {lang: 0x136, region: 0x87}, - 53: {lang: 0x1a4, region: 0x99}, - 54: {lang: 0x39d, region: 0x99}, - 55: {lang: 0x529, region: 0x12e}, - 56: {lang: 0x254, region: 0xab}, - 57: {lang: 0x529, region: 0x53}, - 58: {lang: 0x1cb, region: 0xe7}, - 59: {lang: 0x529, region: 0x53}, - 60: {lang: 0x529, region: 0x12e}, - 61: {lang: 0x2fd, region: 0x9b}, - 62: {lang: 0x1bc, region: 0x97}, - 63: {lang: 0x200, region: 0xa2}, - 64: {lang: 0x1c5, region: 0x12b}, - 65: {lang: 0x1ca, region: 0xaf}, - 68: {lang: 0x1d5, region: 0x92}, - 70: {lang: 0x142, region: 0x9e}, - 71: {lang: 0x254, region: 0xab}, - 72: {lang: 0x20e, region: 0x95}, - 73: {lang: 0x200, region: 0xa2}, - 75: {lang: 0x135, region: 0xc4}, - 76: {lang: 0x200, region: 0xa2}, - 77: {lang: 0x3bb, region: 0xe8}, - 78: {lang: 0x24a, region: 0xa6}, - 79: {lang: 0x3fa, region: 0x99}, - 82: {lang: 0x251, region: 0x99}, - 83: {lang: 0x254, region: 0xab}, - 85: {lang: 0x88, region: 0x99}, - 86: {lang: 0x370, region: 0x123}, - 87: {lang: 0x2b8, region: 0xaf}, - 92: {lang: 0x29f, region: 0x99}, - 93: {lang: 0x2a8, region: 0x99}, - 94: {lang: 0x28f, region: 0x87}, - 95: {lang: 0x1a0, region: 0x87}, - 96: {lang: 0x2ac, region: 0x53}, - 98: {lang: 0x4f4, region: 0x12b}, - 99: {lang: 0x4f5, region: 0x12b}, - 100: {lang: 0x1be, region: 0x99}, - 102: {lang: 0x337, region: 0x9c}, - 103: {lang: 0x4f7, region: 0x53}, - 104: {lang: 0xa9, region: 0x53}, - 107: {lang: 0x2e8, region: 0x112}, - 108: {lang: 0x4f8, region: 0x10b}, - 109: {lang: 0x4f8, region: 0x10b}, - 110: {lang: 0x304, region: 0x99}, - 111: {lang: 0x31b, region: 0x99}, - 112: {lang: 0x30b, region: 0x53}, - 114: {lang: 0x31e, region: 0x35}, - 115: {lang: 0x30e, region: 0x99}, - 116: {lang: 0x414, region: 0xe8}, - 117: {lang: 0x331, region: 0xc4}, - 119: {lang: 0x4f9, region: 0x108}, - 120: {lang: 0x3b, region: 0xa1}, - 121: {lang: 0x353, region: 0xdb}, - 124: {lang: 0x2d0, region: 0x84}, - 125: {lang: 0x52a, region: 0x53}, - 126: {lang: 0x403, region: 0x96}, - 127: {lang: 0x3ee, region: 0x99}, - 128: {lang: 0x39b, region: 0xc5}, - 129: {lang: 0x395, region: 0x99}, - 130: {lang: 0x399, region: 0x135}, - 131: {lang: 0x429, region: 0x115}, - 133: {lang: 0x3b, region: 0x11c}, - 134: {lang: 0xfd, region: 0xc4}, - 137: {lang: 0x27d, region: 0x106}, - 138: {lang: 0x2c9, region: 0x53}, - 139: {lang: 0x39f, region: 0x9c}, - 140: {lang: 0x39f, region: 0x53}, - 142: {lang: 0x3ad, region: 0xb0}, - 144: {lang: 0x1c6, region: 0x53}, - 145: {lang: 0x4fd, region: 0x9c}, - 198: {lang: 0x3cb, region: 0x95}, - 201: {lang: 0x372, region: 0x10c}, - 202: {lang: 0x420, region: 0x97}, - 204: {lang: 0x4ff, region: 0x15e}, - 205: {lang: 0x3f0, region: 0x99}, - 206: {lang: 0x45, region: 0x135}, - 207: {lang: 0x139, region: 0x7b}, - 208: {lang: 0x3e9, region: 0x99}, - 210: {lang: 0x3e9, region: 0x99}, - 211: {lang: 0x3fa, region: 0x99}, - 212: {lang: 0x40c, region: 0xb3}, - 215: {lang: 0x433, region: 0x99}, - 216: {lang: 0xef, region: 0xc5}, - 217: {lang: 0x43e, region: 0x95}, - 218: {lang: 0x44d, region: 0x35}, - 219: {lang: 0x44e, region: 0x9b}, - 223: {lang: 0x45a, region: 0xe7}, - 224: {lang: 0x11a, region: 0x99}, - 225: {lang: 0x45e, region: 0x53}, - 226: {lang: 0x232, region: 0x53}, - 227: {lang: 0x450, region: 0x99}, - 228: {lang: 0x4a5, region: 0x53}, - 229: {lang: 0x9f, region: 0x13e}, - 230: {lang: 0x461, region: 0x99}, - 232: {lang: 0x528, region: 0xba}, - 233: {lang: 0x153, region: 0xe7}, - 234: {lang: 0x128, region: 0xcd}, - 235: {lang: 0x46b, region: 0x123}, - 236: {lang: 0xa9, region: 0x53}, - 237: {lang: 0x2ce, region: 0x99}, - 240: {lang: 0x4ad, region: 0x11c}, - 241: {lang: 0x4be, region: 0xb4}, - 244: {lang: 0x1ce, region: 0x99}, - 247: {lang: 0x3a9, region: 0x9c}, - 248: {lang: 0x22, region: 0x9b}, - 250: {lang: 0x1ea, region: 0x53}, - 251: {lang: 0xef, region: 0xc5}, -} - -type likelyScriptRegion struct { - region uint16 - script uint16 - flags uint8 -} - -// likelyLang is a lookup table, indexed by langID, for the most likely -// scripts and regions given incomplete information. If more entries exist for a -// given language, region and script are the index and size respectively -// of the list in likelyLangList. -// Size: 7980 bytes, 1330 elements -var likelyLang = [1330]likelyScriptRegion{ - 0: {region: 0x135, script: 0x5a, flags: 0x0}, - 1: {region: 0x6f, script: 0x5a, flags: 0x0}, - 2: {region: 0x165, script: 0x5a, flags: 0x0}, - 3: {region: 0x165, script: 0x5a, flags: 0x0}, - 4: {region: 0x165, script: 0x5a, flags: 0x0}, - 5: {region: 0x7d, script: 0x20, flags: 0x0}, - 6: {region: 0x165, script: 0x5a, flags: 0x0}, - 7: {region: 0x165, script: 0x20, flags: 0x0}, - 8: {region: 0x80, script: 0x5a, flags: 0x0}, - 9: {region: 0x165, script: 0x5a, flags: 0x0}, - 10: {region: 0x165, script: 0x5a, flags: 0x0}, - 11: {region: 0x165, script: 0x5a, flags: 0x0}, - 12: {region: 0x95, script: 0x5a, flags: 0x0}, - 13: {region: 0x131, script: 0x5a, flags: 0x0}, - 14: {region: 0x80, script: 0x5a, flags: 0x0}, - 15: {region: 0x165, script: 0x5a, flags: 0x0}, - 16: {region: 0x165, script: 0x5a, flags: 0x0}, - 17: {region: 0x106, script: 0x20, flags: 0x0}, - 18: {region: 0x165, script: 0x5a, flags: 0x0}, - 19: {region: 0x9c, script: 0x9, flags: 0x0}, - 20: {region: 0x128, script: 0x5, flags: 0x0}, - 21: {region: 0x165, script: 0x5a, flags: 0x0}, - 22: {region: 0x161, script: 0x5a, flags: 0x0}, - 23: {region: 0x165, script: 0x5a, flags: 0x0}, - 24: {region: 0x165, script: 0x5a, flags: 0x0}, - 25: {region: 0x165, script: 0x5a, flags: 0x0}, - 26: {region: 0x165, script: 0x5a, flags: 0x0}, - 27: {region: 0x165, script: 0x5a, flags: 0x0}, - 28: {region: 0x52, script: 0x5a, flags: 0x0}, - 29: {region: 0x165, script: 0x5a, flags: 0x0}, - 30: {region: 0x165, script: 0x5a, flags: 0x0}, - 31: {region: 0x99, script: 0x4, flags: 0x0}, - 32: {region: 0x165, script: 0x5a, flags: 0x0}, - 33: {region: 0x80, script: 0x5a, flags: 0x0}, - 34: {region: 0x9b, script: 0xf8, flags: 0x0}, - 35: {region: 0x165, script: 0x5a, flags: 0x0}, - 36: {region: 0x165, script: 0x5a, flags: 0x0}, - 37: {region: 0x14d, script: 0x5a, flags: 0x0}, - 38: {region: 0x106, script: 0x20, flags: 0x0}, - 39: {region: 0x6f, script: 0x2c, flags: 0x0}, - 40: {region: 0x165, script: 0x5a, flags: 0x0}, - 41: {region: 0x165, script: 0x5a, flags: 0x0}, - 42: {region: 0xd6, script: 0x5a, flags: 0x0}, - 43: {region: 0x165, script: 0x5a, flags: 0x0}, - 45: {region: 0x165, script: 0x5a, flags: 0x0}, - 46: {region: 0x165, script: 0x5a, flags: 0x0}, - 47: {region: 0x165, script: 0x5a, flags: 0x0}, - 48: {region: 0x165, script: 0x5a, flags: 0x0}, - 49: {region: 0x165, script: 0x5a, flags: 0x0}, - 50: {region: 0x165, script: 0x5a, flags: 0x0}, - 51: {region: 0x95, script: 0x5a, flags: 0x0}, - 52: {region: 0x165, script: 0x5, flags: 0x0}, - 53: {region: 0x122, script: 0x5, flags: 0x0}, - 54: {region: 0x165, script: 0x5a, flags: 0x0}, - 55: {region: 0x165, script: 0x5a, flags: 0x0}, - 56: {region: 0x165, script: 0x5a, flags: 0x0}, - 57: {region: 0x165, script: 0x5a, flags: 0x0}, - 58: {region: 0x6b, script: 0x5, flags: 0x0}, - 59: {region: 0x0, script: 0x3, flags: 0x1}, - 60: {region: 0x165, script: 0x5a, flags: 0x0}, - 61: {region: 0x51, script: 0x5a, flags: 0x0}, - 62: {region: 0x3f, script: 0x5a, flags: 0x0}, - 63: {region: 0x67, script: 0x5, flags: 0x0}, - 65: {region: 0xba, script: 0x5, flags: 0x0}, - 66: {region: 0x6b, script: 0x5, flags: 0x0}, - 67: {region: 0x99, script: 0xe, flags: 0x0}, - 68: {region: 0x12f, script: 0x5a, flags: 0x0}, - 69: {region: 0x135, script: 0xce, flags: 0x0}, - 70: {region: 0x165, script: 0x5a, flags: 0x0}, - 71: {region: 0x165, script: 0x5a, flags: 0x0}, - 72: {region: 0x6e, script: 0x5a, flags: 0x0}, - 73: {region: 0x165, script: 0x5a, flags: 0x0}, - 74: {region: 0x165, script: 0x5a, flags: 0x0}, - 75: {region: 0x49, script: 0x5a, flags: 0x0}, - 76: {region: 0x165, script: 0x5a, flags: 0x0}, - 77: {region: 0x106, script: 0x20, flags: 0x0}, - 78: {region: 0x165, script: 0x5, flags: 0x0}, - 79: {region: 0x165, script: 0x5a, flags: 0x0}, - 80: {region: 0x165, script: 0x5a, flags: 0x0}, - 81: {region: 0x165, script: 0x5a, flags: 0x0}, - 82: {region: 0x99, script: 0x22, flags: 0x0}, - 83: {region: 0x165, script: 0x5a, flags: 0x0}, - 84: {region: 0x165, script: 0x5a, flags: 0x0}, - 85: {region: 0x165, script: 0x5a, flags: 0x0}, - 86: {region: 0x3f, script: 0x5a, flags: 0x0}, - 87: {region: 0x165, script: 0x5a, flags: 0x0}, - 88: {region: 0x3, script: 0x5, flags: 0x1}, - 89: {region: 0x106, script: 0x20, flags: 0x0}, - 90: {region: 0xe8, script: 0x5, flags: 0x0}, - 91: {region: 0x95, script: 0x5a, flags: 0x0}, - 92: {region: 0xdb, script: 0x22, flags: 0x0}, - 93: {region: 0x2e, script: 0x5a, flags: 0x0}, - 94: {region: 0x52, script: 0x5a, flags: 0x0}, - 95: {region: 0x165, script: 0x5a, flags: 0x0}, - 96: {region: 0x52, script: 0xb, flags: 0x0}, - 97: {region: 0x165, script: 0x5a, flags: 0x0}, - 98: {region: 0x165, script: 0x5a, flags: 0x0}, - 99: {region: 0x95, script: 0x5a, flags: 0x0}, - 100: {region: 0x165, script: 0x5a, flags: 0x0}, - 101: {region: 0x52, script: 0x5a, flags: 0x0}, - 102: {region: 0x165, script: 0x5a, flags: 0x0}, - 103: {region: 0x165, script: 0x5a, flags: 0x0}, - 104: {region: 0x165, script: 0x5a, flags: 0x0}, - 105: {region: 0x165, script: 0x5a, flags: 0x0}, - 106: {region: 0x4f, script: 0x5a, flags: 0x0}, - 107: {region: 0x165, script: 0x5a, flags: 0x0}, - 108: {region: 0x165, script: 0x5a, flags: 0x0}, - 109: {region: 0x165, script: 0x5a, flags: 0x0}, - 110: {region: 0x165, script: 0x2c, flags: 0x0}, - 111: {region: 0x165, script: 0x5a, flags: 0x0}, - 112: {region: 0x165, script: 0x5a, flags: 0x0}, - 113: {region: 0x47, script: 0x20, flags: 0x0}, - 114: {region: 0x165, script: 0x5a, flags: 0x0}, - 115: {region: 0x165, script: 0x5a, flags: 0x0}, - 116: {region: 0x10b, script: 0x5, flags: 0x0}, - 117: {region: 0x162, script: 0x5a, flags: 0x0}, - 118: {region: 0x165, script: 0x5a, flags: 0x0}, - 119: {region: 0x95, script: 0x5a, flags: 0x0}, - 120: {region: 0x165, script: 0x5a, flags: 0x0}, - 121: {region: 0x12f, script: 0x5a, flags: 0x0}, - 122: {region: 0x52, script: 0x5a, flags: 0x0}, - 123: {region: 0x99, script: 0xe3, flags: 0x0}, - 124: {region: 0xe8, script: 0x5, flags: 0x0}, - 125: {region: 0x99, script: 0x22, flags: 0x0}, - 126: {region: 0x38, script: 0x20, flags: 0x0}, - 127: {region: 0x99, script: 0x22, flags: 0x0}, - 128: {region: 0xe8, script: 0x5, flags: 0x0}, - 129: {region: 0x12b, script: 0x34, flags: 0x0}, - 131: {region: 0x99, script: 0x22, flags: 0x0}, - 132: {region: 0x165, script: 0x5a, flags: 0x0}, - 133: {region: 0x99, script: 0x22, flags: 0x0}, - 134: {region: 0xe7, script: 0x5a, flags: 0x0}, - 135: {region: 0x165, script: 0x5a, flags: 0x0}, - 136: {region: 0x99, script: 0x22, flags: 0x0}, - 137: {region: 0x165, script: 0x5a, flags: 0x0}, - 138: {region: 0x13f, script: 0x5a, flags: 0x0}, - 139: {region: 0x165, script: 0x5a, flags: 0x0}, - 140: {region: 0x165, script: 0x5a, flags: 0x0}, - 141: {region: 0xe7, script: 0x5a, flags: 0x0}, - 142: {region: 0x165, script: 0x5a, flags: 0x0}, - 143: {region: 0xd6, script: 0x5a, flags: 0x0}, - 144: {region: 0x165, script: 0x5a, flags: 0x0}, - 145: {region: 0x165, script: 0x5a, flags: 0x0}, - 146: {region: 0x165, script: 0x5a, flags: 0x0}, - 147: {region: 0x165, script: 0x2c, flags: 0x0}, - 148: {region: 0x99, script: 0x22, flags: 0x0}, - 149: {region: 0x95, script: 0x5a, flags: 0x0}, - 150: {region: 0x165, script: 0x5a, flags: 0x0}, - 151: {region: 0x165, script: 0x5a, flags: 0x0}, - 152: {region: 0x114, script: 0x5a, flags: 0x0}, - 153: {region: 0x165, script: 0x5a, flags: 0x0}, - 154: {region: 0x165, script: 0x5a, flags: 0x0}, - 155: {region: 0x52, script: 0x5a, flags: 0x0}, - 156: {region: 0x165, script: 0x5a, flags: 0x0}, - 157: {region: 0xe7, script: 0x5a, flags: 0x0}, - 158: {region: 0x165, script: 0x5a, flags: 0x0}, - 159: {region: 0x13e, script: 0xe5, flags: 0x0}, - 160: {region: 0xc3, script: 0x5a, flags: 0x0}, - 161: {region: 0x165, script: 0x5a, flags: 0x0}, - 162: {region: 0x165, script: 0x5a, flags: 0x0}, - 163: {region: 0xc3, script: 0x5a, flags: 0x0}, - 164: {region: 0x165, script: 0x5a, flags: 0x0}, - 165: {region: 0x35, script: 0xe, flags: 0x0}, - 166: {region: 0x165, script: 0x5a, flags: 0x0}, - 167: {region: 0x165, script: 0x5a, flags: 0x0}, - 168: {region: 0x165, script: 0x5a, flags: 0x0}, - 169: {region: 0x53, script: 0xec, flags: 0x0}, - 170: {region: 0x165, script: 0x5a, flags: 0x0}, - 171: {region: 0x165, script: 0x5a, flags: 0x0}, - 172: {region: 0x165, script: 0x5a, flags: 0x0}, - 173: {region: 0x99, script: 0xe, flags: 0x0}, - 174: {region: 0x165, script: 0x5a, flags: 0x0}, - 175: {region: 0x9c, script: 0x5, flags: 0x0}, - 176: {region: 0x165, script: 0x5a, flags: 0x0}, - 177: {region: 0x4f, script: 0x5a, flags: 0x0}, - 178: {region: 0x78, script: 0x5a, flags: 0x0}, - 179: {region: 0x99, script: 0x22, flags: 0x0}, - 180: {region: 0xe8, script: 0x5, flags: 0x0}, - 181: {region: 0x99, script: 0x22, flags: 0x0}, - 182: {region: 0x165, script: 0x5a, flags: 0x0}, - 183: {region: 0x33, script: 0x5a, flags: 0x0}, - 184: {region: 0x165, script: 0x5a, flags: 0x0}, - 185: {region: 0xb4, script: 0xc, flags: 0x0}, - 186: {region: 0x52, script: 0x5a, flags: 0x0}, - 187: {region: 0x165, script: 0x2c, flags: 0x0}, - 188: {region: 0xe7, script: 0x5a, flags: 0x0}, - 189: {region: 0x165, script: 0x5a, flags: 0x0}, - 190: {region: 0xe8, script: 0x22, flags: 0x0}, - 191: {region: 0x106, script: 0x20, flags: 0x0}, - 192: {region: 0x15f, script: 0x5a, flags: 0x0}, - 193: {region: 0x165, script: 0x5a, flags: 0x0}, - 194: {region: 0x95, script: 0x5a, flags: 0x0}, - 195: {region: 0x165, script: 0x5a, flags: 0x0}, - 196: {region: 0x52, script: 0x5a, flags: 0x0}, - 197: {region: 0x165, script: 0x5a, flags: 0x0}, - 198: {region: 0x165, script: 0x5a, flags: 0x0}, - 199: {region: 0x165, script: 0x5a, flags: 0x0}, - 200: {region: 0x86, script: 0x5a, flags: 0x0}, - 201: {region: 0x165, script: 0x5a, flags: 0x0}, - 202: {region: 0x165, script: 0x5a, flags: 0x0}, - 203: {region: 0x165, script: 0x5a, flags: 0x0}, - 204: {region: 0x165, script: 0x5a, flags: 0x0}, - 205: {region: 0x6d, script: 0x2c, flags: 0x0}, - 206: {region: 0x165, script: 0x5a, flags: 0x0}, - 207: {region: 0x165, script: 0x5a, flags: 0x0}, - 208: {region: 0x52, script: 0x5a, flags: 0x0}, - 209: {region: 0x165, script: 0x5a, flags: 0x0}, - 210: {region: 0x165, script: 0x5a, flags: 0x0}, - 211: {region: 0xc3, script: 0x5a, flags: 0x0}, - 212: {region: 0x165, script: 0x5a, flags: 0x0}, - 213: {region: 0x165, script: 0x5a, flags: 0x0}, - 214: {region: 0x165, script: 0x5a, flags: 0x0}, - 215: {region: 0x6e, script: 0x5a, flags: 0x0}, - 216: {region: 0x165, script: 0x5a, flags: 0x0}, - 217: {region: 0x165, script: 0x5a, flags: 0x0}, - 218: {region: 0xd6, script: 0x5a, flags: 0x0}, - 219: {region: 0x35, script: 0x16, flags: 0x0}, - 220: {region: 0x106, script: 0x20, flags: 0x0}, - 221: {region: 0xe7, script: 0x5a, flags: 0x0}, - 222: {region: 0x165, script: 0x5a, flags: 0x0}, - 223: {region: 0x131, script: 0x5a, flags: 0x0}, - 224: {region: 0x8a, script: 0x5a, flags: 0x0}, - 225: {region: 0x75, script: 0x5a, flags: 0x0}, - 226: {region: 0x106, script: 0x20, flags: 0x0}, - 227: {region: 0x135, script: 0x5a, flags: 0x0}, - 228: {region: 0x49, script: 0x5a, flags: 0x0}, - 229: {region: 0x135, script: 0x1a, flags: 0x0}, - 230: {region: 0xa6, script: 0x5, flags: 0x0}, - 231: {region: 0x13e, script: 0x19, flags: 0x0}, - 232: {region: 0x165, script: 0x5a, flags: 0x0}, - 233: {region: 0x9b, script: 0x5, flags: 0x0}, - 234: {region: 0x165, script: 0x5a, flags: 0x0}, - 235: {region: 0x165, script: 0x5a, flags: 0x0}, - 236: {region: 0x165, script: 0x5a, flags: 0x0}, - 237: {region: 0x165, script: 0x5a, flags: 0x0}, - 238: {region: 0x165, script: 0x5a, flags: 0x0}, - 239: {region: 0xc5, script: 0xd8, flags: 0x0}, - 240: {region: 0x78, script: 0x5a, flags: 0x0}, - 241: {region: 0x6b, script: 0x1d, flags: 0x0}, - 242: {region: 0xe7, script: 0x5a, flags: 0x0}, - 243: {region: 0x49, script: 0x17, flags: 0x0}, - 244: {region: 0x130, script: 0x20, flags: 0x0}, - 245: {region: 0x49, script: 0x17, flags: 0x0}, - 246: {region: 0x49, script: 0x17, flags: 0x0}, - 247: {region: 0x49, script: 0x17, flags: 0x0}, - 248: {region: 0x49, script: 0x17, flags: 0x0}, - 249: {region: 0x10a, script: 0x5a, flags: 0x0}, - 250: {region: 0x5e, script: 0x5a, flags: 0x0}, - 251: {region: 0xe9, script: 0x5a, flags: 0x0}, - 252: {region: 0x49, script: 0x17, flags: 0x0}, - 253: {region: 0xc4, script: 0x86, flags: 0x0}, - 254: {region: 0x8, script: 0x2, flags: 0x1}, - 255: {region: 0x106, script: 0x20, flags: 0x0}, - 256: {region: 0x7b, script: 0x5a, flags: 0x0}, - 257: {region: 0x63, script: 0x5a, flags: 0x0}, - 258: {region: 0x165, script: 0x5a, flags: 0x0}, - 259: {region: 0x165, script: 0x5a, flags: 0x0}, - 260: {region: 0x165, script: 0x5a, flags: 0x0}, - 261: {region: 0x165, script: 0x5a, flags: 0x0}, - 262: {region: 0x135, script: 0x5a, flags: 0x0}, - 263: {region: 0x106, script: 0x20, flags: 0x0}, - 264: {region: 0xa4, script: 0x5a, flags: 0x0}, - 265: {region: 0x165, script: 0x5a, flags: 0x0}, - 266: {region: 0x165, script: 0x5a, flags: 0x0}, - 267: {region: 0x99, script: 0x5, flags: 0x0}, - 268: {region: 0x165, script: 0x5a, flags: 0x0}, - 269: {region: 0x60, script: 0x5a, flags: 0x0}, - 270: {region: 0x165, script: 0x5a, flags: 0x0}, - 271: {region: 0x49, script: 0x5a, flags: 0x0}, - 272: {region: 0x165, script: 0x5a, flags: 0x0}, - 273: {region: 0x165, script: 0x5a, flags: 0x0}, - 274: {region: 0x165, script: 0x5a, flags: 0x0}, - 275: {region: 0x165, script: 0x5, flags: 0x0}, - 276: {region: 0x49, script: 0x5a, flags: 0x0}, - 277: {region: 0x165, script: 0x5a, flags: 0x0}, - 278: {region: 0x165, script: 0x5a, flags: 0x0}, - 279: {region: 0xd4, script: 0x5a, flags: 0x0}, - 280: {region: 0x4f, script: 0x5a, flags: 0x0}, - 281: {region: 0x165, script: 0x5a, flags: 0x0}, - 282: {region: 0x99, script: 0x5, flags: 0x0}, - 283: {region: 0x165, script: 0x5a, flags: 0x0}, - 284: {region: 0x165, script: 0x5a, flags: 0x0}, - 285: {region: 0x165, script: 0x5a, flags: 0x0}, - 286: {region: 0x165, script: 0x2c, flags: 0x0}, - 287: {region: 0x60, script: 0x5a, flags: 0x0}, - 288: {region: 0xc3, script: 0x5a, flags: 0x0}, - 289: {region: 0xd0, script: 0x5a, flags: 0x0}, - 290: {region: 0x165, script: 0x5a, flags: 0x0}, - 291: {region: 0xdb, script: 0x22, flags: 0x0}, - 292: {region: 0x52, script: 0x5a, flags: 0x0}, - 293: {region: 0x165, script: 0x5a, flags: 0x0}, - 294: {region: 0x165, script: 0x5a, flags: 0x0}, - 295: {region: 0x165, script: 0x5a, flags: 0x0}, - 296: {region: 0xcd, script: 0xea, flags: 0x0}, - 297: {region: 0x165, script: 0x5a, flags: 0x0}, - 298: {region: 0x165, script: 0x5a, flags: 0x0}, - 299: {region: 0x114, script: 0x5a, flags: 0x0}, - 300: {region: 0x37, script: 0x5a, flags: 0x0}, - 301: {region: 0x43, script: 0xec, flags: 0x0}, - 302: {region: 0x165, script: 0x5a, flags: 0x0}, - 303: {region: 0xa4, script: 0x5a, flags: 0x0}, - 304: {region: 0x80, script: 0x5a, flags: 0x0}, - 305: {region: 0xd6, script: 0x5a, flags: 0x0}, - 306: {region: 0x9e, script: 0x5a, flags: 0x0}, - 307: {region: 0x6b, script: 0x29, flags: 0x0}, - 308: {region: 0x165, script: 0x5a, flags: 0x0}, - 309: {region: 0xc4, script: 0x4b, flags: 0x0}, - 310: {region: 0x87, script: 0x34, flags: 0x0}, - 311: {region: 0x165, script: 0x5a, flags: 0x0}, - 312: {region: 0x165, script: 0x5a, flags: 0x0}, - 313: {region: 0xa, script: 0x2, flags: 0x1}, - 314: {region: 0x165, script: 0x5a, flags: 0x0}, - 315: {region: 0x165, script: 0x5a, flags: 0x0}, - 316: {region: 0x1, script: 0x5a, flags: 0x0}, - 317: {region: 0x165, script: 0x5a, flags: 0x0}, - 318: {region: 0x6e, script: 0x5a, flags: 0x0}, - 319: {region: 0x135, script: 0x5a, flags: 0x0}, - 320: {region: 0x6a, script: 0x5a, flags: 0x0}, - 321: {region: 0x165, script: 0x5a, flags: 0x0}, - 322: {region: 0x9e, script: 0x46, flags: 0x0}, - 323: {region: 0x165, script: 0x5a, flags: 0x0}, - 324: {region: 0x165, script: 0x5a, flags: 0x0}, - 325: {region: 0x6e, script: 0x5a, flags: 0x0}, - 326: {region: 0x52, script: 0x5a, flags: 0x0}, - 327: {region: 0x6e, script: 0x5a, flags: 0x0}, - 328: {region: 0x9c, script: 0x5, flags: 0x0}, - 329: {region: 0x165, script: 0x5a, flags: 0x0}, - 330: {region: 0x165, script: 0x5a, flags: 0x0}, - 331: {region: 0x165, script: 0x5a, flags: 0x0}, - 332: {region: 0x165, script: 0x5a, flags: 0x0}, - 333: {region: 0x86, script: 0x5a, flags: 0x0}, - 334: {region: 0xc, script: 0x2, flags: 0x1}, - 335: {region: 0x165, script: 0x5a, flags: 0x0}, - 336: {region: 0xc3, script: 0x5a, flags: 0x0}, - 337: {region: 0x72, script: 0x5a, flags: 0x0}, - 338: {region: 0x10b, script: 0x5, flags: 0x0}, - 339: {region: 0xe7, script: 0x5a, flags: 0x0}, - 340: {region: 0x10c, script: 0x5a, flags: 0x0}, - 341: {region: 0x73, script: 0x5a, flags: 0x0}, - 342: {region: 0x165, script: 0x5a, flags: 0x0}, - 343: {region: 0x165, script: 0x5a, flags: 0x0}, - 344: {region: 0x76, script: 0x5a, flags: 0x0}, - 345: {region: 0x165, script: 0x5a, flags: 0x0}, - 346: {region: 0x3b, script: 0x5a, flags: 0x0}, - 347: {region: 0x165, script: 0x5a, flags: 0x0}, - 348: {region: 0x165, script: 0x5a, flags: 0x0}, - 349: {region: 0x165, script: 0x5a, flags: 0x0}, - 350: {region: 0x78, script: 0x5a, flags: 0x0}, - 351: {region: 0x135, script: 0x5a, flags: 0x0}, - 352: {region: 0x78, script: 0x5a, flags: 0x0}, - 353: {region: 0x60, script: 0x5a, flags: 0x0}, - 354: {region: 0x60, script: 0x5a, flags: 0x0}, - 355: {region: 0x52, script: 0x5, flags: 0x0}, - 356: {region: 0x140, script: 0x5a, flags: 0x0}, - 357: {region: 0x165, script: 0x5a, flags: 0x0}, - 358: {region: 0x84, script: 0x5a, flags: 0x0}, - 359: {region: 0x165, script: 0x5a, flags: 0x0}, - 360: {region: 0xd4, script: 0x5a, flags: 0x0}, - 361: {region: 0x9e, script: 0x5a, flags: 0x0}, - 362: {region: 0xd6, script: 0x5a, flags: 0x0}, - 363: {region: 0x165, script: 0x5a, flags: 0x0}, - 364: {region: 0x10b, script: 0x5a, flags: 0x0}, - 365: {region: 0xd9, script: 0x5a, flags: 0x0}, - 366: {region: 0x96, script: 0x5a, flags: 0x0}, - 367: {region: 0x80, script: 0x5a, flags: 0x0}, - 368: {region: 0x165, script: 0x5a, flags: 0x0}, - 369: {region: 0xbc, script: 0x5a, flags: 0x0}, - 370: {region: 0x165, script: 0x5a, flags: 0x0}, - 371: {region: 0x165, script: 0x5a, flags: 0x0}, - 372: {region: 0x165, script: 0x5a, flags: 0x0}, - 373: {region: 0x53, script: 0x3b, flags: 0x0}, - 374: {region: 0x165, script: 0x5a, flags: 0x0}, - 375: {region: 0x95, script: 0x5a, flags: 0x0}, - 376: {region: 0x165, script: 0x5a, flags: 0x0}, - 377: {region: 0x165, script: 0x5a, flags: 0x0}, - 378: {region: 0x99, script: 0x22, flags: 0x0}, - 379: {region: 0x165, script: 0x5a, flags: 0x0}, - 380: {region: 0x9c, script: 0x5, flags: 0x0}, - 381: {region: 0x7e, script: 0x5a, flags: 0x0}, - 382: {region: 0x7b, script: 0x5a, flags: 0x0}, - 383: {region: 0x165, script: 0x5a, flags: 0x0}, - 384: {region: 0x165, script: 0x5a, flags: 0x0}, - 385: {region: 0x165, script: 0x5a, flags: 0x0}, - 386: {region: 0x165, script: 0x5a, flags: 0x0}, - 387: {region: 0x165, script: 0x5a, flags: 0x0}, - 388: {region: 0x165, script: 0x5a, flags: 0x0}, - 389: {region: 0x6f, script: 0x2c, flags: 0x0}, - 390: {region: 0x165, script: 0x5a, flags: 0x0}, - 391: {region: 0xdb, script: 0x22, flags: 0x0}, - 392: {region: 0x165, script: 0x5a, flags: 0x0}, - 393: {region: 0xa7, script: 0x5a, flags: 0x0}, - 394: {region: 0x165, script: 0x5a, flags: 0x0}, - 395: {region: 0xe8, script: 0x5, flags: 0x0}, - 396: {region: 0x165, script: 0x5a, flags: 0x0}, - 397: {region: 0xe8, script: 0x5, flags: 0x0}, - 398: {region: 0x165, script: 0x5a, flags: 0x0}, - 399: {region: 0x165, script: 0x5a, flags: 0x0}, - 400: {region: 0x6e, script: 0x5a, flags: 0x0}, - 401: {region: 0x9c, script: 0x5, flags: 0x0}, - 402: {region: 0x165, script: 0x5a, flags: 0x0}, - 403: {region: 0x165, script: 0x2c, flags: 0x0}, - 404: {region: 0xf1, script: 0x5a, flags: 0x0}, - 405: {region: 0x165, script: 0x5a, flags: 0x0}, - 406: {region: 0x165, script: 0x5a, flags: 0x0}, - 407: {region: 0x165, script: 0x5a, flags: 0x0}, - 408: {region: 0x165, script: 0x2c, flags: 0x0}, - 409: {region: 0x165, script: 0x5a, flags: 0x0}, - 410: {region: 0x99, script: 0x22, flags: 0x0}, - 411: {region: 0x99, script: 0xe6, flags: 0x0}, - 412: {region: 0x95, script: 0x5a, flags: 0x0}, - 413: {region: 0xd9, script: 0x5a, flags: 0x0}, - 414: {region: 0x130, script: 0x32, flags: 0x0}, - 415: {region: 0x165, script: 0x5a, flags: 0x0}, - 416: {region: 0xe, script: 0x2, flags: 0x1}, - 417: {region: 0x99, script: 0xe, flags: 0x0}, - 418: {region: 0x165, script: 0x5a, flags: 0x0}, - 419: {region: 0x4e, script: 0x5a, flags: 0x0}, - 420: {region: 0x99, script: 0x35, flags: 0x0}, - 421: {region: 0x41, script: 0x5a, flags: 0x0}, - 422: {region: 0x54, script: 0x5a, flags: 0x0}, - 423: {region: 0x165, script: 0x5a, flags: 0x0}, - 424: {region: 0x80, script: 0x5a, flags: 0x0}, - 425: {region: 0x165, script: 0x5a, flags: 0x0}, - 426: {region: 0x165, script: 0x5a, flags: 0x0}, - 427: {region: 0xa4, script: 0x5a, flags: 0x0}, - 428: {region: 0x98, script: 0x5a, flags: 0x0}, - 429: {region: 0x165, script: 0x5a, flags: 0x0}, - 430: {region: 0xdb, script: 0x22, flags: 0x0}, - 431: {region: 0x165, script: 0x5a, flags: 0x0}, - 432: {region: 0x165, script: 0x5, flags: 0x0}, - 433: {region: 0x49, script: 0x5a, flags: 0x0}, - 434: {region: 0x165, script: 0x5, flags: 0x0}, - 435: {region: 0x165, script: 0x5a, flags: 0x0}, - 436: {region: 0x10, script: 0x3, flags: 0x1}, - 437: {region: 0x165, script: 0x5a, flags: 0x0}, - 438: {region: 0x53, script: 0x3b, flags: 0x0}, - 439: {region: 0x165, script: 0x5a, flags: 0x0}, - 440: {region: 0x135, script: 0x5a, flags: 0x0}, - 441: {region: 0x24, script: 0x5, flags: 0x0}, - 442: {region: 0x165, script: 0x5a, flags: 0x0}, - 443: {region: 0x165, script: 0x2c, flags: 0x0}, - 444: {region: 0x97, script: 0x3e, flags: 0x0}, - 445: {region: 0x165, script: 0x5a, flags: 0x0}, - 446: {region: 0x99, script: 0x22, flags: 0x0}, - 447: {region: 0x165, script: 0x5a, flags: 0x0}, - 448: {region: 0x73, script: 0x5a, flags: 0x0}, - 449: {region: 0x165, script: 0x5a, flags: 0x0}, - 450: {region: 0x165, script: 0x5a, flags: 0x0}, - 451: {region: 0xe7, script: 0x5a, flags: 0x0}, - 452: {region: 0x165, script: 0x5a, flags: 0x0}, - 453: {region: 0x12b, script: 0x40, flags: 0x0}, - 454: {region: 0x53, script: 0x90, flags: 0x0}, - 455: {region: 0x165, script: 0x5a, flags: 0x0}, - 456: {region: 0xe8, script: 0x5, flags: 0x0}, - 457: {region: 0x99, script: 0x22, flags: 0x0}, - 458: {region: 0xaf, script: 0x41, flags: 0x0}, - 459: {region: 0xe7, script: 0x5a, flags: 0x0}, - 460: {region: 0xe8, script: 0x5, flags: 0x0}, - 461: {region: 0xe6, script: 0x5a, flags: 0x0}, - 462: {region: 0x99, script: 0x22, flags: 0x0}, - 463: {region: 0x99, script: 0x22, flags: 0x0}, - 464: {region: 0x165, script: 0x5a, flags: 0x0}, - 465: {region: 0x90, script: 0x5a, flags: 0x0}, - 466: {region: 0x60, script: 0x5a, flags: 0x0}, - 467: {region: 0x53, script: 0x3b, flags: 0x0}, - 468: {region: 0x91, script: 0x5a, flags: 0x0}, - 469: {region: 0x92, script: 0x5a, flags: 0x0}, - 470: {region: 0x165, script: 0x5a, flags: 0x0}, - 471: {region: 0x28, script: 0x8, flags: 0x0}, - 472: {region: 0xd2, script: 0x5a, flags: 0x0}, - 473: {region: 0x78, script: 0x5a, flags: 0x0}, - 474: {region: 0x165, script: 0x5a, flags: 0x0}, - 475: {region: 0x165, script: 0x5a, flags: 0x0}, - 476: {region: 0xd0, script: 0x5a, flags: 0x0}, - 477: {region: 0xd6, script: 0x5a, flags: 0x0}, - 478: {region: 0x165, script: 0x5a, flags: 0x0}, - 479: {region: 0x165, script: 0x5a, flags: 0x0}, - 480: {region: 0x165, script: 0x5a, flags: 0x0}, - 481: {region: 0x95, script: 0x5a, flags: 0x0}, - 482: {region: 0x165, script: 0x5a, flags: 0x0}, - 483: {region: 0x165, script: 0x5a, flags: 0x0}, - 484: {region: 0x165, script: 0x5a, flags: 0x0}, - 486: {region: 0x122, script: 0x5a, flags: 0x0}, - 487: {region: 0xd6, script: 0x5a, flags: 0x0}, - 488: {region: 0x165, script: 0x5a, flags: 0x0}, - 489: {region: 0x165, script: 0x5a, flags: 0x0}, - 490: {region: 0x53, script: 0xfa, flags: 0x0}, - 491: {region: 0x165, script: 0x5a, flags: 0x0}, - 492: {region: 0x135, script: 0x5a, flags: 0x0}, - 493: {region: 0x165, script: 0x5a, flags: 0x0}, - 494: {region: 0x49, script: 0x5a, flags: 0x0}, - 495: {region: 0x165, script: 0x5a, flags: 0x0}, - 496: {region: 0x165, script: 0x5a, flags: 0x0}, - 497: {region: 0xe7, script: 0x5a, flags: 0x0}, - 498: {region: 0x165, script: 0x5a, flags: 0x0}, - 499: {region: 0x95, script: 0x5a, flags: 0x0}, - 500: {region: 0x106, script: 0x20, flags: 0x0}, - 501: {region: 0x1, script: 0x5a, flags: 0x0}, - 502: {region: 0x165, script: 0x5a, flags: 0x0}, - 503: {region: 0x165, script: 0x5a, flags: 0x0}, - 504: {region: 0x9d, script: 0x5a, flags: 0x0}, - 505: {region: 0x9e, script: 0x5a, flags: 0x0}, - 506: {region: 0x49, script: 0x17, flags: 0x0}, - 507: {region: 0x97, script: 0x3e, flags: 0x0}, - 508: {region: 0x165, script: 0x5a, flags: 0x0}, - 509: {region: 0x165, script: 0x5a, flags: 0x0}, - 510: {region: 0x106, script: 0x5a, flags: 0x0}, - 511: {region: 0x165, script: 0x5a, flags: 0x0}, - 512: {region: 0xa2, script: 0x49, flags: 0x0}, - 513: {region: 0x165, script: 0x5a, flags: 0x0}, - 514: {region: 0xa0, script: 0x5a, flags: 0x0}, - 515: {region: 0x1, script: 0x5a, flags: 0x0}, - 516: {region: 0x165, script: 0x5a, flags: 0x0}, - 517: {region: 0x165, script: 0x5a, flags: 0x0}, - 518: {region: 0x165, script: 0x5a, flags: 0x0}, - 519: {region: 0x52, script: 0x5a, flags: 0x0}, - 520: {region: 0x130, script: 0x3e, flags: 0x0}, - 521: {region: 0x165, script: 0x5a, flags: 0x0}, - 522: {region: 0x12f, script: 0x5a, flags: 0x0}, - 523: {region: 0xdb, script: 0x22, flags: 0x0}, - 524: {region: 0x165, script: 0x5a, flags: 0x0}, - 525: {region: 0x63, script: 0x5a, flags: 0x0}, - 526: {region: 0x95, script: 0x5a, flags: 0x0}, - 527: {region: 0x95, script: 0x5a, flags: 0x0}, - 528: {region: 0x7d, script: 0x2e, flags: 0x0}, - 529: {region: 0x137, script: 0x20, flags: 0x0}, - 530: {region: 0x67, script: 0x5a, flags: 0x0}, - 531: {region: 0xc4, script: 0x5a, flags: 0x0}, - 532: {region: 0x165, script: 0x5a, flags: 0x0}, - 533: {region: 0x165, script: 0x5a, flags: 0x0}, - 534: {region: 0xd6, script: 0x5a, flags: 0x0}, - 535: {region: 0xa4, script: 0x5a, flags: 0x0}, - 536: {region: 0xc3, script: 0x5a, flags: 0x0}, - 537: {region: 0x106, script: 0x20, flags: 0x0}, - 538: {region: 0x165, script: 0x5a, flags: 0x0}, - 539: {region: 0x165, script: 0x5a, flags: 0x0}, - 540: {region: 0x165, script: 0x5a, flags: 0x0}, - 541: {region: 0x165, script: 0x5a, flags: 0x0}, - 542: {region: 0xd4, script: 0x5, flags: 0x0}, - 543: {region: 0xd6, script: 0x5a, flags: 0x0}, - 544: {region: 0x164, script: 0x5a, flags: 0x0}, - 545: {region: 0x165, script: 0x5a, flags: 0x0}, - 546: {region: 0x165, script: 0x5a, flags: 0x0}, - 547: {region: 0x12f, script: 0x5a, flags: 0x0}, - 548: {region: 0x122, script: 0x5, flags: 0x0}, - 549: {region: 0x165, script: 0x5a, flags: 0x0}, - 550: {region: 0x123, script: 0xeb, flags: 0x0}, - 551: {region: 0x5a, script: 0x5a, flags: 0x0}, - 552: {region: 0x52, script: 0x5a, flags: 0x0}, - 553: {region: 0x165, script: 0x5a, flags: 0x0}, - 554: {region: 0x4f, script: 0x5a, flags: 0x0}, - 555: {region: 0x99, script: 0x22, flags: 0x0}, - 556: {region: 0x99, script: 0x22, flags: 0x0}, - 557: {region: 0x4b, script: 0x5a, flags: 0x0}, - 558: {region: 0x95, script: 0x5a, flags: 0x0}, - 559: {region: 0x165, script: 0x5a, flags: 0x0}, - 560: {region: 0x41, script: 0x5a, flags: 0x0}, - 561: {region: 0x99, script: 0x5a, flags: 0x0}, - 562: {region: 0x53, script: 0xe2, flags: 0x0}, - 563: {region: 0x99, script: 0x22, flags: 0x0}, - 564: {region: 0xc3, script: 0x5a, flags: 0x0}, - 565: {region: 0x165, script: 0x5a, flags: 0x0}, - 566: {region: 0x99, script: 0x75, flags: 0x0}, - 567: {region: 0xe8, script: 0x5, flags: 0x0}, - 568: {region: 0x165, script: 0x5a, flags: 0x0}, - 569: {region: 0xa4, script: 0x5a, flags: 0x0}, - 570: {region: 0x165, script: 0x5a, flags: 0x0}, - 571: {region: 0x12b, script: 0x5a, flags: 0x0}, - 572: {region: 0x165, script: 0x5a, flags: 0x0}, - 573: {region: 0xd2, script: 0x5a, flags: 0x0}, - 574: {region: 0x165, script: 0x5a, flags: 0x0}, - 575: {region: 0xaf, script: 0x57, flags: 0x0}, - 576: {region: 0x165, script: 0x5a, flags: 0x0}, - 577: {region: 0x165, script: 0x5a, flags: 0x0}, - 578: {region: 0x13, script: 0x6, flags: 0x1}, - 579: {region: 0x165, script: 0x5a, flags: 0x0}, - 580: {region: 0x52, script: 0x5a, flags: 0x0}, - 581: {region: 0x82, script: 0x5a, flags: 0x0}, - 582: {region: 0xa4, script: 0x5a, flags: 0x0}, - 583: {region: 0x165, script: 0x5a, flags: 0x0}, - 584: {region: 0x165, script: 0x5a, flags: 0x0}, - 585: {region: 0x165, script: 0x5a, flags: 0x0}, - 586: {region: 0xa6, script: 0x4e, flags: 0x0}, - 587: {region: 0x2a, script: 0x5a, flags: 0x0}, - 588: {region: 0x165, script: 0x5a, flags: 0x0}, - 589: {region: 0x165, script: 0x5a, flags: 0x0}, - 590: {region: 0x165, script: 0x5a, flags: 0x0}, - 591: {region: 0x165, script: 0x5a, flags: 0x0}, - 592: {region: 0x165, script: 0x5a, flags: 0x0}, - 593: {region: 0x99, script: 0x52, flags: 0x0}, - 594: {region: 0x8b, script: 0x5a, flags: 0x0}, - 595: {region: 0x165, script: 0x5a, flags: 0x0}, - 596: {region: 0xab, script: 0x53, flags: 0x0}, - 597: {region: 0x106, script: 0x20, flags: 0x0}, - 598: {region: 0x99, script: 0x22, flags: 0x0}, - 599: {region: 0x165, script: 0x5a, flags: 0x0}, - 600: {region: 0x75, script: 0x5a, flags: 0x0}, - 601: {region: 0x165, script: 0x5a, flags: 0x0}, - 602: {region: 0xb4, script: 0x5a, flags: 0x0}, - 603: {region: 0x165, script: 0x5a, flags: 0x0}, - 604: {region: 0x165, script: 0x5a, flags: 0x0}, - 605: {region: 0x165, script: 0x5a, flags: 0x0}, - 606: {region: 0x165, script: 0x5a, flags: 0x0}, - 607: {region: 0x165, script: 0x5a, flags: 0x0}, - 608: {region: 0x165, script: 0x5a, flags: 0x0}, - 609: {region: 0x165, script: 0x5a, flags: 0x0}, - 610: {region: 0x165, script: 0x2c, flags: 0x0}, - 611: {region: 0x165, script: 0x5a, flags: 0x0}, - 612: {region: 0x106, script: 0x20, flags: 0x0}, - 613: {region: 0x112, script: 0x5a, flags: 0x0}, - 614: {region: 0xe7, script: 0x5a, flags: 0x0}, - 615: {region: 0x106, script: 0x5a, flags: 0x0}, - 616: {region: 0x165, script: 0x5a, flags: 0x0}, - 617: {region: 0x99, script: 0x22, flags: 0x0}, - 618: {region: 0x99, script: 0x5, flags: 0x0}, - 619: {region: 0x12f, script: 0x5a, flags: 0x0}, - 620: {region: 0x165, script: 0x5a, flags: 0x0}, - 621: {region: 0x52, script: 0x5a, flags: 0x0}, - 622: {region: 0x60, script: 0x5a, flags: 0x0}, - 623: {region: 0x165, script: 0x5a, flags: 0x0}, - 624: {region: 0x165, script: 0x5a, flags: 0x0}, - 625: {region: 0x165, script: 0x2c, flags: 0x0}, - 626: {region: 0x165, script: 0x5a, flags: 0x0}, - 627: {region: 0x165, script: 0x5a, flags: 0x0}, - 628: {region: 0x19, script: 0x3, flags: 0x1}, - 629: {region: 0x165, script: 0x5a, flags: 0x0}, - 630: {region: 0x165, script: 0x5a, flags: 0x0}, - 631: {region: 0x165, script: 0x5a, flags: 0x0}, - 632: {region: 0x165, script: 0x5a, flags: 0x0}, - 633: {region: 0x106, script: 0x20, flags: 0x0}, - 634: {region: 0x165, script: 0x5a, flags: 0x0}, - 635: {region: 0x165, script: 0x5a, flags: 0x0}, - 636: {region: 0x165, script: 0x5a, flags: 0x0}, - 637: {region: 0x106, script: 0x20, flags: 0x0}, - 638: {region: 0x165, script: 0x5a, flags: 0x0}, - 639: {region: 0x95, script: 0x5a, flags: 0x0}, - 640: {region: 0xe8, script: 0x5, flags: 0x0}, - 641: {region: 0x7b, script: 0x5a, flags: 0x0}, - 642: {region: 0x165, script: 0x5a, flags: 0x0}, - 643: {region: 0x165, script: 0x5a, flags: 0x0}, - 644: {region: 0x165, script: 0x5a, flags: 0x0}, - 645: {region: 0x165, script: 0x2c, flags: 0x0}, - 646: {region: 0x123, script: 0xeb, flags: 0x0}, - 647: {region: 0xe8, script: 0x5, flags: 0x0}, - 648: {region: 0x165, script: 0x5a, flags: 0x0}, - 649: {region: 0x165, script: 0x5a, flags: 0x0}, - 650: {region: 0x1c, script: 0x5, flags: 0x1}, - 651: {region: 0x165, script: 0x5a, flags: 0x0}, - 652: {region: 0x165, script: 0x5a, flags: 0x0}, - 653: {region: 0x165, script: 0x5a, flags: 0x0}, - 654: {region: 0x138, script: 0x5a, flags: 0x0}, - 655: {region: 0x87, script: 0x5e, flags: 0x0}, - 656: {region: 0x97, script: 0x3e, flags: 0x0}, - 657: {region: 0x12f, script: 0x5a, flags: 0x0}, - 658: {region: 0xe8, script: 0x5, flags: 0x0}, - 659: {region: 0x131, script: 0x5a, flags: 0x0}, - 660: {region: 0x165, script: 0x5a, flags: 0x0}, - 661: {region: 0xb7, script: 0x5a, flags: 0x0}, - 662: {region: 0x106, script: 0x20, flags: 0x0}, - 663: {region: 0x165, script: 0x5a, flags: 0x0}, - 664: {region: 0x95, script: 0x5a, flags: 0x0}, - 665: {region: 0x165, script: 0x5a, flags: 0x0}, - 666: {region: 0x53, script: 0xeb, flags: 0x0}, - 667: {region: 0x165, script: 0x5a, flags: 0x0}, - 668: {region: 0x165, script: 0x5a, flags: 0x0}, - 669: {region: 0x165, script: 0x5a, flags: 0x0}, - 670: {region: 0x165, script: 0x5a, flags: 0x0}, - 671: {region: 0x99, script: 0x5c, flags: 0x0}, - 672: {region: 0x165, script: 0x5a, flags: 0x0}, - 673: {region: 0x165, script: 0x5a, flags: 0x0}, - 674: {region: 0x106, script: 0x20, flags: 0x0}, - 675: {region: 0x131, script: 0x5a, flags: 0x0}, - 676: {region: 0x165, script: 0x5a, flags: 0x0}, - 677: {region: 0xd9, script: 0x5a, flags: 0x0}, - 678: {region: 0x165, script: 0x5a, flags: 0x0}, - 679: {region: 0x165, script: 0x5a, flags: 0x0}, - 680: {region: 0x21, script: 0x2, flags: 0x1}, - 681: {region: 0x165, script: 0x5a, flags: 0x0}, - 682: {region: 0x165, script: 0x5a, flags: 0x0}, - 683: {region: 0x9e, script: 0x5a, flags: 0x0}, - 684: {region: 0x53, script: 0x60, flags: 0x0}, - 685: {region: 0x95, script: 0x5a, flags: 0x0}, - 686: {region: 0x9c, script: 0x5, flags: 0x0}, - 687: {region: 0x135, script: 0x5a, flags: 0x0}, - 688: {region: 0x165, script: 0x5a, flags: 0x0}, - 689: {region: 0x165, script: 0x5a, flags: 0x0}, - 690: {region: 0x99, script: 0xe6, flags: 0x0}, - 691: {region: 0x9e, script: 0x5a, flags: 0x0}, - 692: {region: 0x165, script: 0x5a, flags: 0x0}, - 693: {region: 0x4b, script: 0x5a, flags: 0x0}, - 694: {region: 0x165, script: 0x5a, flags: 0x0}, - 695: {region: 0x165, script: 0x5a, flags: 0x0}, - 696: {region: 0xaf, script: 0x57, flags: 0x0}, - 697: {region: 0x165, script: 0x5a, flags: 0x0}, - 698: {region: 0x165, script: 0x5a, flags: 0x0}, - 699: {region: 0x4b, script: 0x5a, flags: 0x0}, - 700: {region: 0x165, script: 0x5a, flags: 0x0}, - 701: {region: 0x165, script: 0x5a, flags: 0x0}, - 702: {region: 0x162, script: 0x5a, flags: 0x0}, - 703: {region: 0x9c, script: 0x5, flags: 0x0}, - 704: {region: 0xb6, script: 0x5a, flags: 0x0}, - 705: {region: 0xb8, script: 0x5a, flags: 0x0}, - 706: {region: 0x4b, script: 0x5a, flags: 0x0}, - 707: {region: 0x4b, script: 0x5a, flags: 0x0}, - 708: {region: 0xa4, script: 0x5a, flags: 0x0}, - 709: {region: 0xa4, script: 0x5a, flags: 0x0}, - 710: {region: 0x9c, script: 0x5, flags: 0x0}, - 711: {region: 0xb8, script: 0x5a, flags: 0x0}, - 712: {region: 0x123, script: 0xeb, flags: 0x0}, - 713: {region: 0x53, script: 0x3b, flags: 0x0}, - 714: {region: 0x12b, script: 0x5a, flags: 0x0}, - 715: {region: 0x95, script: 0x5a, flags: 0x0}, - 716: {region: 0x52, script: 0x5a, flags: 0x0}, - 717: {region: 0x99, script: 0x22, flags: 0x0}, - 718: {region: 0x99, script: 0x22, flags: 0x0}, - 719: {region: 0x95, script: 0x5a, flags: 0x0}, - 720: {region: 0x23, script: 0x3, flags: 0x1}, - 721: {region: 0xa4, script: 0x5a, flags: 0x0}, - 722: {region: 0x165, script: 0x5a, flags: 0x0}, - 723: {region: 0xcf, script: 0x5a, flags: 0x0}, - 724: {region: 0x165, script: 0x5a, flags: 0x0}, - 725: {region: 0x165, script: 0x5a, flags: 0x0}, - 726: {region: 0x165, script: 0x5a, flags: 0x0}, - 727: {region: 0x165, script: 0x5a, flags: 0x0}, - 728: {region: 0x165, script: 0x5a, flags: 0x0}, - 729: {region: 0x165, script: 0x5a, flags: 0x0}, - 730: {region: 0x165, script: 0x5a, flags: 0x0}, - 731: {region: 0x165, script: 0x5a, flags: 0x0}, - 732: {region: 0x165, script: 0x5a, flags: 0x0}, - 733: {region: 0x165, script: 0x5a, flags: 0x0}, - 734: {region: 0x165, script: 0x5a, flags: 0x0}, - 735: {region: 0x165, script: 0x5, flags: 0x0}, - 736: {region: 0x106, script: 0x20, flags: 0x0}, - 737: {region: 0xe7, script: 0x5a, flags: 0x0}, - 738: {region: 0x165, script: 0x5a, flags: 0x0}, - 739: {region: 0x95, script: 0x5a, flags: 0x0}, - 740: {region: 0x165, script: 0x2c, flags: 0x0}, - 741: {region: 0x165, script: 0x5a, flags: 0x0}, - 742: {region: 0x165, script: 0x5a, flags: 0x0}, - 743: {region: 0x165, script: 0x5a, flags: 0x0}, - 744: {region: 0x112, script: 0x5a, flags: 0x0}, - 745: {region: 0xa4, script: 0x5a, flags: 0x0}, - 746: {region: 0x165, script: 0x5a, flags: 0x0}, - 747: {region: 0x165, script: 0x5a, flags: 0x0}, - 748: {region: 0x123, script: 0x5, flags: 0x0}, - 749: {region: 0xcc, script: 0x5a, flags: 0x0}, - 750: {region: 0x165, script: 0x5a, flags: 0x0}, - 751: {region: 0x165, script: 0x5a, flags: 0x0}, - 752: {region: 0x165, script: 0x5a, flags: 0x0}, - 753: {region: 0xbf, script: 0x5a, flags: 0x0}, - 754: {region: 0xd1, script: 0x5a, flags: 0x0}, - 755: {region: 0x165, script: 0x5a, flags: 0x0}, - 756: {region: 0x52, script: 0x5a, flags: 0x0}, - 757: {region: 0xdb, script: 0x22, flags: 0x0}, - 758: {region: 0x12f, script: 0x5a, flags: 0x0}, - 759: {region: 0xc0, script: 0x5a, flags: 0x0}, - 760: {region: 0x165, script: 0x5a, flags: 0x0}, - 761: {region: 0x165, script: 0x5a, flags: 0x0}, - 762: {region: 0xe0, script: 0x5a, flags: 0x0}, - 763: {region: 0x165, script: 0x5a, flags: 0x0}, - 764: {region: 0x95, script: 0x5a, flags: 0x0}, - 765: {region: 0x9b, script: 0x3d, flags: 0x0}, - 766: {region: 0x165, script: 0x5a, flags: 0x0}, - 767: {region: 0xc2, script: 0x20, flags: 0x0}, - 768: {region: 0x165, script: 0x5, flags: 0x0}, - 769: {region: 0x165, script: 0x5a, flags: 0x0}, - 770: {region: 0x165, script: 0x5a, flags: 0x0}, - 771: {region: 0x165, script: 0x5a, flags: 0x0}, - 772: {region: 0x99, script: 0x6e, flags: 0x0}, - 773: {region: 0x165, script: 0x5a, flags: 0x0}, - 774: {region: 0x165, script: 0x5a, flags: 0x0}, - 775: {region: 0x10b, script: 0x5a, flags: 0x0}, - 776: {region: 0x165, script: 0x5a, flags: 0x0}, - 777: {region: 0x165, script: 0x5a, flags: 0x0}, - 778: {region: 0x165, script: 0x5a, flags: 0x0}, - 779: {region: 0x26, script: 0x3, flags: 0x1}, - 780: {region: 0x165, script: 0x5a, flags: 0x0}, - 781: {region: 0x165, script: 0x5a, flags: 0x0}, - 782: {region: 0x99, script: 0xe, flags: 0x0}, - 783: {region: 0xc4, script: 0x75, flags: 0x0}, - 785: {region: 0x165, script: 0x5a, flags: 0x0}, - 786: {region: 0x49, script: 0x5a, flags: 0x0}, - 787: {region: 0x49, script: 0x5a, flags: 0x0}, - 788: {region: 0x37, script: 0x5a, flags: 0x0}, - 789: {region: 0x165, script: 0x5a, flags: 0x0}, - 790: {region: 0x165, script: 0x5a, flags: 0x0}, - 791: {region: 0x165, script: 0x5a, flags: 0x0}, - 792: {region: 0x165, script: 0x5a, flags: 0x0}, - 793: {region: 0x165, script: 0x5a, flags: 0x0}, - 794: {region: 0x165, script: 0x5a, flags: 0x0}, - 795: {region: 0x99, script: 0x22, flags: 0x0}, - 796: {region: 0xdb, script: 0x22, flags: 0x0}, - 797: {region: 0x106, script: 0x20, flags: 0x0}, - 798: {region: 0x35, script: 0x72, flags: 0x0}, - 799: {region: 0x29, script: 0x3, flags: 0x1}, - 800: {region: 0xcb, script: 0x5a, flags: 0x0}, - 801: {region: 0x165, script: 0x5a, flags: 0x0}, - 802: {region: 0x165, script: 0x5a, flags: 0x0}, - 803: {region: 0x165, script: 0x5a, flags: 0x0}, - 804: {region: 0x99, script: 0x22, flags: 0x0}, - 805: {region: 0x52, script: 0x5a, flags: 0x0}, - 807: {region: 0x165, script: 0x5a, flags: 0x0}, - 808: {region: 0x135, script: 0x5a, flags: 0x0}, - 809: {region: 0x165, script: 0x5a, flags: 0x0}, - 810: {region: 0x165, script: 0x5a, flags: 0x0}, - 811: {region: 0xe8, script: 0x5, flags: 0x0}, - 812: {region: 0xc3, script: 0x5a, flags: 0x0}, - 813: {region: 0x99, script: 0x22, flags: 0x0}, - 814: {region: 0x95, script: 0x5a, flags: 0x0}, - 815: {region: 0x164, script: 0x5a, flags: 0x0}, - 816: {region: 0x165, script: 0x5a, flags: 0x0}, - 817: {region: 0xc4, script: 0x75, flags: 0x0}, - 818: {region: 0x165, script: 0x5a, flags: 0x0}, - 819: {region: 0x165, script: 0x2c, flags: 0x0}, - 820: {region: 0x106, script: 0x20, flags: 0x0}, - 821: {region: 0x165, script: 0x5a, flags: 0x0}, - 822: {region: 0x131, script: 0x5a, flags: 0x0}, - 823: {region: 0x9c, script: 0x66, flags: 0x0}, - 824: {region: 0x165, script: 0x5a, flags: 0x0}, - 825: {region: 0x165, script: 0x5a, flags: 0x0}, - 826: {region: 0x9c, script: 0x5, flags: 0x0}, - 827: {region: 0x165, script: 0x5a, flags: 0x0}, - 828: {region: 0x165, script: 0x5a, flags: 0x0}, - 829: {region: 0x165, script: 0x5a, flags: 0x0}, - 830: {region: 0xdd, script: 0x5a, flags: 0x0}, - 831: {region: 0x165, script: 0x5a, flags: 0x0}, - 832: {region: 0x165, script: 0x5a, flags: 0x0}, - 834: {region: 0x165, script: 0x5a, flags: 0x0}, - 835: {region: 0x53, script: 0x3b, flags: 0x0}, - 836: {region: 0x9e, script: 0x5a, flags: 0x0}, - 837: {region: 0xd2, script: 0x5a, flags: 0x0}, - 838: {region: 0x165, script: 0x5a, flags: 0x0}, - 839: {region: 0xda, script: 0x5a, flags: 0x0}, - 840: {region: 0x165, script: 0x5a, flags: 0x0}, - 841: {region: 0x165, script: 0x5a, flags: 0x0}, - 842: {region: 0x165, script: 0x5a, flags: 0x0}, - 843: {region: 0xcf, script: 0x5a, flags: 0x0}, - 844: {region: 0x165, script: 0x5a, flags: 0x0}, - 845: {region: 0x165, script: 0x5a, flags: 0x0}, - 846: {region: 0x164, script: 0x5a, flags: 0x0}, - 847: {region: 0xd1, script: 0x5a, flags: 0x0}, - 848: {region: 0x60, script: 0x5a, flags: 0x0}, - 849: {region: 0xdb, script: 0x22, flags: 0x0}, - 850: {region: 0x165, script: 0x5a, flags: 0x0}, - 851: {region: 0xdb, script: 0x22, flags: 0x0}, - 852: {region: 0x165, script: 0x5a, flags: 0x0}, - 853: {region: 0x165, script: 0x5a, flags: 0x0}, - 854: {region: 0xd2, script: 0x5a, flags: 0x0}, - 855: {region: 0x165, script: 0x5a, flags: 0x0}, - 856: {region: 0x165, script: 0x5a, flags: 0x0}, - 857: {region: 0xd1, script: 0x5a, flags: 0x0}, - 858: {region: 0x165, script: 0x5a, flags: 0x0}, - 859: {region: 0xcf, script: 0x5a, flags: 0x0}, - 860: {region: 0xcf, script: 0x5a, flags: 0x0}, - 861: {region: 0x165, script: 0x5a, flags: 0x0}, - 862: {region: 0x165, script: 0x5a, flags: 0x0}, - 863: {region: 0x95, script: 0x5a, flags: 0x0}, - 864: {region: 0x165, script: 0x5a, flags: 0x0}, - 865: {region: 0xdf, script: 0x5a, flags: 0x0}, - 866: {region: 0x165, script: 0x5a, flags: 0x0}, - 867: {region: 0x165, script: 0x5a, flags: 0x0}, - 868: {region: 0x99, script: 0x5a, flags: 0x0}, - 869: {region: 0x165, script: 0x5a, flags: 0x0}, - 870: {region: 0x165, script: 0x5a, flags: 0x0}, - 871: {region: 0xd9, script: 0x5a, flags: 0x0}, - 872: {region: 0x52, script: 0x5a, flags: 0x0}, - 873: {region: 0x165, script: 0x5a, flags: 0x0}, - 874: {region: 0xda, script: 0x5a, flags: 0x0}, - 875: {region: 0x165, script: 0x5a, flags: 0x0}, - 876: {region: 0x52, script: 0x5a, flags: 0x0}, - 877: {region: 0x165, script: 0x5a, flags: 0x0}, - 878: {region: 0x165, script: 0x5a, flags: 0x0}, - 879: {region: 0xda, script: 0x5a, flags: 0x0}, - 880: {region: 0x123, script: 0x56, flags: 0x0}, - 881: {region: 0x99, script: 0x22, flags: 0x0}, - 882: {region: 0x10c, script: 0xc9, flags: 0x0}, - 883: {region: 0x165, script: 0x5a, flags: 0x0}, - 884: {region: 0x165, script: 0x5a, flags: 0x0}, - 885: {region: 0x84, script: 0x7c, flags: 0x0}, - 886: {region: 0x161, script: 0x5a, flags: 0x0}, - 887: {region: 0x165, script: 0x5a, flags: 0x0}, - 888: {region: 0x49, script: 0x17, flags: 0x0}, - 889: {region: 0x165, script: 0x5a, flags: 0x0}, - 890: {region: 0x161, script: 0x5a, flags: 0x0}, - 891: {region: 0x165, script: 0x5a, flags: 0x0}, - 892: {region: 0x165, script: 0x5a, flags: 0x0}, - 893: {region: 0x165, script: 0x5a, flags: 0x0}, - 894: {region: 0x165, script: 0x5a, flags: 0x0}, - 895: {region: 0x165, script: 0x5a, flags: 0x0}, - 896: {region: 0x117, script: 0x5a, flags: 0x0}, - 897: {region: 0x165, script: 0x5a, flags: 0x0}, - 898: {region: 0x165, script: 0x5a, flags: 0x0}, - 899: {region: 0x135, script: 0x5a, flags: 0x0}, - 900: {region: 0x165, script: 0x5a, flags: 0x0}, - 901: {region: 0x53, script: 0x5a, flags: 0x0}, - 902: {region: 0x165, script: 0x5a, flags: 0x0}, - 903: {region: 0xce, script: 0x5a, flags: 0x0}, - 904: {region: 0x12f, script: 0x5a, flags: 0x0}, - 905: {region: 0x131, script: 0x5a, flags: 0x0}, - 906: {region: 0x80, script: 0x5a, flags: 0x0}, - 907: {region: 0x78, script: 0x5a, flags: 0x0}, - 908: {region: 0x165, script: 0x5a, flags: 0x0}, - 910: {region: 0x165, script: 0x5a, flags: 0x0}, - 911: {region: 0x165, script: 0x5a, flags: 0x0}, - 912: {region: 0x6f, script: 0x5a, flags: 0x0}, - 913: {region: 0x165, script: 0x5a, flags: 0x0}, - 914: {region: 0x165, script: 0x5a, flags: 0x0}, - 915: {region: 0x165, script: 0x5a, flags: 0x0}, - 916: {region: 0x165, script: 0x5a, flags: 0x0}, - 917: {region: 0x99, script: 0x81, flags: 0x0}, - 918: {region: 0x165, script: 0x5a, flags: 0x0}, - 919: {region: 0x165, script: 0x5, flags: 0x0}, - 920: {region: 0x7d, script: 0x20, flags: 0x0}, - 921: {region: 0x135, script: 0x82, flags: 0x0}, - 922: {region: 0x165, script: 0x5, flags: 0x0}, - 923: {region: 0xc5, script: 0x80, flags: 0x0}, - 924: {region: 0x165, script: 0x5a, flags: 0x0}, - 925: {region: 0x2c, script: 0x3, flags: 0x1}, - 926: {region: 0xe7, script: 0x5a, flags: 0x0}, - 927: {region: 0x2f, script: 0x2, flags: 0x1}, - 928: {region: 0xe7, script: 0x5a, flags: 0x0}, - 929: {region: 0x30, script: 0x5a, flags: 0x0}, - 930: {region: 0xf0, script: 0x5a, flags: 0x0}, - 931: {region: 0x165, script: 0x5a, flags: 0x0}, - 932: {region: 0x78, script: 0x5a, flags: 0x0}, - 933: {region: 0xd6, script: 0x5a, flags: 0x0}, - 934: {region: 0x135, script: 0x5a, flags: 0x0}, - 935: {region: 0x49, script: 0x5a, flags: 0x0}, - 936: {region: 0x165, script: 0x5a, flags: 0x0}, - 937: {region: 0x9c, script: 0xf7, flags: 0x0}, - 938: {region: 0x165, script: 0x5a, flags: 0x0}, - 939: {region: 0x60, script: 0x5a, flags: 0x0}, - 940: {region: 0x165, script: 0x5, flags: 0x0}, - 941: {region: 0xb0, script: 0x8e, flags: 0x0}, - 943: {region: 0x165, script: 0x5a, flags: 0x0}, - 944: {region: 0x165, script: 0x5a, flags: 0x0}, - 945: {region: 0x99, script: 0x12, flags: 0x0}, - 946: {region: 0xa4, script: 0x5a, flags: 0x0}, - 947: {region: 0xe9, script: 0x5a, flags: 0x0}, - 948: {region: 0x165, script: 0x5a, flags: 0x0}, - 949: {region: 0x9e, script: 0x5a, flags: 0x0}, - 950: {region: 0x165, script: 0x5a, flags: 0x0}, - 951: {region: 0x165, script: 0x5a, flags: 0x0}, - 952: {region: 0x87, script: 0x34, flags: 0x0}, - 953: {region: 0x75, script: 0x5a, flags: 0x0}, - 954: {region: 0x165, script: 0x5a, flags: 0x0}, - 955: {region: 0xe8, script: 0x4d, flags: 0x0}, - 956: {region: 0x9c, script: 0x5, flags: 0x0}, - 957: {region: 0x1, script: 0x5a, flags: 0x0}, - 958: {region: 0x24, script: 0x5, flags: 0x0}, - 959: {region: 0x165, script: 0x5a, flags: 0x0}, - 960: {region: 0x41, script: 0x5a, flags: 0x0}, - 961: {region: 0x165, script: 0x5a, flags: 0x0}, - 962: {region: 0x7a, script: 0x5a, flags: 0x0}, - 963: {region: 0x165, script: 0x5a, flags: 0x0}, - 964: {region: 0xe4, script: 0x5a, flags: 0x0}, - 965: {region: 0x89, script: 0x5a, flags: 0x0}, - 966: {region: 0x69, script: 0x5a, flags: 0x0}, - 967: {region: 0x165, script: 0x5a, flags: 0x0}, - 968: {region: 0x99, script: 0x22, flags: 0x0}, - 969: {region: 0x165, script: 0x5a, flags: 0x0}, - 970: {region: 0x102, script: 0x5a, flags: 0x0}, - 971: {region: 0x95, script: 0x5a, flags: 0x0}, - 972: {region: 0x165, script: 0x5a, flags: 0x0}, - 973: {region: 0x165, script: 0x5a, flags: 0x0}, - 974: {region: 0x9e, script: 0x5a, flags: 0x0}, - 975: {region: 0x165, script: 0x5, flags: 0x0}, - 976: {region: 0x99, script: 0x5a, flags: 0x0}, - 977: {region: 0x31, script: 0x2, flags: 0x1}, - 978: {region: 0xdb, script: 0x22, flags: 0x0}, - 979: {region: 0x35, script: 0xe, flags: 0x0}, - 980: {region: 0x4e, script: 0x5a, flags: 0x0}, - 981: {region: 0x72, script: 0x5a, flags: 0x0}, - 982: {region: 0x4e, script: 0x5a, flags: 0x0}, - 983: {region: 0x9c, script: 0x5, flags: 0x0}, - 984: {region: 0x10c, script: 0x5a, flags: 0x0}, - 985: {region: 0x3a, script: 0x5a, flags: 0x0}, - 986: {region: 0x165, script: 0x5a, flags: 0x0}, - 987: {region: 0xd1, script: 0x5a, flags: 0x0}, - 988: {region: 0x104, script: 0x5a, flags: 0x0}, - 989: {region: 0x95, script: 0x5a, flags: 0x0}, - 990: {region: 0x12f, script: 0x5a, flags: 0x0}, - 991: {region: 0x165, script: 0x5a, flags: 0x0}, - 992: {region: 0x165, script: 0x5a, flags: 0x0}, - 993: {region: 0x73, script: 0x5a, flags: 0x0}, - 994: {region: 0x106, script: 0x20, flags: 0x0}, - 995: {region: 0x130, script: 0x20, flags: 0x0}, - 996: {region: 0x109, script: 0x5a, flags: 0x0}, - 997: {region: 0x107, script: 0x5a, flags: 0x0}, - 998: {region: 0x12f, script: 0x5a, flags: 0x0}, - 999: {region: 0x165, script: 0x5a, flags: 0x0}, - 1000: {region: 0xa2, script: 0x4c, flags: 0x0}, - 1001: {region: 0x99, script: 0x22, flags: 0x0}, - 1002: {region: 0x80, script: 0x5a, flags: 0x0}, - 1003: {region: 0x106, script: 0x20, flags: 0x0}, - 1004: {region: 0xa4, script: 0x5a, flags: 0x0}, - 1005: {region: 0x95, script: 0x5a, flags: 0x0}, - 1006: {region: 0x99, script: 0x5a, flags: 0x0}, - 1007: {region: 0x114, script: 0x5a, flags: 0x0}, - 1008: {region: 0x99, script: 0xcd, flags: 0x0}, - 1009: {region: 0x165, script: 0x5a, flags: 0x0}, - 1010: {region: 0x165, script: 0x5a, flags: 0x0}, - 1011: {region: 0x12f, script: 0x5a, flags: 0x0}, - 1012: {region: 0x9e, script: 0x5a, flags: 0x0}, - 1013: {region: 0x99, script: 0x22, flags: 0x0}, - 1014: {region: 0x165, script: 0x5, flags: 0x0}, - 1015: {region: 0x9e, script: 0x5a, flags: 0x0}, - 1016: {region: 0x7b, script: 0x5a, flags: 0x0}, - 1017: {region: 0x49, script: 0x5a, flags: 0x0}, - 1018: {region: 0x33, script: 0x4, flags: 0x1}, - 1019: {region: 0x9e, script: 0x5a, flags: 0x0}, - 1020: {region: 0x9c, script: 0x5, flags: 0x0}, - 1021: {region: 0xda, script: 0x5a, flags: 0x0}, - 1022: {region: 0x4f, script: 0x5a, flags: 0x0}, - 1023: {region: 0xd1, script: 0x5a, flags: 0x0}, - 1024: {region: 0xcf, script: 0x5a, flags: 0x0}, - 1025: {region: 0xc3, script: 0x5a, flags: 0x0}, - 1026: {region: 0x4c, script: 0x5a, flags: 0x0}, - 1027: {region: 0x96, script: 0x7e, flags: 0x0}, - 1028: {region: 0xb6, script: 0x5a, flags: 0x0}, - 1029: {region: 0x165, script: 0x2c, flags: 0x0}, - 1030: {region: 0x165, script: 0x5a, flags: 0x0}, - 1032: {region: 0xba, script: 0xe8, flags: 0x0}, - 1033: {region: 0x165, script: 0x5a, flags: 0x0}, - 1034: {region: 0xc4, script: 0x75, flags: 0x0}, - 1035: {region: 0x165, script: 0x5, flags: 0x0}, - 1036: {region: 0xb3, script: 0xd4, flags: 0x0}, - 1037: {region: 0x6f, script: 0x5a, flags: 0x0}, - 1038: {region: 0x165, script: 0x5a, flags: 0x0}, - 1039: {region: 0x165, script: 0x5a, flags: 0x0}, - 1040: {region: 0x165, script: 0x5a, flags: 0x0}, - 1041: {region: 0x165, script: 0x5a, flags: 0x0}, - 1042: {region: 0x111, script: 0x5a, flags: 0x0}, - 1043: {region: 0x165, script: 0x5a, flags: 0x0}, - 1044: {region: 0xe8, script: 0x5, flags: 0x0}, - 1045: {region: 0x165, script: 0x5a, flags: 0x0}, - 1046: {region: 0x10f, script: 0x5a, flags: 0x0}, - 1047: {region: 0x165, script: 0x5a, flags: 0x0}, - 1048: {region: 0xe9, script: 0x5a, flags: 0x0}, - 1049: {region: 0x165, script: 0x5a, flags: 0x0}, - 1050: {region: 0x95, script: 0x5a, flags: 0x0}, - 1051: {region: 0x142, script: 0x5a, flags: 0x0}, - 1052: {region: 0x10c, script: 0x5a, flags: 0x0}, - 1054: {region: 0x10c, script: 0x5a, flags: 0x0}, - 1055: {region: 0x72, script: 0x5a, flags: 0x0}, - 1056: {region: 0x97, script: 0xca, flags: 0x0}, - 1057: {region: 0x165, script: 0x5a, flags: 0x0}, - 1058: {region: 0x72, script: 0x5a, flags: 0x0}, - 1059: {region: 0x164, script: 0x5a, flags: 0x0}, - 1060: {region: 0x165, script: 0x5a, flags: 0x0}, - 1061: {region: 0xc3, script: 0x5a, flags: 0x0}, - 1062: {region: 0x165, script: 0x5a, flags: 0x0}, - 1063: {region: 0x165, script: 0x5a, flags: 0x0}, - 1064: {region: 0x165, script: 0x5a, flags: 0x0}, - 1065: {region: 0x115, script: 0x5a, flags: 0x0}, - 1066: {region: 0x165, script: 0x5a, flags: 0x0}, - 1067: {region: 0x165, script: 0x5a, flags: 0x0}, - 1068: {region: 0x123, script: 0xeb, flags: 0x0}, - 1069: {region: 0x165, script: 0x5a, flags: 0x0}, - 1070: {region: 0x165, script: 0x5a, flags: 0x0}, - 1071: {region: 0x165, script: 0x5a, flags: 0x0}, - 1072: {region: 0x165, script: 0x5a, flags: 0x0}, - 1073: {region: 0x27, script: 0x5a, flags: 0x0}, - 1074: {region: 0x37, script: 0x5, flags: 0x1}, - 1075: {region: 0x99, script: 0xd7, flags: 0x0}, - 1076: {region: 0x116, script: 0x5a, flags: 0x0}, - 1077: {region: 0x114, script: 0x5a, flags: 0x0}, - 1078: {region: 0x99, script: 0x22, flags: 0x0}, - 1079: {region: 0x161, script: 0x5a, flags: 0x0}, - 1080: {region: 0x165, script: 0x5a, flags: 0x0}, - 1081: {region: 0x165, script: 0x5a, flags: 0x0}, - 1082: {region: 0x6d, script: 0x5a, flags: 0x0}, - 1083: {region: 0x161, script: 0x5a, flags: 0x0}, - 1084: {region: 0x165, script: 0x5a, flags: 0x0}, - 1085: {region: 0x60, script: 0x5a, flags: 0x0}, - 1086: {region: 0x95, script: 0x5a, flags: 0x0}, - 1087: {region: 0x165, script: 0x5a, flags: 0x0}, - 1088: {region: 0x165, script: 0x5a, flags: 0x0}, - 1089: {region: 0x12f, script: 0x5a, flags: 0x0}, - 1090: {region: 0x165, script: 0x5a, flags: 0x0}, - 1091: {region: 0x84, script: 0x5a, flags: 0x0}, - 1092: {region: 0x10c, script: 0x5a, flags: 0x0}, - 1093: {region: 0x12f, script: 0x5a, flags: 0x0}, - 1094: {region: 0x15f, script: 0x5, flags: 0x0}, - 1095: {region: 0x4b, script: 0x5a, flags: 0x0}, - 1096: {region: 0x60, script: 0x5a, flags: 0x0}, - 1097: {region: 0x165, script: 0x5a, flags: 0x0}, - 1098: {region: 0x99, script: 0x22, flags: 0x0}, - 1099: {region: 0x95, script: 0x5a, flags: 0x0}, - 1100: {region: 0x165, script: 0x5a, flags: 0x0}, - 1101: {region: 0x35, script: 0xe, flags: 0x0}, - 1102: {region: 0x9b, script: 0xdb, flags: 0x0}, - 1103: {region: 0xe9, script: 0x5a, flags: 0x0}, - 1104: {region: 0x99, script: 0xe3, flags: 0x0}, - 1105: {region: 0xdb, script: 0x22, flags: 0x0}, - 1106: {region: 0x165, script: 0x5a, flags: 0x0}, - 1107: {region: 0x165, script: 0x5a, flags: 0x0}, - 1108: {region: 0x165, script: 0x5a, flags: 0x0}, - 1109: {region: 0x165, script: 0x5a, flags: 0x0}, - 1110: {region: 0x165, script: 0x5a, flags: 0x0}, - 1111: {region: 0x165, script: 0x5a, flags: 0x0}, - 1112: {region: 0x165, script: 0x5a, flags: 0x0}, - 1113: {region: 0x165, script: 0x5a, flags: 0x0}, - 1114: {region: 0xe7, script: 0x5a, flags: 0x0}, - 1115: {region: 0x165, script: 0x5a, flags: 0x0}, - 1116: {region: 0x165, script: 0x5a, flags: 0x0}, - 1117: {region: 0x99, script: 0x52, flags: 0x0}, - 1118: {region: 0x53, script: 0xe1, flags: 0x0}, - 1119: {region: 0xdb, script: 0x22, flags: 0x0}, - 1120: {region: 0xdb, script: 0x22, flags: 0x0}, - 1121: {region: 0x99, script: 0xe6, flags: 0x0}, - 1122: {region: 0x165, script: 0x5a, flags: 0x0}, - 1123: {region: 0x112, script: 0x5a, flags: 0x0}, - 1124: {region: 0x131, script: 0x5a, flags: 0x0}, - 1125: {region: 0x126, script: 0x5a, flags: 0x0}, - 1126: {region: 0x165, script: 0x5a, flags: 0x0}, - 1127: {region: 0x3c, script: 0x3, flags: 0x1}, - 1128: {region: 0x165, script: 0x5a, flags: 0x0}, - 1129: {region: 0x165, script: 0x5a, flags: 0x0}, - 1130: {region: 0x165, script: 0x5a, flags: 0x0}, - 1131: {region: 0x123, script: 0xeb, flags: 0x0}, - 1132: {region: 0xdb, script: 0x22, flags: 0x0}, - 1133: {region: 0xdb, script: 0x22, flags: 0x0}, - 1134: {region: 0xdb, script: 0x22, flags: 0x0}, - 1135: {region: 0x6f, script: 0x2c, flags: 0x0}, - 1136: {region: 0x165, script: 0x5a, flags: 0x0}, - 1137: {region: 0x6d, script: 0x2c, flags: 0x0}, - 1138: {region: 0x165, script: 0x5a, flags: 0x0}, - 1139: {region: 0x165, script: 0x5a, flags: 0x0}, - 1140: {region: 0x165, script: 0x5a, flags: 0x0}, - 1141: {region: 0xd6, script: 0x5a, flags: 0x0}, - 1142: {region: 0x127, script: 0x5a, flags: 0x0}, - 1143: {region: 0x125, script: 0x5a, flags: 0x0}, - 1144: {region: 0x32, script: 0x5a, flags: 0x0}, - 1145: {region: 0xdb, script: 0x22, flags: 0x0}, - 1146: {region: 0xe7, script: 0x5a, flags: 0x0}, - 1147: {region: 0x165, script: 0x5a, flags: 0x0}, - 1148: {region: 0x165, script: 0x5a, flags: 0x0}, - 1149: {region: 0x32, script: 0x5a, flags: 0x0}, - 1150: {region: 0xd4, script: 0x5a, flags: 0x0}, - 1151: {region: 0x165, script: 0x5a, flags: 0x0}, - 1152: {region: 0x161, script: 0x5a, flags: 0x0}, - 1153: {region: 0x165, script: 0x5a, flags: 0x0}, - 1154: {region: 0x129, script: 0x5a, flags: 0x0}, - 1155: {region: 0x165, script: 0x5a, flags: 0x0}, - 1156: {region: 0xce, script: 0x5a, flags: 0x0}, - 1157: {region: 0x165, script: 0x5a, flags: 0x0}, - 1158: {region: 0xe6, script: 0x5a, flags: 0x0}, - 1159: {region: 0x165, script: 0x5a, flags: 0x0}, - 1160: {region: 0x165, script: 0x5a, flags: 0x0}, - 1161: {region: 0x165, script: 0x5a, flags: 0x0}, - 1162: {region: 0x12b, script: 0x5a, flags: 0x0}, - 1163: {region: 0x12b, script: 0x5a, flags: 0x0}, - 1164: {region: 0x12e, script: 0x5a, flags: 0x0}, - 1165: {region: 0x165, script: 0x5, flags: 0x0}, - 1166: {region: 0x161, script: 0x5a, flags: 0x0}, - 1167: {region: 0x87, script: 0x34, flags: 0x0}, - 1168: {region: 0xdb, script: 0x22, flags: 0x0}, - 1169: {region: 0xe7, script: 0x5a, flags: 0x0}, - 1170: {region: 0x43, script: 0xec, flags: 0x0}, - 1171: {region: 0x165, script: 0x5a, flags: 0x0}, - 1172: {region: 0x106, script: 0x20, flags: 0x0}, - 1173: {region: 0x165, script: 0x5a, flags: 0x0}, - 1174: {region: 0x165, script: 0x5a, flags: 0x0}, - 1175: {region: 0x131, script: 0x5a, flags: 0x0}, - 1176: {region: 0x165, script: 0x5a, flags: 0x0}, - 1177: {region: 0x123, script: 0xeb, flags: 0x0}, - 1178: {region: 0x32, script: 0x5a, flags: 0x0}, - 1179: {region: 0x165, script: 0x5a, flags: 0x0}, - 1180: {region: 0x165, script: 0x5a, flags: 0x0}, - 1181: {region: 0xce, script: 0x5a, flags: 0x0}, - 1182: {region: 0x165, script: 0x5a, flags: 0x0}, - 1183: {region: 0x165, script: 0x5a, flags: 0x0}, - 1184: {region: 0x12d, script: 0x5a, flags: 0x0}, - 1185: {region: 0x165, script: 0x5a, flags: 0x0}, - 1187: {region: 0x165, script: 0x5a, flags: 0x0}, - 1188: {region: 0xd4, script: 0x5a, flags: 0x0}, - 1189: {region: 0x53, script: 0xe4, flags: 0x0}, - 1190: {region: 0xe5, script: 0x5a, flags: 0x0}, - 1191: {region: 0x165, script: 0x5a, flags: 0x0}, - 1192: {region: 0x106, script: 0x20, flags: 0x0}, - 1193: {region: 0xba, script: 0x5a, flags: 0x0}, - 1194: {region: 0x165, script: 0x5a, flags: 0x0}, - 1195: {region: 0x106, script: 0x20, flags: 0x0}, - 1196: {region: 0x3f, script: 0x4, flags: 0x1}, - 1197: {region: 0x11c, script: 0xf0, flags: 0x0}, - 1198: {region: 0x130, script: 0x20, flags: 0x0}, - 1199: {region: 0x75, script: 0x5a, flags: 0x0}, - 1200: {region: 0x2a, script: 0x5a, flags: 0x0}, - 1202: {region: 0x43, script: 0x3, flags: 0x1}, - 1203: {region: 0x99, script: 0xe, flags: 0x0}, - 1204: {region: 0xe8, script: 0x5, flags: 0x0}, - 1205: {region: 0x165, script: 0x5a, flags: 0x0}, - 1206: {region: 0x165, script: 0x5a, flags: 0x0}, - 1207: {region: 0x165, script: 0x5a, flags: 0x0}, - 1208: {region: 0x165, script: 0x5a, flags: 0x0}, - 1209: {region: 0x165, script: 0x5a, flags: 0x0}, - 1210: {region: 0x165, script: 0x5a, flags: 0x0}, - 1211: {region: 0x165, script: 0x5a, flags: 0x0}, - 1212: {region: 0x46, script: 0x4, flags: 0x1}, - 1213: {region: 0x165, script: 0x5a, flags: 0x0}, - 1214: {region: 0xb4, script: 0xf1, flags: 0x0}, - 1215: {region: 0x165, script: 0x5a, flags: 0x0}, - 1216: {region: 0x161, script: 0x5a, flags: 0x0}, - 1217: {region: 0x9e, script: 0x5a, flags: 0x0}, - 1218: {region: 0x106, script: 0x5a, flags: 0x0}, - 1219: {region: 0x13e, script: 0x5a, flags: 0x0}, - 1220: {region: 0x11b, script: 0x5a, flags: 0x0}, - 1221: {region: 0x165, script: 0x5a, flags: 0x0}, - 1222: {region: 0x36, script: 0x5a, flags: 0x0}, - 1223: {region: 0x60, script: 0x5a, flags: 0x0}, - 1224: {region: 0xd1, script: 0x5a, flags: 0x0}, - 1225: {region: 0x1, script: 0x5a, flags: 0x0}, - 1226: {region: 0x106, script: 0x5a, flags: 0x0}, - 1227: {region: 0x6a, script: 0x5a, flags: 0x0}, - 1228: {region: 0x12f, script: 0x5a, flags: 0x0}, - 1229: {region: 0x165, script: 0x5a, flags: 0x0}, - 1230: {region: 0x36, script: 0x5a, flags: 0x0}, - 1231: {region: 0x4e, script: 0x5a, flags: 0x0}, - 1232: {region: 0x165, script: 0x5a, flags: 0x0}, - 1233: {region: 0x6f, script: 0x2c, flags: 0x0}, - 1234: {region: 0x165, script: 0x5a, flags: 0x0}, - 1235: {region: 0xe7, script: 0x5a, flags: 0x0}, - 1236: {region: 0x2f, script: 0x5a, flags: 0x0}, - 1237: {region: 0x99, script: 0xe6, flags: 0x0}, - 1238: {region: 0x99, script: 0x22, flags: 0x0}, - 1239: {region: 0x165, script: 0x5a, flags: 0x0}, - 1240: {region: 0x165, script: 0x5a, flags: 0x0}, - 1241: {region: 0x165, script: 0x5a, flags: 0x0}, - 1242: {region: 0x165, script: 0x5a, flags: 0x0}, - 1243: {region: 0x165, script: 0x5a, flags: 0x0}, - 1244: {region: 0x165, script: 0x5a, flags: 0x0}, - 1245: {region: 0x165, script: 0x5a, flags: 0x0}, - 1246: {region: 0x165, script: 0x5a, flags: 0x0}, - 1247: {region: 0x165, script: 0x5a, flags: 0x0}, - 1248: {region: 0x140, script: 0x5a, flags: 0x0}, - 1249: {region: 0x165, script: 0x5a, flags: 0x0}, - 1250: {region: 0x165, script: 0x5a, flags: 0x0}, - 1251: {region: 0xa8, script: 0x5, flags: 0x0}, - 1252: {region: 0x165, script: 0x5a, flags: 0x0}, - 1253: {region: 0x114, script: 0x5a, flags: 0x0}, - 1254: {region: 0x165, script: 0x5a, flags: 0x0}, - 1255: {region: 0x165, script: 0x5a, flags: 0x0}, - 1256: {region: 0x165, script: 0x5a, flags: 0x0}, - 1257: {region: 0x165, script: 0x5a, flags: 0x0}, - 1258: {region: 0x99, script: 0x22, flags: 0x0}, - 1259: {region: 0x53, script: 0x3b, flags: 0x0}, - 1260: {region: 0x165, script: 0x5a, flags: 0x0}, - 1261: {region: 0x165, script: 0x5a, flags: 0x0}, - 1262: {region: 0x41, script: 0x5a, flags: 0x0}, - 1263: {region: 0x165, script: 0x5a, flags: 0x0}, - 1264: {region: 0x12b, script: 0x18, flags: 0x0}, - 1265: {region: 0x165, script: 0x5a, flags: 0x0}, - 1266: {region: 0x161, script: 0x5a, flags: 0x0}, - 1267: {region: 0x165, script: 0x5a, flags: 0x0}, - 1268: {region: 0x12b, script: 0x62, flags: 0x0}, - 1269: {region: 0x12b, script: 0x63, flags: 0x0}, - 1270: {region: 0x7d, script: 0x2e, flags: 0x0}, - 1271: {region: 0x53, script: 0x67, flags: 0x0}, - 1272: {region: 0x10b, script: 0x6c, flags: 0x0}, - 1273: {region: 0x108, script: 0x77, flags: 0x0}, - 1274: {region: 0x99, script: 0x22, flags: 0x0}, - 1275: {region: 0x131, script: 0x5a, flags: 0x0}, - 1276: {region: 0x165, script: 0x5a, flags: 0x0}, - 1277: {region: 0x9c, script: 0x91, flags: 0x0}, - 1278: {region: 0x165, script: 0x5a, flags: 0x0}, - 1279: {region: 0x15e, script: 0xcc, flags: 0x0}, - 1280: {region: 0x165, script: 0x5a, flags: 0x0}, - 1281: {region: 0x165, script: 0x5a, flags: 0x0}, - 1282: {region: 0xdb, script: 0x22, flags: 0x0}, - 1283: {region: 0x165, script: 0x5a, flags: 0x0}, - 1284: {region: 0x165, script: 0x5a, flags: 0x0}, - 1285: {region: 0xd1, script: 0x5a, flags: 0x0}, - 1286: {region: 0x75, script: 0x5a, flags: 0x0}, - 1287: {region: 0x165, script: 0x5a, flags: 0x0}, - 1288: {region: 0x165, script: 0x5a, flags: 0x0}, - 1289: {region: 0x52, script: 0x5a, flags: 0x0}, - 1290: {region: 0x165, script: 0x5a, flags: 0x0}, - 1291: {region: 0x165, script: 0x5a, flags: 0x0}, - 1292: {region: 0x165, script: 0x5a, flags: 0x0}, - 1293: {region: 0x52, script: 0x5a, flags: 0x0}, - 1294: {region: 0x165, script: 0x5a, flags: 0x0}, - 1295: {region: 0x165, script: 0x5a, flags: 0x0}, - 1296: {region: 0x165, script: 0x5a, flags: 0x0}, - 1297: {region: 0x165, script: 0x5a, flags: 0x0}, - 1298: {region: 0x1, script: 0x3e, flags: 0x0}, - 1299: {region: 0x165, script: 0x5a, flags: 0x0}, - 1300: {region: 0x165, script: 0x5a, flags: 0x0}, - 1301: {region: 0x165, script: 0x5a, flags: 0x0}, - 1302: {region: 0x165, script: 0x5a, flags: 0x0}, - 1303: {region: 0x165, script: 0x5a, flags: 0x0}, - 1304: {region: 0xd6, script: 0x5a, flags: 0x0}, - 1305: {region: 0x165, script: 0x5a, flags: 0x0}, - 1306: {region: 0x165, script: 0x5a, flags: 0x0}, - 1307: {region: 0x165, script: 0x5a, flags: 0x0}, - 1308: {region: 0x41, script: 0x5a, flags: 0x0}, - 1309: {region: 0x165, script: 0x5a, flags: 0x0}, - 1310: {region: 0xcf, script: 0x5a, flags: 0x0}, - 1311: {region: 0x4a, script: 0x3, flags: 0x1}, - 1312: {region: 0x165, script: 0x5a, flags: 0x0}, - 1313: {region: 0x165, script: 0x5a, flags: 0x0}, - 1314: {region: 0x165, script: 0x5a, flags: 0x0}, - 1315: {region: 0x53, script: 0x5a, flags: 0x0}, - 1316: {region: 0x10b, script: 0x5a, flags: 0x0}, - 1318: {region: 0xa8, script: 0x5, flags: 0x0}, - 1319: {region: 0xd9, script: 0x5a, flags: 0x0}, - 1320: {region: 0xba, script: 0xe8, flags: 0x0}, - 1321: {region: 0x4d, script: 0x14, flags: 0x1}, - 1322: {region: 0x53, script: 0x7d, flags: 0x0}, - 1323: {region: 0x165, script: 0x5a, flags: 0x0}, - 1324: {region: 0x122, script: 0x5a, flags: 0x0}, - 1325: {region: 0xd0, script: 0x5a, flags: 0x0}, - 1326: {region: 0x165, script: 0x5a, flags: 0x0}, - 1327: {region: 0x161, script: 0x5a, flags: 0x0}, - 1329: {region: 0x12b, script: 0x5a, flags: 0x0}, -} - -// likelyLangList holds lists info associated with likelyLang. -// Size: 582 bytes, 97 elements -var likelyLangList = [97]likelyScriptRegion{ - 0: {region: 0x9c, script: 0x7, flags: 0x0}, - 1: {region: 0xa1, script: 0x78, flags: 0x2}, - 2: {region: 0x11c, script: 0x85, flags: 0x2}, - 3: {region: 0x32, script: 0x5a, flags: 0x0}, - 4: {region: 0x9b, script: 0x5, flags: 0x4}, - 5: {region: 0x9c, script: 0x5, flags: 0x4}, - 6: {region: 0x106, script: 0x20, flags: 0x4}, - 7: {region: 0x9c, script: 0x5, flags: 0x2}, - 8: {region: 0x106, script: 0x20, flags: 0x0}, - 9: {region: 0x38, script: 0x2f, flags: 0x2}, - 10: {region: 0x135, script: 0x5a, flags: 0x0}, - 11: {region: 0x7b, script: 0xcf, flags: 0x2}, - 12: {region: 0x114, script: 0x5a, flags: 0x0}, - 13: {region: 0x84, script: 0x1, flags: 0x2}, - 14: {region: 0x5d, script: 0x1f, flags: 0x0}, - 15: {region: 0x87, script: 0x5f, flags: 0x2}, - 16: {region: 0xd6, script: 0x5a, flags: 0x0}, - 17: {region: 0x52, script: 0x5, flags: 0x4}, - 18: {region: 0x10b, script: 0x5, flags: 0x4}, - 19: {region: 0xae, script: 0x20, flags: 0x0}, - 20: {region: 0x24, script: 0x5, flags: 0x4}, - 21: {region: 0x53, script: 0x5, flags: 0x4}, - 22: {region: 0x9c, script: 0x5, flags: 0x4}, - 23: {region: 0xc5, script: 0x5, flags: 0x4}, - 24: {region: 0x53, script: 0x5, flags: 0x2}, - 25: {region: 0x12b, script: 0x5a, flags: 0x0}, - 26: {region: 0xb0, script: 0x5, flags: 0x4}, - 27: {region: 0x9b, script: 0x5, flags: 0x2}, - 28: {region: 0xa5, script: 0x20, flags: 0x0}, - 29: {region: 0x53, script: 0x5, flags: 0x4}, - 30: {region: 0x12b, script: 0x5a, flags: 0x4}, - 31: {region: 0x53, script: 0x5, flags: 0x2}, - 32: {region: 0x12b, script: 0x5a, flags: 0x2}, - 33: {region: 0xdb, script: 0x22, flags: 0x0}, - 34: {region: 0x99, script: 0x5d, flags: 0x2}, - 35: {region: 0x83, script: 0x5a, flags: 0x0}, - 36: {region: 0x84, script: 0x7c, flags: 0x4}, - 37: {region: 0x84, script: 0x7c, flags: 0x2}, - 38: {region: 0xc5, script: 0x20, flags: 0x0}, - 39: {region: 0x53, script: 0x70, flags: 0x4}, - 40: {region: 0x53, script: 0x70, flags: 0x2}, - 41: {region: 0xd0, script: 0x5a, flags: 0x0}, - 42: {region: 0x4a, script: 0x5, flags: 0x4}, - 43: {region: 0x95, script: 0x5, flags: 0x4}, - 44: {region: 0x99, script: 0x36, flags: 0x0}, - 45: {region: 0xe8, script: 0x5, flags: 0x4}, - 46: {region: 0xe8, script: 0x5, flags: 0x2}, - 47: {region: 0x9c, script: 0x8b, flags: 0x0}, - 48: {region: 0x53, script: 0x8c, flags: 0x2}, - 49: {region: 0xba, script: 0xe8, flags: 0x0}, - 50: {region: 0xd9, script: 0x5a, flags: 0x4}, - 51: {region: 0xe8, script: 0x5, flags: 0x0}, - 52: {region: 0x99, script: 0x22, flags: 0x2}, - 53: {region: 0x99, script: 0x4f, flags: 0x2}, - 54: {region: 0x99, script: 0xd3, flags: 0x2}, - 55: {region: 0x105, script: 0x20, flags: 0x0}, - 56: {region: 0xbd, script: 0x5a, flags: 0x4}, - 57: {region: 0x104, script: 0x5a, flags: 0x4}, - 58: {region: 0x106, script: 0x5a, flags: 0x4}, - 59: {region: 0x12b, script: 0x5a, flags: 0x4}, - 60: {region: 0x124, script: 0x20, flags: 0x0}, - 61: {region: 0xe8, script: 0x5, flags: 0x4}, - 62: {region: 0xe8, script: 0x5, flags: 0x2}, - 63: {region: 0x53, script: 0x5, flags: 0x0}, - 64: {region: 0xae, script: 0x20, flags: 0x4}, - 65: {region: 0xc5, script: 0x20, flags: 0x4}, - 66: {region: 0xae, script: 0x20, flags: 0x2}, - 67: {region: 0x99, script: 0xe, flags: 0x0}, - 68: {region: 0xdb, script: 0x22, flags: 0x4}, - 69: {region: 0xdb, script: 0x22, flags: 0x2}, - 70: {region: 0x137, script: 0x5a, flags: 0x0}, - 71: {region: 0x24, script: 0x5, flags: 0x4}, - 72: {region: 0x53, script: 0x20, flags: 0x4}, - 73: {region: 0x24, script: 0x5, flags: 0x2}, - 74: {region: 0x8d, script: 0x3c, flags: 0x0}, - 75: {region: 0x53, script: 0x3b, flags: 0x4}, - 76: {region: 0x53, script: 0x3b, flags: 0x2}, - 77: {region: 0x53, script: 0x3b, flags: 0x0}, - 78: {region: 0x2f, script: 0x3c, flags: 0x4}, - 79: {region: 0x3e, script: 0x3c, flags: 0x4}, - 80: {region: 0x7b, script: 0x3c, flags: 0x4}, - 81: {region: 0x7e, script: 0x3c, flags: 0x4}, - 82: {region: 0x8d, script: 0x3c, flags: 0x4}, - 83: {region: 0x95, script: 0x3c, flags: 0x4}, - 84: {region: 0xc6, script: 0x3c, flags: 0x4}, - 85: {region: 0xd0, script: 0x3c, flags: 0x4}, - 86: {region: 0xe2, script: 0x3c, flags: 0x4}, - 87: {region: 0xe5, script: 0x3c, flags: 0x4}, - 88: {region: 0xe7, script: 0x3c, flags: 0x4}, - 89: {region: 0x116, script: 0x3c, flags: 0x4}, - 90: {region: 0x123, script: 0x3c, flags: 0x4}, - 91: {region: 0x12e, script: 0x3c, flags: 0x4}, - 92: {region: 0x135, script: 0x3c, flags: 0x4}, - 93: {region: 0x13e, script: 0x3c, flags: 0x4}, - 94: {region: 0x12e, script: 0x11, flags: 0x2}, - 95: {region: 0x12e, script: 0x37, flags: 0x2}, - 96: {region: 0x12e, script: 0x3c, flags: 0x2}, -} - -type likelyLangScript struct { - lang uint16 - script uint16 - flags uint8 -} - -// likelyRegion is a lookup table, indexed by regionID, for the most likely -// languages and scripts given incomplete information. If more entries exist -// for a given regionID, lang and script are the index and size respectively -// of the list in likelyRegionList. -// TODO: exclude containers and user-definable regions from the list. -// Size: 2148 bytes, 358 elements -var likelyRegion = [358]likelyLangScript{ - 34: {lang: 0xd7, script: 0x5a, flags: 0x0}, - 35: {lang: 0x3a, script: 0x5, flags: 0x0}, - 36: {lang: 0x0, script: 0x2, flags: 0x1}, - 39: {lang: 0x2, script: 0x2, flags: 0x1}, - 40: {lang: 0x4, script: 0x2, flags: 0x1}, - 42: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 43: {lang: 0x0, script: 0x5a, flags: 0x0}, - 44: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 45: {lang: 0x41b, script: 0x5a, flags: 0x0}, - 46: {lang: 0x10d, script: 0x5a, flags: 0x0}, - 48: {lang: 0x367, script: 0x5a, flags: 0x0}, - 49: {lang: 0x444, script: 0x5a, flags: 0x0}, - 50: {lang: 0x58, script: 0x5a, flags: 0x0}, - 51: {lang: 0x6, script: 0x2, flags: 0x1}, - 53: {lang: 0xa5, script: 0xe, flags: 0x0}, - 54: {lang: 0x367, script: 0x5a, flags: 0x0}, - 55: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 56: {lang: 0x7e, script: 0x20, flags: 0x0}, - 57: {lang: 0x3a, script: 0x5, flags: 0x0}, - 58: {lang: 0x3d9, script: 0x5a, flags: 0x0}, - 59: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 60: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 62: {lang: 0x31f, script: 0x5a, flags: 0x0}, - 63: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 64: {lang: 0x3a1, script: 0x5a, flags: 0x0}, - 65: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 67: {lang: 0x8, script: 0x2, flags: 0x1}, - 69: {lang: 0x0, script: 0x5a, flags: 0x0}, - 71: {lang: 0x71, script: 0x20, flags: 0x0}, - 73: {lang: 0x512, script: 0x3e, flags: 0x2}, - 74: {lang: 0x31f, script: 0x5, flags: 0x2}, - 75: {lang: 0x445, script: 0x5a, flags: 0x0}, - 76: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 77: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 78: {lang: 0x10d, script: 0x5a, flags: 0x0}, - 79: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 81: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 82: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 83: {lang: 0xa, script: 0x4, flags: 0x1}, - 84: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 85: {lang: 0x0, script: 0x5a, flags: 0x0}, - 86: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 89: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 90: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 91: {lang: 0x3a1, script: 0x5a, flags: 0x0}, - 93: {lang: 0xe, script: 0x2, flags: 0x1}, - 94: {lang: 0xfa, script: 0x5a, flags: 0x0}, - 96: {lang: 0x10d, script: 0x5a, flags: 0x0}, - 98: {lang: 0x1, script: 0x5a, flags: 0x0}, - 99: {lang: 0x101, script: 0x5a, flags: 0x0}, - 101: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 103: {lang: 0x10, script: 0x2, flags: 0x1}, - 104: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 105: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 106: {lang: 0x140, script: 0x5a, flags: 0x0}, - 107: {lang: 0x3a, script: 0x5, flags: 0x0}, - 108: {lang: 0x3a, script: 0x5, flags: 0x0}, - 109: {lang: 0x46f, script: 0x2c, flags: 0x0}, - 110: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 111: {lang: 0x12, script: 0x2, flags: 0x1}, - 113: {lang: 0x10d, script: 0x5a, flags: 0x0}, - 114: {lang: 0x151, script: 0x5a, flags: 0x0}, - 115: {lang: 0x1c0, script: 0x22, flags: 0x2}, - 118: {lang: 0x158, script: 0x5a, flags: 0x0}, - 120: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 122: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 123: {lang: 0x14, script: 0x2, flags: 0x1}, - 125: {lang: 0x16, script: 0x3, flags: 0x1}, - 126: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 128: {lang: 0x21, script: 0x5a, flags: 0x0}, - 130: {lang: 0x245, script: 0x5a, flags: 0x0}, - 132: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 133: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 134: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 135: {lang: 0x19, script: 0x2, flags: 0x1}, - 136: {lang: 0x0, script: 0x5a, flags: 0x0}, - 137: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 139: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 141: {lang: 0x529, script: 0x3c, flags: 0x0}, - 142: {lang: 0x0, script: 0x5a, flags: 0x0}, - 143: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 144: {lang: 0x1d1, script: 0x5a, flags: 0x0}, - 145: {lang: 0x1d4, script: 0x5a, flags: 0x0}, - 146: {lang: 0x1d5, script: 0x5a, flags: 0x0}, - 148: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 149: {lang: 0x1b, script: 0x2, flags: 0x1}, - 151: {lang: 0x1bc, script: 0x3e, flags: 0x0}, - 153: {lang: 0x1d, script: 0x3, flags: 0x1}, - 155: {lang: 0x3a, script: 0x5, flags: 0x0}, - 156: {lang: 0x20, script: 0x2, flags: 0x1}, - 157: {lang: 0x1f8, script: 0x5a, flags: 0x0}, - 158: {lang: 0x1f9, script: 0x5a, flags: 0x0}, - 161: {lang: 0x3a, script: 0x5, flags: 0x0}, - 162: {lang: 0x200, script: 0x49, flags: 0x0}, - 164: {lang: 0x445, script: 0x5a, flags: 0x0}, - 165: {lang: 0x28a, script: 0x20, flags: 0x0}, - 166: {lang: 0x22, script: 0x3, flags: 0x1}, - 168: {lang: 0x25, script: 0x2, flags: 0x1}, - 170: {lang: 0x254, script: 0x53, flags: 0x0}, - 171: {lang: 0x254, script: 0x53, flags: 0x0}, - 172: {lang: 0x3a, script: 0x5, flags: 0x0}, - 174: {lang: 0x3e2, script: 0x20, flags: 0x0}, - 175: {lang: 0x27, script: 0x2, flags: 0x1}, - 176: {lang: 0x3a, script: 0x5, flags: 0x0}, - 178: {lang: 0x10d, script: 0x5a, flags: 0x0}, - 179: {lang: 0x40c, script: 0xd4, flags: 0x0}, - 181: {lang: 0x43b, script: 0x5a, flags: 0x0}, - 182: {lang: 0x2c0, script: 0x5a, flags: 0x0}, - 183: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 184: {lang: 0x2c7, script: 0x5a, flags: 0x0}, - 185: {lang: 0x3a, script: 0x5, flags: 0x0}, - 186: {lang: 0x29, script: 0x2, flags: 0x1}, - 187: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 188: {lang: 0x2b, script: 0x2, flags: 0x1}, - 189: {lang: 0x432, script: 0x5a, flags: 0x0}, - 190: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 191: {lang: 0x2f1, script: 0x5a, flags: 0x0}, - 194: {lang: 0x2d, script: 0x2, flags: 0x1}, - 195: {lang: 0xa0, script: 0x5a, flags: 0x0}, - 196: {lang: 0x2f, script: 0x2, flags: 0x1}, - 197: {lang: 0x31, script: 0x2, flags: 0x1}, - 198: {lang: 0x33, script: 0x2, flags: 0x1}, - 200: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 201: {lang: 0x35, script: 0x2, flags: 0x1}, - 203: {lang: 0x320, script: 0x5a, flags: 0x0}, - 204: {lang: 0x37, script: 0x3, flags: 0x1}, - 205: {lang: 0x128, script: 0xea, flags: 0x0}, - 207: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 208: {lang: 0x31f, script: 0x5a, flags: 0x0}, - 209: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 210: {lang: 0x16, script: 0x5a, flags: 0x0}, - 211: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 212: {lang: 0x1b4, script: 0x5a, flags: 0x0}, - 214: {lang: 0x1b4, script: 0x5, flags: 0x2}, - 216: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 217: {lang: 0x367, script: 0x5a, flags: 0x0}, - 218: {lang: 0x347, script: 0x5a, flags: 0x0}, - 219: {lang: 0x351, script: 0x22, flags: 0x0}, - 225: {lang: 0x3a, script: 0x5, flags: 0x0}, - 226: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 228: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 229: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 230: {lang: 0x486, script: 0x5a, flags: 0x0}, - 231: {lang: 0x153, script: 0x5a, flags: 0x0}, - 232: {lang: 0x3a, script: 0x3, flags: 0x1}, - 233: {lang: 0x3b3, script: 0x5a, flags: 0x0}, - 234: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 236: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 237: {lang: 0x3a, script: 0x5, flags: 0x0}, - 238: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 240: {lang: 0x3a2, script: 0x5a, flags: 0x0}, - 241: {lang: 0x194, script: 0x5a, flags: 0x0}, - 243: {lang: 0x3a, script: 0x5, flags: 0x0}, - 258: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 260: {lang: 0x3d, script: 0x2, flags: 0x1}, - 261: {lang: 0x432, script: 0x20, flags: 0x0}, - 262: {lang: 0x3f, script: 0x2, flags: 0x1}, - 263: {lang: 0x3e5, script: 0x5a, flags: 0x0}, - 264: {lang: 0x3a, script: 0x5, flags: 0x0}, - 266: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 267: {lang: 0x3a, script: 0x5, flags: 0x0}, - 268: {lang: 0x41, script: 0x2, flags: 0x1}, - 271: {lang: 0x416, script: 0x5a, flags: 0x0}, - 272: {lang: 0x347, script: 0x5a, flags: 0x0}, - 273: {lang: 0x43, script: 0x2, flags: 0x1}, - 275: {lang: 0x1f9, script: 0x5a, flags: 0x0}, - 276: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 277: {lang: 0x429, script: 0x5a, flags: 0x0}, - 278: {lang: 0x367, script: 0x5a, flags: 0x0}, - 280: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 282: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 284: {lang: 0x45, script: 0x2, flags: 0x1}, - 288: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 289: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 290: {lang: 0x47, script: 0x2, flags: 0x1}, - 291: {lang: 0x49, script: 0x3, flags: 0x1}, - 292: {lang: 0x4c, script: 0x2, flags: 0x1}, - 293: {lang: 0x477, script: 0x5a, flags: 0x0}, - 294: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 295: {lang: 0x476, script: 0x5a, flags: 0x0}, - 296: {lang: 0x4e, script: 0x2, flags: 0x1}, - 297: {lang: 0x482, script: 0x5a, flags: 0x0}, - 299: {lang: 0x50, script: 0x4, flags: 0x1}, - 301: {lang: 0x4a0, script: 0x5a, flags: 0x0}, - 302: {lang: 0x54, script: 0x2, flags: 0x1}, - 303: {lang: 0x445, script: 0x5a, flags: 0x0}, - 304: {lang: 0x56, script: 0x3, flags: 0x1}, - 305: {lang: 0x445, script: 0x5a, flags: 0x0}, - 309: {lang: 0x512, script: 0x3e, flags: 0x2}, - 310: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 311: {lang: 0x4bc, script: 0x5a, flags: 0x0}, - 312: {lang: 0x1f9, script: 0x5a, flags: 0x0}, - 315: {lang: 0x13e, script: 0x5a, flags: 0x0}, - 318: {lang: 0x4c3, script: 0x5a, flags: 0x0}, - 319: {lang: 0x8a, script: 0x5a, flags: 0x0}, - 320: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 322: {lang: 0x41b, script: 0x5a, flags: 0x0}, - 333: {lang: 0x59, script: 0x2, flags: 0x1}, - 350: {lang: 0x3a, script: 0x5, flags: 0x0}, - 351: {lang: 0x5b, script: 0x2, flags: 0x1}, - 356: {lang: 0x423, script: 0x5a, flags: 0x0}, -} - -// likelyRegionList holds lists info associated with likelyRegion. -// Size: 558 bytes, 93 elements -var likelyRegionList = [93]likelyLangScript{ - 0: {lang: 0x148, script: 0x5, flags: 0x0}, - 1: {lang: 0x476, script: 0x5a, flags: 0x0}, - 2: {lang: 0x431, script: 0x5a, flags: 0x0}, - 3: {lang: 0x2ff, script: 0x20, flags: 0x0}, - 4: {lang: 0x1d7, script: 0x8, flags: 0x0}, - 5: {lang: 0x274, script: 0x5a, flags: 0x0}, - 6: {lang: 0xb7, script: 0x5a, flags: 0x0}, - 7: {lang: 0x432, script: 0x20, flags: 0x0}, - 8: {lang: 0x12d, script: 0xec, flags: 0x0}, - 9: {lang: 0x351, script: 0x22, flags: 0x0}, - 10: {lang: 0x529, script: 0x3b, flags: 0x0}, - 11: {lang: 0x4ac, script: 0x5, flags: 0x0}, - 12: {lang: 0x523, script: 0x5a, flags: 0x0}, - 13: {lang: 0x29a, script: 0xeb, flags: 0x0}, - 14: {lang: 0x136, script: 0x34, flags: 0x0}, - 15: {lang: 0x48a, script: 0x5a, flags: 0x0}, - 16: {lang: 0x3a, script: 0x5, flags: 0x0}, - 17: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 18: {lang: 0x27, script: 0x2c, flags: 0x0}, - 19: {lang: 0x139, script: 0x5a, flags: 0x0}, - 20: {lang: 0x26a, script: 0x5, flags: 0x2}, - 21: {lang: 0x512, script: 0x3e, flags: 0x2}, - 22: {lang: 0x210, script: 0x2e, flags: 0x0}, - 23: {lang: 0x5, script: 0x20, flags: 0x0}, - 24: {lang: 0x274, script: 0x5a, flags: 0x0}, - 25: {lang: 0x136, script: 0x34, flags: 0x0}, - 26: {lang: 0x2ff, script: 0x20, flags: 0x0}, - 27: {lang: 0x1e1, script: 0x5a, flags: 0x0}, - 28: {lang: 0x31f, script: 0x5, flags: 0x0}, - 29: {lang: 0x1be, script: 0x22, flags: 0x0}, - 30: {lang: 0x4b4, script: 0x5, flags: 0x0}, - 31: {lang: 0x236, script: 0x75, flags: 0x0}, - 32: {lang: 0x148, script: 0x5, flags: 0x0}, - 33: {lang: 0x476, script: 0x5a, flags: 0x0}, - 34: {lang: 0x24a, script: 0x4e, flags: 0x0}, - 35: {lang: 0xe6, script: 0x5, flags: 0x0}, - 36: {lang: 0x226, script: 0xeb, flags: 0x0}, - 37: {lang: 0x3a, script: 0x5, flags: 0x0}, - 38: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 39: {lang: 0x2b8, script: 0x57, flags: 0x0}, - 40: {lang: 0x226, script: 0xeb, flags: 0x0}, - 41: {lang: 0x3a, script: 0x5, flags: 0x0}, - 42: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 43: {lang: 0x3dc, script: 0x5a, flags: 0x0}, - 44: {lang: 0x4ae, script: 0x20, flags: 0x0}, - 45: {lang: 0x2ff, script: 0x20, flags: 0x0}, - 46: {lang: 0x431, script: 0x5a, flags: 0x0}, - 47: {lang: 0x331, script: 0x75, flags: 0x0}, - 48: {lang: 0x213, script: 0x5a, flags: 0x0}, - 49: {lang: 0x30b, script: 0x20, flags: 0x0}, - 50: {lang: 0x242, script: 0x5, flags: 0x0}, - 51: {lang: 0x529, script: 0x3c, flags: 0x0}, - 52: {lang: 0x3c0, script: 0x5a, flags: 0x0}, - 53: {lang: 0x3a, script: 0x5, flags: 0x0}, - 54: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 55: {lang: 0x2ed, script: 0x5a, flags: 0x0}, - 56: {lang: 0x4b4, script: 0x5, flags: 0x0}, - 57: {lang: 0x88, script: 0x22, flags: 0x0}, - 58: {lang: 0x4b4, script: 0x5, flags: 0x0}, - 59: {lang: 0x4b4, script: 0x5, flags: 0x0}, - 60: {lang: 0xbe, script: 0x22, flags: 0x0}, - 61: {lang: 0x3dc, script: 0x5a, flags: 0x0}, - 62: {lang: 0x7e, script: 0x20, flags: 0x0}, - 63: {lang: 0x3e2, script: 0x20, flags: 0x0}, - 64: {lang: 0x267, script: 0x5a, flags: 0x0}, - 65: {lang: 0x444, script: 0x5a, flags: 0x0}, - 66: {lang: 0x512, script: 0x3e, flags: 0x0}, - 67: {lang: 0x412, script: 0x5a, flags: 0x0}, - 68: {lang: 0x4ae, script: 0x20, flags: 0x0}, - 69: {lang: 0x3a, script: 0x5, flags: 0x0}, - 70: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 71: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 72: {lang: 0x35, script: 0x5, flags: 0x0}, - 73: {lang: 0x46b, script: 0xeb, flags: 0x0}, - 74: {lang: 0x2ec, script: 0x5, flags: 0x0}, - 75: {lang: 0x30f, script: 0x75, flags: 0x0}, - 76: {lang: 0x467, script: 0x20, flags: 0x0}, - 77: {lang: 0x148, script: 0x5, flags: 0x0}, - 78: {lang: 0x3a, script: 0x5, flags: 0x0}, - 79: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 80: {lang: 0x48a, script: 0x5a, flags: 0x0}, - 81: {lang: 0x58, script: 0x5, flags: 0x0}, - 82: {lang: 0x219, script: 0x20, flags: 0x0}, - 83: {lang: 0x81, script: 0x34, flags: 0x0}, - 84: {lang: 0x529, script: 0x3c, flags: 0x0}, - 85: {lang: 0x48c, script: 0x5a, flags: 0x0}, - 86: {lang: 0x4ae, script: 0x20, flags: 0x0}, - 87: {lang: 0x512, script: 0x3e, flags: 0x0}, - 88: {lang: 0x3b3, script: 0x5a, flags: 0x0}, - 89: {lang: 0x431, script: 0x5a, flags: 0x0}, - 90: {lang: 0x432, script: 0x20, flags: 0x0}, - 91: {lang: 0x15e, script: 0x5a, flags: 0x0}, - 92: {lang: 0x446, script: 0x5, flags: 0x0}, -} - -type likelyTag struct { - lang uint16 - region uint16 - script uint16 -} - -// Size: 198 bytes, 33 elements -var likelyRegionGroup = [33]likelyTag{ - 1: {lang: 0x139, region: 0xd6, script: 0x5a}, - 2: {lang: 0x139, region: 0x135, script: 0x5a}, - 3: {lang: 0x3c0, region: 0x41, script: 0x5a}, - 4: {lang: 0x139, region: 0x2f, script: 0x5a}, - 5: {lang: 0x139, region: 0xd6, script: 0x5a}, - 6: {lang: 0x13e, region: 0xcf, script: 0x5a}, - 7: {lang: 0x445, region: 0x12f, script: 0x5a}, - 8: {lang: 0x3a, region: 0x6b, script: 0x5}, - 9: {lang: 0x445, region: 0x4b, script: 0x5a}, - 10: {lang: 0x139, region: 0x161, script: 0x5a}, - 11: {lang: 0x139, region: 0x135, script: 0x5a}, - 12: {lang: 0x139, region: 0x135, script: 0x5a}, - 13: {lang: 0x13e, region: 0x59, script: 0x5a}, - 14: {lang: 0x529, region: 0x53, script: 0x3b}, - 15: {lang: 0x1be, region: 0x99, script: 0x22}, - 16: {lang: 0x1e1, region: 0x95, script: 0x5a}, - 17: {lang: 0x1f9, region: 0x9e, script: 0x5a}, - 18: {lang: 0x139, region: 0x2f, script: 0x5a}, - 19: {lang: 0x139, region: 0xe6, script: 0x5a}, - 20: {lang: 0x139, region: 0x8a, script: 0x5a}, - 21: {lang: 0x41b, region: 0x142, script: 0x5a}, - 22: {lang: 0x529, region: 0x53, script: 0x3b}, - 23: {lang: 0x4bc, region: 0x137, script: 0x5a}, - 24: {lang: 0x3a, region: 0x108, script: 0x5}, - 25: {lang: 0x3e2, region: 0x106, script: 0x20}, - 26: {lang: 0x3e2, region: 0x106, script: 0x20}, - 27: {lang: 0x139, region: 0x7b, script: 0x5a}, - 28: {lang: 0x10d, region: 0x60, script: 0x5a}, - 29: {lang: 0x139, region: 0xd6, script: 0x5a}, - 30: {lang: 0x13e, region: 0x1f, script: 0x5a}, - 31: {lang: 0x139, region: 0x9a, script: 0x5a}, - 32: {lang: 0x139, region: 0x7b, script: 0x5a}, -} - -// Size: 264 bytes, 33 elements -var regionContainment = [33]uint64{ - // Entry 0 - 1F - 0x00000001ffffffff, 0x00000000200007a2, 0x0000000000003044, 0x0000000000000008, - 0x00000000803c0010, 0x0000000000000020, 0x0000000000000040, 0x0000000000000080, - 0x0000000000000100, 0x0000000000000200, 0x0000000000000400, 0x000000004000384c, - 0x0000000000001000, 0x0000000000002000, 0x0000000000004000, 0x0000000000008000, - 0x0000000000010000, 0x0000000000020000, 0x0000000000040000, 0x0000000000080000, - 0x0000000000100000, 0x0000000000200000, 0x0000000001c1c000, 0x0000000000800000, - 0x0000000001000000, 0x000000001e020000, 0x0000000004000000, 0x0000000008000000, - 0x0000000010000000, 0x00000000200006a0, 0x0000000040002048, 0x0000000080000000, - // Entry 20 - 3F - 0x0000000100000000, -} - -// regionInclusion maps region identifiers to sets of regions in regionInclusionBits, -// where each set holds all groupings that are directly connected in a region -// containment graph. -// Size: 358 bytes, 358 elements -var regionInclusion = [358]uint8{ - // Entry 0 - 3F - 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, - 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, - 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, - 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x26, 0x23, - 0x24, 0x26, 0x27, 0x22, 0x28, 0x29, 0x2a, 0x2b, - 0x26, 0x2c, 0x24, 0x23, 0x26, 0x25, 0x2a, 0x2d, - 0x2e, 0x24, 0x2f, 0x2d, 0x26, 0x30, 0x31, 0x28, - // Entry 40 - 7F - 0x26, 0x28, 0x26, 0x25, 0x31, 0x22, 0x32, 0x33, - 0x34, 0x30, 0x22, 0x27, 0x27, 0x27, 0x35, 0x2d, - 0x29, 0x28, 0x27, 0x36, 0x28, 0x22, 0x34, 0x23, - 0x21, 0x26, 0x2d, 0x26, 0x22, 0x37, 0x2e, 0x35, - 0x2a, 0x22, 0x2f, 0x38, 0x26, 0x26, 0x21, 0x39, - 0x39, 0x28, 0x38, 0x39, 0x39, 0x2f, 0x3a, 0x2f, - 0x20, 0x21, 0x38, 0x3b, 0x28, 0x3c, 0x2c, 0x21, - 0x2a, 0x35, 0x27, 0x38, 0x26, 0x24, 0x28, 0x2c, - // Entry 80 - BF - 0x2d, 0x23, 0x30, 0x2d, 0x2d, 0x26, 0x27, 0x3a, - 0x22, 0x34, 0x3c, 0x2d, 0x28, 0x36, 0x22, 0x34, - 0x3a, 0x26, 0x2e, 0x21, 0x39, 0x31, 0x38, 0x24, - 0x2c, 0x25, 0x22, 0x24, 0x25, 0x2c, 0x3a, 0x2c, - 0x26, 0x24, 0x36, 0x21, 0x2f, 0x3d, 0x31, 0x3c, - 0x2f, 0x26, 0x36, 0x36, 0x24, 0x26, 0x3d, 0x31, - 0x24, 0x26, 0x35, 0x25, 0x2d, 0x32, 0x38, 0x2a, - 0x38, 0x39, 0x39, 0x35, 0x33, 0x23, 0x26, 0x2f, - // Entry C0 - FF - 0x3c, 0x21, 0x23, 0x2d, 0x31, 0x36, 0x36, 0x3c, - 0x26, 0x2d, 0x26, 0x3a, 0x2f, 0x25, 0x2f, 0x34, - 0x31, 0x2f, 0x32, 0x3b, 0x2d, 0x2b, 0x2d, 0x21, - 0x34, 0x2a, 0x2c, 0x25, 0x21, 0x3c, 0x24, 0x29, - 0x2b, 0x24, 0x34, 0x21, 0x28, 0x29, 0x3b, 0x31, - 0x25, 0x2e, 0x30, 0x29, 0x26, 0x24, 0x3a, 0x21, - 0x3c, 0x28, 0x21, 0x24, 0x21, 0x21, 0x1f, 0x21, - 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, - // Entry 100 - 13F - 0x21, 0x21, 0x2f, 0x21, 0x2e, 0x23, 0x33, 0x2f, - 0x24, 0x3b, 0x2f, 0x39, 0x38, 0x31, 0x2d, 0x3a, - 0x2c, 0x2e, 0x2d, 0x23, 0x2d, 0x2f, 0x28, 0x2f, - 0x27, 0x33, 0x34, 0x26, 0x24, 0x32, 0x22, 0x26, - 0x27, 0x22, 0x2d, 0x31, 0x3d, 0x29, 0x31, 0x3d, - 0x39, 0x29, 0x31, 0x24, 0x26, 0x29, 0x36, 0x2f, - 0x33, 0x2f, 0x21, 0x22, 0x21, 0x30, 0x28, 0x3d, - 0x23, 0x26, 0x21, 0x28, 0x26, 0x26, 0x31, 0x3b, - // Entry 140 - 17F - 0x29, 0x21, 0x29, 0x21, 0x21, 0x21, 0x21, 0x21, - 0x21, 0x21, 0x21, 0x21, 0x21, 0x23, 0x21, 0x21, - 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, - 0x21, 0x21, 0x21, 0x21, 0x21, 0x24, 0x24, 0x2f, - 0x23, 0x32, 0x2f, 0x27, 0x2f, 0x21, -} - -// regionInclusionBits is an array of bit vectors where every vector represents -// a set of region groupings. These sets are used to compute the distance -// between two regions for the purpose of language matching. -// Size: 584 bytes, 73 elements -var regionInclusionBits = [73]uint64{ - // Entry 0 - 1F - 0x0000000102400813, 0x00000000200007a3, 0x0000000000003844, 0x0000000040000808, - 0x00000000803c0011, 0x0000000020000022, 0x0000000040000844, 0x0000000020000082, - 0x0000000000000102, 0x0000000020000202, 0x0000000020000402, 0x000000004000384d, - 0x0000000000001804, 0x0000000040002804, 0x0000000000404000, 0x0000000000408000, - 0x0000000000410000, 0x0000000002020000, 0x0000000000040010, 0x0000000000080010, - 0x0000000000100010, 0x0000000000200010, 0x0000000001c1c001, 0x0000000000c00000, - 0x0000000001400000, 0x000000001e020001, 0x0000000006000000, 0x000000000a000000, - 0x0000000012000000, 0x00000000200006a2, 0x0000000040002848, 0x0000000080000010, - // Entry 20 - 3F - 0x0000000100000001, 0x0000000000000001, 0x0000000080000000, 0x0000000000020000, - 0x0000000001000000, 0x0000000000008000, 0x0000000000002000, 0x0000000000000200, - 0x0000000000000008, 0x0000000000200000, 0x0000000110000000, 0x0000000000040000, - 0x0000000008000000, 0x0000000000000020, 0x0000000104000000, 0x0000000000000080, - 0x0000000000001000, 0x0000000000010000, 0x0000000000000400, 0x0000000004000000, - 0x0000000000000040, 0x0000000010000000, 0x0000000000004000, 0x0000000101000000, - 0x0000000108000000, 0x0000000000000100, 0x0000000100020000, 0x0000000000080000, - 0x0000000000100000, 0x0000000000800000, 0x00000001ffffffff, 0x0000000122400fb3, - // Entry 40 - 5F - 0x00000001827c0813, 0x000000014240385f, 0x0000000103c1c813, 0x000000011e420813, - 0x0000000112000001, 0x0000000106000001, 0x0000000101400001, 0x000000010a000001, - 0x0000000102020001, -} - -// regionInclusionNext marks, for each entry in regionInclusionBits, the set of -// all groups that are reachable from the groups set in the respective entry. -// Size: 73 bytes, 73 elements -var regionInclusionNext = [73]uint8{ - // Entry 0 - 3F - 0x3e, 0x3f, 0x0b, 0x0b, 0x40, 0x01, 0x0b, 0x01, - 0x01, 0x01, 0x01, 0x41, 0x0b, 0x0b, 0x16, 0x16, - 0x16, 0x19, 0x04, 0x04, 0x04, 0x04, 0x42, 0x16, - 0x16, 0x43, 0x19, 0x19, 0x19, 0x01, 0x0b, 0x04, - 0x00, 0x00, 0x1f, 0x11, 0x18, 0x0f, 0x0d, 0x09, - 0x03, 0x15, 0x44, 0x12, 0x1b, 0x05, 0x45, 0x07, - 0x0c, 0x10, 0x0a, 0x1a, 0x06, 0x1c, 0x0e, 0x46, - 0x47, 0x08, 0x48, 0x13, 0x14, 0x17, 0x3e, 0x3e, - // Entry 40 - 7F - 0x3e, 0x3e, 0x3e, 0x3e, 0x43, 0x43, 0x42, 0x43, - 0x43, -} - -type parentRel struct { - lang uint16 - script uint16 - maxScript uint16 - toRegion uint16 - fromRegion []uint16 -} - -// Size: 414 bytes, 5 elements -var parents = [5]parentRel{ - 0: {lang: 0x139, script: 0x0, maxScript: 0x5a, toRegion: 0x1, fromRegion: []uint16{0x1a, 0x25, 0x26, 0x2f, 0x34, 0x36, 0x3d, 0x42, 0x46, 0x48, 0x49, 0x4a, 0x50, 0x52, 0x5c, 0x5d, 0x61, 0x64, 0x6d, 0x73, 0x74, 0x75, 0x7b, 0x7c, 0x7f, 0x80, 0x81, 0x83, 0x8c, 0x8d, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9f, 0xa0, 0xa4, 0xa7, 0xa9, 0xad, 0xb1, 0xb4, 0xb5, 0xbf, 0xc6, 0xca, 0xcb, 0xcc, 0xce, 0xd0, 0xd2, 0xd5, 0xd6, 0xdd, 0xdf, 0xe0, 0xe6, 0xe7, 0xe8, 0xeb, 0xf0, 0x107, 0x109, 0x10a, 0x10b, 0x10d, 0x10e, 0x112, 0x117, 0x11b, 0x11d, 0x11f, 0x125, 0x129, 0x12c, 0x12d, 0x12f, 0x131, 0x139, 0x13c, 0x13f, 0x142, 0x161, 0x162, 0x164}}, - 1: {lang: 0x139, script: 0x0, maxScript: 0x5a, toRegion: 0x1a, fromRegion: []uint16{0x2e, 0x4e, 0x60, 0x63, 0x72, 0xd9, 0x10c, 0x10f}}, - 2: {lang: 0x13e, script: 0x0, maxScript: 0x5a, toRegion: 0x1f, fromRegion: []uint16{0x2c, 0x3f, 0x41, 0x48, 0x51, 0x54, 0x56, 0x59, 0x65, 0x69, 0x89, 0x8f, 0xcf, 0xd8, 0xe2, 0xe4, 0xec, 0xf1, 0x11a, 0x135, 0x136, 0x13b}}, - 3: {lang: 0x3c0, script: 0x0, maxScript: 0x5a, toRegion: 0xee, fromRegion: []uint16{0x2a, 0x4e, 0x5a, 0x86, 0x8b, 0xb7, 0xc6, 0xd1, 0x118, 0x126}}, - 4: {lang: 0x529, script: 0x3c, maxScript: 0x3c, toRegion: 0x8d, fromRegion: []uint16{0xc6}}, -} - -// Total table size 30244 bytes (29KiB); checksum: B6B15F30 diff --git a/vendor/golang.org/x/text/internal/language/tags.go b/vendor/golang.org/x/text/internal/language/tags.go deleted file mode 100644 index e7afd31..0000000 --- a/vendor/golang.org/x/text/internal/language/tags.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2013 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 language - -// MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. -// It simplifies safe initialization of Tag values. -func MustParse(s string) Tag { - t, err := Parse(s) - if err != nil { - panic(err) - } - return t -} - -// MustParseBase is like ParseBase, but panics if the given base cannot be parsed. -// It simplifies safe initialization of Base values. -func MustParseBase(s string) Language { - b, err := ParseBase(s) - if err != nil { - panic(err) - } - return b -} - -// MustParseScript is like ParseScript, but panics if the given script cannot be -// parsed. It simplifies safe initialization of Script values. -func MustParseScript(s string) Script { - scr, err := ParseScript(s) - if err != nil { - panic(err) - } - return scr -} - -// MustParseRegion is like ParseRegion, but panics if the given region cannot be -// parsed. It simplifies safe initialization of Region values. -func MustParseRegion(s string) Region { - r, err := ParseRegion(s) - if err != nil { - panic(err) - } - return r -} - -// Und is the root language. -var Und Tag diff --git a/vendor/golang.org/x/text/internal/tag/tag.go b/vendor/golang.org/x/text/internal/tag/tag.go deleted file mode 100644 index b5d3488..0000000 --- a/vendor/golang.org/x/text/internal/tag/tag.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2015 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 tag contains functionality handling tags and related data. -package tag // import "golang.org/x/text/internal/tag" - -import "sort" - -// An Index converts tags to a compact numeric value. -// -// All elements are of size 4. Tags may be up to 4 bytes long. Excess bytes can -// be used to store additional information about the tag. -type Index string - -// Elem returns the element data at the given index. -func (s Index) Elem(x int) string { - return string(s[x*4 : x*4+4]) -} - -// Index reports the index of the given key or -1 if it could not be found. -// Only the first len(key) bytes from the start of the 4-byte entries will be -// considered for the search and the first match in Index will be returned. -func (s Index) Index(key []byte) int { - n := len(key) - // search the index of the first entry with an equal or higher value than - // key in s. - index := sort.Search(len(s)/4, func(i int) bool { - return cmp(s[i*4:i*4+n], key) != -1 - }) - i := index * 4 - if cmp(s[i:i+len(key)], key) != 0 { - return -1 - } - return index -} - -// Next finds the next occurrence of key after index x, which must have been -// obtained from a call to Index using the same key. It returns x+1 or -1. -func (s Index) Next(key []byte, x int) int { - if x++; x*4 < len(s) && cmp(s[x*4:x*4+len(key)], key) == 0 { - return x - } - return -1 -} - -// cmp returns an integer comparing a and b lexicographically. -func cmp(a Index, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - for i, c := range b[:n] { - switch { - case a[i] > c: - return 1 - case a[i] < c: - return -1 - } - } - switch { - case len(a) < len(b): - return -1 - case len(a) > len(b): - return 1 - } - return 0 -} - -// Compare returns an integer comparing a and b lexicographically. -func Compare(a string, b []byte) int { - return cmp(Index(a), b) -} - -// FixCase reformats b to the same pattern of cases as form. -// If returns false if string b is malformed. -func FixCase(form string, b []byte) bool { - if len(form) != len(b) { - return false - } - for i, c := range b { - if form[i] <= 'Z' { - if c >= 'a' { - c -= 'z' - 'Z' - } - if c < 'A' || 'Z' < c { - return false - } - } else { - if c <= 'Z' { - c += 'z' - 'Z' - } - if c < 'a' || 'z' < c { - return false - } - } - b[i] = c - } - return true -} diff --git a/vendor/golang.org/x/text/language/coverage.go b/vendor/golang.org/x/text/language/coverage.go deleted file mode 100644 index a24fd1a..0000000 --- a/vendor/golang.org/x/text/language/coverage.go +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright 2014 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 language - -import ( - "fmt" - "sort" - - "golang.org/x/text/internal/language" -) - -// The Coverage interface is used to define the level of coverage of an -// internationalization service. Note that not all types are supported by all -// services. As lists may be generated on the fly, it is recommended that users -// of a Coverage cache the results. -type Coverage interface { - // Tags returns the list of supported tags. - Tags() []Tag - - // BaseLanguages returns the list of supported base languages. - BaseLanguages() []Base - - // Scripts returns the list of supported scripts. - Scripts() []Script - - // Regions returns the list of supported regions. - Regions() []Region -} - -var ( - // Supported defines a Coverage that lists all supported subtags. Tags - // always returns nil. - Supported Coverage = allSubtags{} -) - -// TODO: -// - Support Variants, numbering systems. -// - CLDR coverage levels. -// - Set of common tags defined in this package. - -type allSubtags struct{} - -// Regions returns the list of supported regions. As all regions are in a -// consecutive range, it simply returns a slice of numbers in increasing order. -// The "undefined" region is not returned. -func (s allSubtags) Regions() []Region { - reg := make([]Region, language.NumRegions) - for i := range reg { - reg[i] = Region{language.Region(i + 1)} - } - return reg -} - -// Scripts returns the list of supported scripts. As all scripts are in a -// consecutive range, it simply returns a slice of numbers in increasing order. -// The "undefined" script is not returned. -func (s allSubtags) Scripts() []Script { - scr := make([]Script, language.NumScripts) - for i := range scr { - scr[i] = Script{language.Script(i + 1)} - } - return scr -} - -// BaseLanguages returns the list of all supported base languages. It generates -// the list by traversing the internal structures. -func (s allSubtags) BaseLanguages() []Base { - bs := language.BaseLanguages() - base := make([]Base, len(bs)) - for i, b := range bs { - base[i] = Base{b} - } - return base -} - -// Tags always returns nil. -func (s allSubtags) Tags() []Tag { - return nil -} - -// coverage is used by NewCoverage which is used as a convenient way for -// creating Coverage implementations for partially defined data. Very often a -// package will only need to define a subset of slices. coverage provides a -// convenient way to do this. Moreover, packages using NewCoverage, instead of -// their own implementation, will not break if later new slice types are added. -type coverage struct { - tags func() []Tag - bases func() []Base - scripts func() []Script - regions func() []Region -} - -func (s *coverage) Tags() []Tag { - if s.tags == nil { - return nil - } - return s.tags() -} - -// bases implements sort.Interface and is used to sort base languages. -type bases []Base - -func (b bases) Len() int { - return len(b) -} - -func (b bases) Swap(i, j int) { - b[i], b[j] = b[j], b[i] -} - -func (b bases) Less(i, j int) bool { - return b[i].langID < b[j].langID -} - -// BaseLanguages returns the result from calling s.bases if it is specified or -// otherwise derives the set of supported base languages from tags. -func (s *coverage) BaseLanguages() []Base { - if s.bases == nil { - tags := s.Tags() - if len(tags) == 0 { - return nil - } - a := make([]Base, len(tags)) - for i, t := range tags { - a[i] = Base{language.Language(t.lang())} - } - sort.Sort(bases(a)) - k := 0 - for i := 1; i < len(a); i++ { - if a[k] != a[i] { - k++ - a[k] = a[i] - } - } - return a[:k+1] - } - return s.bases() -} - -func (s *coverage) Scripts() []Script { - if s.scripts == nil { - return nil - } - return s.scripts() -} - -func (s *coverage) Regions() []Region { - if s.regions == nil { - return nil - } - return s.regions() -} - -// NewCoverage returns a Coverage for the given lists. It is typically used by -// packages providing internationalization services to define their level of -// coverage. A list may be of type []T or func() []T, where T is either Tag, -// Base, Script or Region. The returned Coverage derives the value for Bases -// from Tags if no func or slice for []Base is specified. For other unspecified -// types the returned Coverage will return nil for the respective methods. -func NewCoverage(list ...interface{}) Coverage { - s := &coverage{} - for _, x := range list { - switch v := x.(type) { - case func() []Base: - s.bases = v - case func() []Script: - s.scripts = v - case func() []Region: - s.regions = v - case func() []Tag: - s.tags = v - case []Base: - s.bases = func() []Base { return v } - case []Script: - s.scripts = func() []Script { return v } - case []Region: - s.regions = func() []Region { return v } - case []Tag: - s.tags = func() []Tag { return v } - default: - panic(fmt.Sprintf("language: unsupported set type %T", v)) - } - } - return s -} diff --git a/vendor/golang.org/x/text/language/doc.go b/vendor/golang.org/x/text/language/doc.go deleted file mode 100644 index 212b77c..0000000 --- a/vendor/golang.org/x/text/language/doc.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2017 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 language implements BCP 47 language tags and related functionality. -// -// The most important function of package language is to match a list of -// user-preferred languages to a list of supported languages. -// It alleviates the developer of dealing with the complexity of this process -// and provides the user with the best experience -// (see https://blog.golang.org/matchlang). -// -// # Matching preferred against supported languages -// -// A Matcher for an application that supports English, Australian English, -// Danish, and standard Mandarin can be created as follows: -// -// var matcher = language.NewMatcher([]language.Tag{ -// language.English, // The first language is used as fallback. -// language.MustParse("en-AU"), -// language.Danish, -// language.Chinese, -// }) -// -// This list of supported languages is typically implied by the languages for -// which there exists translations of the user interface. -// -// User-preferred languages usually come as a comma-separated list of BCP 47 -// language tags. -// The MatchString finds best matches for such strings: -// -// handler(w http.ResponseWriter, r *http.Request) { -// lang, _ := r.Cookie("lang") -// accept := r.Header.Get("Accept-Language") -// tag, _ := language.MatchStrings(matcher, lang.String(), accept) -// -// // tag should now be used for the initialization of any -// // locale-specific service. -// } -// -// The Matcher's Match method can be used to match Tags directly. -// -// Matchers are aware of the intricacies of equivalence between languages, such -// as deprecated subtags, legacy tags, macro languages, mutual -// intelligibility between scripts and languages, and transparently passing -// BCP 47 user configuration. -// For instance, it will know that a reader of Bokmål Danish can read Norwegian -// and will know that Cantonese ("yue") is a good match for "zh-HK". -// -// # Using match results -// -// To guarantee a consistent user experience to the user it is important to -// use the same language tag for the selection of any locale-specific services. -// For example, it is utterly confusing to substitute spelled-out numbers -// or dates in one language in text of another language. -// More subtly confusing is using the wrong sorting order or casing -// algorithm for a certain language. -// -// All the packages in x/text that provide locale-specific services -// (e.g. collate, cases) should be initialized with the tag that was -// obtained at the start of an interaction with the user. -// -// Note that Tag that is returned by Match and MatchString may differ from any -// of the supported languages, as it may contain carried over settings from -// the user tags. -// This may be inconvenient when your application has some additional -// locale-specific data for your supported languages. -// Match and MatchString both return the index of the matched supported tag -// to simplify associating such data with the matched tag. -// -// # Canonicalization -// -// If one uses the Matcher to compare languages one does not need to -// worry about canonicalization. -// -// The meaning of a Tag varies per application. The language package -// therefore delays canonicalization and preserves information as much -// as possible. The Matcher, however, will always take into account that -// two different tags may represent the same language. -// -// By default, only legacy and deprecated tags are converted into their -// canonical equivalent. All other information is preserved. This approach makes -// the confidence scores more accurate and allows matchers to distinguish -// between variants that are otherwise lost. -// -// As a consequence, two tags that should be treated as identical according to -// BCP 47 or CLDR, like "en-Latn" and "en", will be represented differently. The -// Matcher handles such distinctions, though, and is aware of the -// equivalence relations. The CanonType type can be used to alter the -// canonicalization form. -// -// # References -// -// BCP 47 - Tags for Identifying Languages http://tools.ietf.org/html/bcp47 -package language // import "golang.org/x/text/language" - -// TODO: explanation on how to match languages for your own locale-specific -// service. diff --git a/vendor/golang.org/x/text/language/language.go b/vendor/golang.org/x/text/language/language.go deleted file mode 100644 index 289b3a3..0000000 --- a/vendor/golang.org/x/text/language/language.go +++ /dev/null @@ -1,605 +0,0 @@ -// Copyright 2013 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. - -//go:generate go run gen.go -output tables.go - -package language - -// TODO: Remove above NOTE after: -// - verifying that tables are dropped correctly (most notably matcher tables). - -import ( - "strings" - - "golang.org/x/text/internal/language" - "golang.org/x/text/internal/language/compact" -) - -// Tag represents a BCP 47 language tag. It is used to specify an instance of a -// specific language or locale. All language tag values are guaranteed to be -// well-formed. -type Tag compact.Tag - -func makeTag(t language.Tag) (tag Tag) { - return Tag(compact.Make(t)) -} - -func (t *Tag) tag() language.Tag { - return (*compact.Tag)(t).Tag() -} - -func (t *Tag) isCompact() bool { - return (*compact.Tag)(t).IsCompact() -} - -// TODO: improve performance. -func (t *Tag) lang() language.Language { return t.tag().LangID } -func (t *Tag) region() language.Region { return t.tag().RegionID } -func (t *Tag) script() language.Script { return t.tag().ScriptID } - -// Make is a convenience wrapper for Parse that omits the error. -// In case of an error, a sensible default is returned. -func Make(s string) Tag { - return Default.Make(s) -} - -// Make is a convenience wrapper for c.Parse that omits the error. -// In case of an error, a sensible default is returned. -func (c CanonType) Make(s string) Tag { - t, _ := c.Parse(s) - return t -} - -// Raw returns the raw base language, script and region, without making an -// attempt to infer their values. -func (t Tag) Raw() (b Base, s Script, r Region) { - tt := t.tag() - return Base{tt.LangID}, Script{tt.ScriptID}, Region{tt.RegionID} -} - -// IsRoot returns true if t is equal to language "und". -func (t Tag) IsRoot() bool { - return compact.Tag(t).IsRoot() -} - -// CanonType can be used to enable or disable various types of canonicalization. -type CanonType int - -const ( - // Replace deprecated base languages with their preferred replacements. - DeprecatedBase CanonType = 1 << iota - // Replace deprecated scripts with their preferred replacements. - DeprecatedScript - // Replace deprecated regions with their preferred replacements. - DeprecatedRegion - // Remove redundant scripts. - SuppressScript - // Normalize legacy encodings. This includes legacy languages defined in - // CLDR as well as bibliographic codes defined in ISO-639. - Legacy - // Map the dominant language of a macro language group to the macro language - // subtag. For example cmn -> zh. - Macro - // The CLDR flag should be used if full compatibility with CLDR is required. - // There are a few cases where language.Tag may differ from CLDR. To follow all - // of CLDR's suggestions, use All|CLDR. - CLDR - - // Raw can be used to Compose or Parse without Canonicalization. - Raw CanonType = 0 - - // Replace all deprecated tags with their preferred replacements. - Deprecated = DeprecatedBase | DeprecatedScript | DeprecatedRegion - - // All canonicalizations recommended by BCP 47. - BCP47 = Deprecated | SuppressScript - - // All canonicalizations. - All = BCP47 | Legacy | Macro - - // Default is the canonicalization used by Parse, Make and Compose. To - // preserve as much information as possible, canonicalizations that remove - // potentially valuable information are not included. The Matcher is - // designed to recognize similar tags that would be the same if - // they were canonicalized using All. - Default = Deprecated | Legacy - - canonLang = DeprecatedBase | Legacy | Macro - - // TODO: LikelyScript, LikelyRegion: suppress similar to ICU. -) - -// canonicalize returns the canonicalized equivalent of the tag and -// whether there was any change. -func canonicalize(c CanonType, t language.Tag) (language.Tag, bool) { - if c == Raw { - return t, false - } - changed := false - if c&SuppressScript != 0 { - if t.LangID.SuppressScript() == t.ScriptID { - t.ScriptID = 0 - changed = true - } - } - if c&canonLang != 0 { - for { - if l, aliasType := t.LangID.Canonicalize(); l != t.LangID { - switch aliasType { - case language.Legacy: - if c&Legacy != 0 { - if t.LangID == _sh && t.ScriptID == 0 { - t.ScriptID = _Latn - } - t.LangID = l - changed = true - } - case language.Macro: - if c&Macro != 0 { - // We deviate here from CLDR. The mapping "nb" -> "no" - // qualifies as a typical Macro language mapping. However, - // for legacy reasons, CLDR maps "no", the macro language - // code for Norwegian, to the dominant variant "nb". This - // change is currently under consideration for CLDR as well. - // See https://unicode.org/cldr/trac/ticket/2698 and also - // https://unicode.org/cldr/trac/ticket/1790 for some of the - // practical implications. TODO: this check could be removed - // if CLDR adopts this change. - if c&CLDR == 0 || t.LangID != _nb { - changed = true - t.LangID = l - } - } - case language.Deprecated: - if c&DeprecatedBase != 0 { - if t.LangID == _mo && t.RegionID == 0 { - t.RegionID = _MD - } - t.LangID = l - changed = true - // Other canonicalization types may still apply. - continue - } - } - } else if c&Legacy != 0 && t.LangID == _no && c&CLDR != 0 { - t.LangID = _nb - changed = true - } - break - } - } - if c&DeprecatedScript != 0 { - if t.ScriptID == _Qaai { - changed = true - t.ScriptID = _Zinh - } - } - if c&DeprecatedRegion != 0 { - if r := t.RegionID.Canonicalize(); r != t.RegionID { - changed = true - t.RegionID = r - } - } - return t, changed -} - -// Canonicalize returns the canonicalized equivalent of the tag. -func (c CanonType) Canonicalize(t Tag) (Tag, error) { - // First try fast path. - if t.isCompact() { - if _, changed := canonicalize(c, compact.Tag(t).Tag()); !changed { - return t, nil - } - } - // It is unlikely that one will canonicalize a tag after matching. So do - // a slow but simple approach here. - if tag, changed := canonicalize(c, t.tag()); changed { - tag.RemakeString() - return makeTag(tag), nil - } - return t, nil - -} - -// Confidence indicates the level of certainty for a given return value. -// For example, Serbian may be written in Cyrillic or Latin script. -// The confidence level indicates whether a value was explicitly specified, -// whether it is typically the only possible value, or whether there is -// an ambiguity. -type Confidence int - -const ( - No Confidence = iota // full confidence that there was no match - Low // most likely value picked out of a set of alternatives - High // value is generally assumed to be the correct match - Exact // exact match or explicitly specified value -) - -var confName = []string{"No", "Low", "High", "Exact"} - -func (c Confidence) String() string { - return confName[c] -} - -// String returns the canonical string representation of the language tag. -func (t Tag) String() string { - return t.tag().String() -} - -// MarshalText implements encoding.TextMarshaler. -func (t Tag) MarshalText() (text []byte, err error) { - return t.tag().MarshalText() -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (t *Tag) UnmarshalText(text []byte) error { - var tag language.Tag - err := tag.UnmarshalText(text) - *t = makeTag(tag) - return err -} - -// Base returns the base language of the language tag. If the base language is -// unspecified, an attempt will be made to infer it from the context. -// It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. -func (t Tag) Base() (Base, Confidence) { - if b := t.lang(); b != 0 { - return Base{b}, Exact - } - tt := t.tag() - c := High - if tt.ScriptID == 0 && !tt.RegionID.IsCountry() { - c = Low - } - if tag, err := tt.Maximize(); err == nil && tag.LangID != 0 { - return Base{tag.LangID}, c - } - return Base{0}, No -} - -// Script infers the script for the language tag. If it was not explicitly given, it will infer -// a most likely candidate. -// If more than one script is commonly used for a language, the most likely one -// is returned with a low confidence indication. For example, it returns (Cyrl, Low) -// for Serbian. -// If a script cannot be inferred (Zzzz, No) is returned. We do not use Zyyy (undetermined) -// as one would suspect from the IANA registry for BCP 47. In a Unicode context Zyyy marks -// common characters (like 1, 2, 3, '.', etc.) and is therefore more like multiple scripts. -// See https://www.unicode.org/reports/tr24/#Values for more details. Zzzz is also used for -// unknown value in CLDR. (Zzzz, Exact) is returned if Zzzz was explicitly specified. -// Note that an inferred script is never guaranteed to be the correct one. Latin is -// almost exclusively used for Afrikaans, but Arabic has been used for some texts -// in the past. Also, the script that is commonly used may change over time. -// It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. -func (t Tag) Script() (Script, Confidence) { - if scr := t.script(); scr != 0 { - return Script{scr}, Exact - } - tt := t.tag() - sc, c := language.Script(_Zzzz), No - if scr := tt.LangID.SuppressScript(); scr != 0 { - // Note: it is not always the case that a language with a suppress - // script value is only written in one script (e.g. kk, ms, pa). - if tt.RegionID == 0 { - return Script{scr}, High - } - sc, c = scr, High - } - if tag, err := tt.Maximize(); err == nil { - if tag.ScriptID != sc { - sc, c = tag.ScriptID, Low - } - } else { - tt, _ = canonicalize(Deprecated|Macro, tt) - if tag, err := tt.Maximize(); err == nil && tag.ScriptID != sc { - sc, c = tag.ScriptID, Low - } - } - return Script{sc}, c -} - -// Region returns the region for the language tag. If it was not explicitly given, it will -// infer a most likely candidate from the context. -// It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. -func (t Tag) Region() (Region, Confidence) { - if r := t.region(); r != 0 { - return Region{r}, Exact - } - tt := t.tag() - if tt, err := tt.Maximize(); err == nil { - return Region{tt.RegionID}, Low // TODO: differentiate between high and low. - } - tt, _ = canonicalize(Deprecated|Macro, tt) - if tag, err := tt.Maximize(); err == nil { - return Region{tag.RegionID}, Low - } - return Region{_ZZ}, No // TODO: return world instead of undetermined? -} - -// Variants returns the variants specified explicitly for this language tag. -// or nil if no variant was specified. -func (t Tag) Variants() []Variant { - if !compact.Tag(t).MayHaveVariants() { - return nil - } - v := []Variant{} - x, str := "", t.tag().Variants() - for str != "" { - x, str = nextToken(str) - v = append(v, Variant{x}) - } - return v -} - -// Parent returns the CLDR parent of t. In CLDR, missing fields in data for a -// specific language are substituted with fields from the parent language. -// The parent for a language may change for newer versions of CLDR. -// -// Parent returns a tag for a less specific language that is mutually -// intelligible or Und if there is no such language. This may not be the same as -// simply stripping the last BCP 47 subtag. For instance, the parent of "zh-TW" -// is "zh-Hant", and the parent of "zh-Hant" is "und". -func (t Tag) Parent() Tag { - return Tag(compact.Tag(t).Parent()) -} - -// returns token t and the rest of the string. -func nextToken(s string) (t, tail string) { - p := strings.Index(s[1:], "-") - if p == -1 { - return s[1:], "" - } - p++ - return s[1:p], s[p:] -} - -// Extension is a single BCP 47 extension. -type Extension struct { - s string -} - -// String returns the string representation of the extension, including the -// type tag. -func (e Extension) String() string { - return e.s -} - -// ParseExtension parses s as an extension and returns it on success. -func ParseExtension(s string) (e Extension, err error) { - ext, err := language.ParseExtension(s) - return Extension{ext}, err -} - -// Type returns the one-byte extension type of e. It returns 0 for the zero -// exception. -func (e Extension) Type() byte { - if e.s == "" { - return 0 - } - return e.s[0] -} - -// Tokens returns the list of tokens of e. -func (e Extension) Tokens() []string { - return strings.Split(e.s, "-") -} - -// Extension returns the extension of type x for tag t. It will return -// false for ok if t does not have the requested extension. The returned -// extension will be invalid in this case. -func (t Tag) Extension(x byte) (ext Extension, ok bool) { - if !compact.Tag(t).MayHaveExtensions() { - return Extension{}, false - } - e, ok := t.tag().Extension(x) - return Extension{e}, ok -} - -// Extensions returns all extensions of t. -func (t Tag) Extensions() []Extension { - if !compact.Tag(t).MayHaveExtensions() { - return nil - } - e := []Extension{} - for _, ext := range t.tag().Extensions() { - e = append(e, Extension{ext}) - } - return e -} - -// TypeForKey returns the type associated with the given key, where key and type -// are of the allowed values defined for the Unicode locale extension ('u') in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -// TypeForKey will traverse the inheritance chain to get the correct value. -// -// If there are multiple types associated with a key, only the first will be -// returned. If there is no type associated with a key, it returns the empty -// string. -func (t Tag) TypeForKey(key string) string { - if !compact.Tag(t).MayHaveExtensions() { - if key != "rg" && key != "va" { - return "" - } - } - return t.tag().TypeForKey(key) -} - -// SetTypeForKey returns a new Tag with the key set to type, where key and type -// are of the allowed values defined for the Unicode locale extension ('u') in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -// An empty value removes an existing pair with the same key. -func (t Tag) SetTypeForKey(key, value string) (Tag, error) { - tt, err := t.tag().SetTypeForKey(key, value) - return makeTag(tt), err -} - -// NumCompactTags is the number of compact tags. The maximum tag is -// NumCompactTags-1. -const NumCompactTags = compact.NumCompactTags - -// CompactIndex returns an index, where 0 <= index < NumCompactTags, for tags -// for which data exists in the text repository.The index will change over time -// and should not be stored in persistent storage. If t does not match a compact -// index, exact will be false and the compact index will be returned for the -// first match after repeatedly taking the Parent of t. -func CompactIndex(t Tag) (index int, exact bool) { - id, exact := compact.LanguageID(compact.Tag(t)) - return int(id), exact -} - -var root = language.Tag{} - -// Base is an ISO 639 language code, used for encoding the base language -// of a language tag. -type Base struct { - langID language.Language -} - -// ParseBase parses a 2- or 3-letter ISO 639 code. -// It returns a ValueError if s is a well-formed but unknown language identifier -// or another error if another error occurred. -func ParseBase(s string) (Base, error) { - l, err := language.ParseBase(s) - return Base{l}, err -} - -// String returns the BCP 47 representation of the base language. -func (b Base) String() string { - return b.langID.String() -} - -// ISO3 returns the ISO 639-3 language code. -func (b Base) ISO3() string { - return b.langID.ISO3() -} - -// IsPrivateUse reports whether this language code is reserved for private use. -func (b Base) IsPrivateUse() bool { - return b.langID.IsPrivateUse() -} - -// Script is a 4-letter ISO 15924 code for representing scripts. -// It is idiomatically represented in title case. -type Script struct { - scriptID language.Script -} - -// ParseScript parses a 4-letter ISO 15924 code. -// It returns a ValueError if s is a well-formed but unknown script identifier -// or another error if another error occurred. -func ParseScript(s string) (Script, error) { - sc, err := language.ParseScript(s) - return Script{sc}, err -} - -// String returns the script code in title case. -// It returns "Zzzz" for an unspecified script. -func (s Script) String() string { - return s.scriptID.String() -} - -// IsPrivateUse reports whether this script code is reserved for private use. -func (s Script) IsPrivateUse() bool { - return s.scriptID.IsPrivateUse() -} - -// Region is an ISO 3166-1 or UN M.49 code for representing countries and regions. -type Region struct { - regionID language.Region -} - -// EncodeM49 returns the Region for the given UN M.49 code. -// It returns an error if r is not a valid code. -func EncodeM49(r int) (Region, error) { - rid, err := language.EncodeM49(r) - return Region{rid}, err -} - -// ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code. -// It returns a ValueError if s is a well-formed but unknown region identifier -// or another error if another error occurred. -func ParseRegion(s string) (Region, error) { - r, err := language.ParseRegion(s) - return Region{r}, err -} - -// String returns the BCP 47 representation for the region. -// It returns "ZZ" for an unspecified region. -func (r Region) String() string { - return r.regionID.String() -} - -// ISO3 returns the 3-letter ISO code of r. -// Note that not all regions have a 3-letter ISO code. -// In such cases this method returns "ZZZ". -func (r Region) ISO3() string { - return r.regionID.ISO3() -} - -// M49 returns the UN M.49 encoding of r, or 0 if this encoding -// is not defined for r. -func (r Region) M49() int { - return r.regionID.M49() -} - -// IsPrivateUse reports whether r has the ISO 3166 User-assigned status. This -// may include private-use tags that are assigned by CLDR and used in this -// implementation. So IsPrivateUse and IsCountry can be simultaneously true. -func (r Region) IsPrivateUse() bool { - return r.regionID.IsPrivateUse() -} - -// IsCountry returns whether this region is a country or autonomous area. This -// includes non-standard definitions from CLDR. -func (r Region) IsCountry() bool { - return r.regionID.IsCountry() -} - -// IsGroup returns whether this region defines a collection of regions. This -// includes non-standard definitions from CLDR. -func (r Region) IsGroup() bool { - return r.regionID.IsGroup() -} - -// Contains returns whether Region c is contained by Region r. It returns true -// if c == r. -func (r Region) Contains(c Region) bool { - return r.regionID.Contains(c.regionID) -} - -// TLD returns the country code top-level domain (ccTLD). UK is returned for GB. -// In all other cases it returns either the region itself or an error. -// -// This method may return an error for a region for which there exists a -// canonical form with a ccTLD. To get that ccTLD canonicalize r first. The -// region will already be canonicalized it was obtained from a Tag that was -// obtained using any of the default methods. -func (r Region) TLD() (Region, error) { - tld, err := r.regionID.TLD() - return Region{tld}, err -} - -// Canonicalize returns the region or a possible replacement if the region is -// deprecated. It will not return a replacement for deprecated regions that -// are split into multiple regions. -func (r Region) Canonicalize() Region { - return Region{r.regionID.Canonicalize()} -} - -// Variant represents a registered variant of a language as defined by BCP 47. -type Variant struct { - variant string -} - -// ParseVariant parses and returns a Variant. An error is returned if s is not -// a valid variant. -func ParseVariant(s string) (Variant, error) { - v, err := language.ParseVariant(s) - return Variant{v.String()}, err -} - -// String returns the string representation of the variant. -func (v Variant) String() string { - return v.variant -} diff --git a/vendor/golang.org/x/text/language/match.go b/vendor/golang.org/x/text/language/match.go deleted file mode 100644 index ee45f49..0000000 --- a/vendor/golang.org/x/text/language/match.go +++ /dev/null @@ -1,735 +0,0 @@ -// Copyright 2013 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 language - -import ( - "errors" - "strings" - - "golang.org/x/text/internal/language" -) - -// A MatchOption configures a Matcher. -type MatchOption func(*matcher) - -// PreferSameScript will, in the absence of a match, result in the first -// preferred tag with the same script as a supported tag to match this supported -// tag. The default is currently true, but this may change in the future. -func PreferSameScript(preferSame bool) MatchOption { - return func(m *matcher) { m.preferSameScript = preferSame } -} - -// TODO(v1.0.0): consider making Matcher a concrete type, instead of interface. -// There doesn't seem to be too much need for multiple types. -// Making it a concrete type allows MatchStrings to be a method, which will -// improve its discoverability. - -// MatchStrings parses and matches the given strings until one of them matches -// the language in the Matcher. A string may be an Accept-Language header as -// handled by ParseAcceptLanguage. The default language is returned if no -// other language matched. -func MatchStrings(m Matcher, lang ...string) (tag Tag, index int) { - for _, accept := range lang { - desired, _, err := ParseAcceptLanguage(accept) - if err != nil { - continue - } - if tag, index, conf := m.Match(desired...); conf != No { - return tag, index - } - } - tag, index, _ = m.Match() - return -} - -// Matcher is the interface that wraps the Match method. -// -// Match returns the best match for any of the given tags, along with -// a unique index associated with the returned tag and a confidence -// score. -type Matcher interface { - Match(t ...Tag) (tag Tag, index int, c Confidence) -} - -// Comprehends reports the confidence score for a speaker of a given language -// to being able to comprehend the written form of an alternative language. -func Comprehends(speaker, alternative Tag) Confidence { - _, _, c := NewMatcher([]Tag{alternative}).Match(speaker) - return c -} - -// NewMatcher returns a Matcher that matches an ordered list of preferred tags -// against a list of supported tags based on written intelligibility, closeness -// of dialect, equivalence of subtags and various other rules. It is initialized -// with the list of supported tags. The first element is used as the default -// value in case no match is found. -// -// Its Match method matches the first of the given Tags to reach a certain -// confidence threshold. The tags passed to Match should therefore be specified -// in order of preference. Extensions are ignored for matching. -// -// The index returned by the Match method corresponds to the index of the -// matched tag in t, but is augmented with the Unicode extension ('u')of the -// corresponding preferred tag. This allows user locale options to be passed -// transparently. -func NewMatcher(t []Tag, options ...MatchOption) Matcher { - return newMatcher(t, options) -} - -func (m *matcher) Match(want ...Tag) (t Tag, index int, c Confidence) { - var tt language.Tag - match, w, c := m.getBest(want...) - if match != nil { - tt, index = match.tag, match.index - } else { - // TODO: this should be an option - tt = m.default_.tag - if m.preferSameScript { - outer: - for _, w := range want { - script, _ := w.Script() - if script.scriptID == 0 { - // Don't do anything if there is no script, such as with - // private subtags. - continue - } - for i, h := range m.supported { - if script.scriptID == h.maxScript { - tt, index = h.tag, i - break outer - } - } - } - } - // TODO: select first language tag based on script. - } - if w.RegionID != tt.RegionID && w.RegionID != 0 { - if w.RegionID != 0 && tt.RegionID != 0 && tt.RegionID.Contains(w.RegionID) { - tt.RegionID = w.RegionID - tt.RemakeString() - } else if r := w.RegionID.String(); len(r) == 2 { - // TODO: also filter macro and deprecated. - tt, _ = tt.SetTypeForKey("rg", strings.ToLower(r)+"zzzz") - } - } - // Copy options from the user-provided tag into the result tag. This is hard - // to do after the fact, so we do it here. - // TODO: add in alternative variants to -u-va-. - // TODO: add preferred region to -u-rg-. - if e := w.Extensions(); len(e) > 0 { - b := language.Builder{} - b.SetTag(tt) - for _, e := range e { - b.AddExt(e) - } - tt = b.Make() - } - return makeTag(tt), index, c -} - -// ErrMissingLikelyTagsData indicates no information was available -// to compute likely values of missing tags. -var ErrMissingLikelyTagsData = errors.New("missing likely tags data") - -// func (t *Tag) setTagsFrom(id Tag) { -// t.LangID = id.LangID -// t.ScriptID = id.ScriptID -// t.RegionID = id.RegionID -// } - -// Tag Matching -// CLDR defines an algorithm for finding the best match between two sets of language -// tags. The basic algorithm defines how to score a possible match and then find -// the match with the best score -// (see https://www.unicode.org/reports/tr35/#LanguageMatching). -// Using scoring has several disadvantages. The scoring obfuscates the importance of -// the various factors considered, making the algorithm harder to understand. Using -// scoring also requires the full score to be computed for each pair of tags. -// -// We will use a different algorithm which aims to have the following properties: -// - clarity on the precedence of the various selection factors, and -// - improved performance by allowing early termination of a comparison. -// -// Matching algorithm (overview) -// Input: -// - supported: a set of supported tags -// - default: the default tag to return in case there is no match -// - desired: list of desired tags, ordered by preference, starting with -// the most-preferred. -// -// Algorithm: -// 1) Set the best match to the lowest confidence level -// 2) For each tag in "desired": -// a) For each tag in "supported": -// 1) compute the match between the two tags. -// 2) if the match is better than the previous best match, replace it -// with the new match. (see next section) -// b) if the current best match is Exact and pin is true the result will be -// frozen to the language found thusfar, although better matches may -// still be found for the same language. -// 3) If the best match so far is below a certain threshold, return "default". -// -// Ranking: -// We use two phases to determine whether one pair of tags are a better match -// than another pair of tags. First, we determine a rough confidence level. If the -// levels are different, the one with the highest confidence wins. -// Second, if the rough confidence levels are identical, we use a set of tie-breaker -// rules. -// -// The confidence level of matching a pair of tags is determined by finding the -// lowest confidence level of any matches of the corresponding subtags (the -// result is deemed as good as its weakest link). -// We define the following levels: -// Exact - An exact match of a subtag, before adding likely subtags. -// MaxExact - An exact match of a subtag, after adding likely subtags. -// [See Note 2]. -// High - High level of mutual intelligibility between different subtag -// variants. -// Low - Low level of mutual intelligibility between different subtag -// variants. -// No - No mutual intelligibility. -// -// The following levels can occur for each type of subtag: -// Base: Exact, MaxExact, High, Low, No -// Script: Exact, MaxExact [see Note 3], Low, No -// Region: Exact, MaxExact, High -// Variant: Exact, High -// Private: Exact, No -// -// Any result with a confidence level of Low or higher is deemed a possible match. -// Once a desired tag matches any of the supported tags with a level of MaxExact -// or higher, the next desired tag is not considered (see Step 2.b). -// Note that CLDR provides languageMatching data that defines close equivalence -// classes for base languages, scripts and regions. -// -// Tie-breaking -// If we get the same confidence level for two matches, we apply a sequence of -// tie-breaking rules. The first that succeeds defines the result. The rules are -// applied in the following order. -// 1) Original language was defined and was identical. -// 2) Original region was defined and was identical. -// 3) Distance between two maximized regions was the smallest. -// 4) Original script was defined and was identical. -// 5) Distance from want tag to have tag using the parent relation [see Note 5.] -// If there is still no winner after these rules are applied, the first match -// found wins. -// -// Notes: -// [2] In practice, as matching of Exact is done in a separate phase from -// matching the other levels, we reuse the Exact level to mean MaxExact in -// the second phase. As a consequence, we only need the levels defined by -// the Confidence type. The MaxExact confidence level is mapped to High in -// the public API. -// [3] We do not differentiate between maximized script values that were derived -// from suppressScript versus most likely tag data. We determined that in -// ranking the two, one ranks just after the other. Moreover, the two cannot -// occur concurrently. As a consequence, they are identical for practical -// purposes. -// [4] In case of deprecated, macro-equivalents and legacy mappings, we assign -// the MaxExact level to allow iw vs he to still be a closer match than -// en-AU vs en-US, for example. -// [5] In CLDR a locale inherits fields that are unspecified for this locale -// from its parent. Therefore, if a locale is a parent of another locale, -// it is a strong measure for closeness, especially when no other tie -// breaker rule applies. One could also argue it is inconsistent, for -// example, when pt-AO matches pt (which CLDR equates with pt-BR), even -// though its parent is pt-PT according to the inheritance rules. -// -// Implementation Details: -// There are several performance considerations worth pointing out. Most notably, -// we preprocess as much as possible (within reason) at the time of creation of a -// matcher. This includes: -// - creating a per-language map, which includes data for the raw base language -// and its canonicalized variant (if applicable), -// - expanding entries for the equivalence classes defined in CLDR's -// languageMatch data. -// The per-language map ensures that typically only a very small number of tags -// need to be considered. The pre-expansion of canonicalized subtags and -// equivalence classes reduces the amount of map lookups that need to be done at -// runtime. - -// matcher keeps a set of supported language tags, indexed by language. -type matcher struct { - default_ *haveTag - supported []*haveTag - index map[language.Language]*matchHeader - passSettings bool - preferSameScript bool -} - -// matchHeader has the lists of tags for exact matches and matches based on -// maximized and canonicalized tags for a given language. -type matchHeader struct { - haveTags []*haveTag - original bool -} - -// haveTag holds a supported Tag and its maximized script and region. The maximized -// or canonicalized language is not stored as it is not needed during matching. -type haveTag struct { - tag language.Tag - - // index of this tag in the original list of supported tags. - index int - - // conf is the maximum confidence that can result from matching this haveTag. - // When conf < Exact this means it was inserted after applying a CLDR equivalence rule. - conf Confidence - - // Maximized region and script. - maxRegion language.Region - maxScript language.Script - - // altScript may be checked as an alternative match to maxScript. If altScript - // matches, the confidence level for this match is Low. Theoretically there - // could be multiple alternative scripts. This does not occur in practice. - altScript language.Script - - // nextMax is the index of the next haveTag with the same maximized tags. - nextMax uint16 -} - -func makeHaveTag(tag language.Tag, index int) (haveTag, language.Language) { - max := tag - if tag.LangID != 0 || tag.RegionID != 0 || tag.ScriptID != 0 { - max, _ = canonicalize(All, max) - max, _ = max.Maximize() - max.RemakeString() - } - return haveTag{tag, index, Exact, max.RegionID, max.ScriptID, altScript(max.LangID, max.ScriptID), 0}, max.LangID -} - -// altScript returns an alternative script that may match the given script with -// a low confidence. At the moment, the langMatch data allows for at most one -// script to map to another and we rely on this to keep the code simple. -func altScript(l language.Language, s language.Script) language.Script { - for _, alt := range matchScript { - // TODO: also match cases where language is not the same. - if (language.Language(alt.wantLang) == l || language.Language(alt.haveLang) == l) && - language.Script(alt.haveScript) == s { - return language.Script(alt.wantScript) - } - } - return 0 -} - -// addIfNew adds a haveTag to the list of tags only if it is a unique tag. -// Tags that have the same maximized values are linked by index. -func (h *matchHeader) addIfNew(n haveTag, exact bool) { - h.original = h.original || exact - // Don't add new exact matches. - for _, v := range h.haveTags { - if equalsRest(v.tag, n.tag) { - return - } - } - // Allow duplicate maximized tags, but create a linked list to allow quickly - // comparing the equivalents and bail out. - for i, v := range h.haveTags { - if v.maxScript == n.maxScript && - v.maxRegion == n.maxRegion && - v.tag.VariantOrPrivateUseTags() == n.tag.VariantOrPrivateUseTags() { - for h.haveTags[i].nextMax != 0 { - i = int(h.haveTags[i].nextMax) - } - h.haveTags[i].nextMax = uint16(len(h.haveTags)) - break - } - } - h.haveTags = append(h.haveTags, &n) -} - -// header returns the matchHeader for the given language. It creates one if -// it doesn't already exist. -func (m *matcher) header(l language.Language) *matchHeader { - if h := m.index[l]; h != nil { - return h - } - h := &matchHeader{} - m.index[l] = h - return h -} - -func toConf(d uint8) Confidence { - if d <= 10 { - return High - } - if d < 30 { - return Low - } - return No -} - -// newMatcher builds an index for the given supported tags and returns it as -// a matcher. It also expands the index by considering various equivalence classes -// for a given tag. -func newMatcher(supported []Tag, options []MatchOption) *matcher { - m := &matcher{ - index: make(map[language.Language]*matchHeader), - preferSameScript: true, - } - for _, o := range options { - o(m) - } - if len(supported) == 0 { - m.default_ = &haveTag{} - return m - } - // Add supported languages to the index. Add exact matches first to give - // them precedence. - for i, tag := range supported { - tt := tag.tag() - pair, _ := makeHaveTag(tt, i) - m.header(tt.LangID).addIfNew(pair, true) - m.supported = append(m.supported, &pair) - } - m.default_ = m.header(supported[0].lang()).haveTags[0] - // Keep these in two different loops to support the case that two equivalent - // languages are distinguished, such as iw and he. - for i, tag := range supported { - tt := tag.tag() - pair, max := makeHaveTag(tt, i) - if max != tt.LangID { - m.header(max).addIfNew(pair, true) - } - } - - // update is used to add indexes in the map for equivalent languages. - // update will only add entries to original indexes, thus not computing any - // transitive relations. - update := func(want, have uint16, conf Confidence) { - if hh := m.index[language.Language(have)]; hh != nil { - if !hh.original { - return - } - hw := m.header(language.Language(want)) - for _, ht := range hh.haveTags { - v := *ht - if conf < v.conf { - v.conf = conf - } - v.nextMax = 0 // this value needs to be recomputed - if v.altScript != 0 { - v.altScript = altScript(language.Language(want), v.maxScript) - } - hw.addIfNew(v, conf == Exact && hh.original) - } - } - } - - // Add entries for languages with mutual intelligibility as defined by CLDR's - // languageMatch data. - for _, ml := range matchLang { - update(ml.want, ml.have, toConf(ml.distance)) - if !ml.oneway { - update(ml.have, ml.want, toConf(ml.distance)) - } - } - - // Add entries for possible canonicalizations. This is an optimization to - // ensure that only one map lookup needs to be done at runtime per desired tag. - // First we match deprecated equivalents. If they are perfect equivalents - // (their canonicalization simply substitutes a different language code, but - // nothing else), the match confidence is Exact, otherwise it is High. - for i, lm := range language.AliasMap { - // If deprecated codes match and there is no fiddling with the script or - // or region, we consider it an exact match. - conf := Exact - if language.AliasTypes[i] != language.Macro { - if !isExactEquivalent(language.Language(lm.From)) { - conf = High - } - update(lm.To, lm.From, conf) - } - update(lm.From, lm.To, conf) - } - return m -} - -// getBest gets the best matching tag in m for any of the given tags, taking into -// account the order of preference of the given tags. -func (m *matcher) getBest(want ...Tag) (got *haveTag, orig language.Tag, c Confidence) { - best := bestMatch{} - for i, ww := range want { - w := ww.tag() - var max language.Tag - // Check for exact match first. - h := m.index[w.LangID] - if w.LangID != 0 { - if h == nil { - continue - } - // Base language is defined. - max, _ = canonicalize(Legacy|Deprecated|Macro, w) - // A region that is added through canonicalization is stronger than - // a maximized region: set it in the original (e.g. mo -> ro-MD). - if w.RegionID != max.RegionID { - w.RegionID = max.RegionID - } - // TODO: should we do the same for scripts? - // See test case: en, sr, nl ; sh ; sr - max, _ = max.Maximize() - } else { - // Base language is not defined. - if h != nil { - for i := range h.haveTags { - have := h.haveTags[i] - if equalsRest(have.tag, w) { - return have, w, Exact - } - } - } - if w.ScriptID == 0 && w.RegionID == 0 { - // We skip all tags matching und for approximate matching, including - // private tags. - continue - } - max, _ = w.Maximize() - if h = m.index[max.LangID]; h == nil { - continue - } - } - pin := true - for _, t := range want[i+1:] { - if w.LangID == t.lang() { - pin = false - break - } - } - // Check for match based on maximized tag. - for i := range h.haveTags { - have := h.haveTags[i] - best.update(have, w, max.ScriptID, max.RegionID, pin) - if best.conf == Exact { - for have.nextMax != 0 { - have = h.haveTags[have.nextMax] - best.update(have, w, max.ScriptID, max.RegionID, pin) - } - return best.have, best.want, best.conf - } - } - } - if best.conf <= No { - if len(want) != 0 { - return nil, want[0].tag(), No - } - return nil, language.Tag{}, No - } - return best.have, best.want, best.conf -} - -// bestMatch accumulates the best match so far. -type bestMatch struct { - have *haveTag - want language.Tag - conf Confidence - pinnedRegion language.Region - pinLanguage bool - sameRegionGroup bool - // Cached results from applying tie-breaking rules. - origLang bool - origReg bool - paradigmReg bool - regGroupDist uint8 - origScript bool -} - -// update updates the existing best match if the new pair is considered to be a -// better match. To determine if the given pair is a better match, it first -// computes the rough confidence level. If this surpasses the current match, it -// will replace it and update the tie-breaker rule cache. If there is a tie, it -// proceeds with applying a series of tie-breaker rules. If there is no -// conclusive winner after applying the tie-breaker rules, it leaves the current -// match as the preferred match. -// -// If pin is true and have and tag are a strong match, it will henceforth only -// consider matches for this language. This corresponds to the idea that most -// users have a strong preference for the first defined language. A user can -// still prefer a second language over a dialect of the preferred language by -// explicitly specifying dialects, e.g. "en, nl, en-GB". In this case pin should -// be false. -func (m *bestMatch) update(have *haveTag, tag language.Tag, maxScript language.Script, maxRegion language.Region, pin bool) { - // Bail if the maximum attainable confidence is below that of the current best match. - c := have.conf - if c < m.conf { - return - } - // Don't change the language once we already have found an exact match. - if m.pinLanguage && tag.LangID != m.want.LangID { - return - } - // Pin the region group if we are comparing tags for the same language. - if tag.LangID == m.want.LangID && m.sameRegionGroup { - _, sameGroup := regionGroupDist(m.pinnedRegion, have.maxRegion, have.maxScript, m.want.LangID) - if !sameGroup { - return - } - } - if c == Exact && have.maxScript == maxScript { - // If there is another language and then another entry of this language, - // don't pin anything, otherwise pin the language. - m.pinLanguage = pin - } - if equalsRest(have.tag, tag) { - } else if have.maxScript != maxScript { - // There is usually very little comprehension between different scripts. - // In a few cases there may still be Low comprehension. This possibility - // is pre-computed and stored in have.altScript. - if Low < m.conf || have.altScript != maxScript { - return - } - c = Low - } else if have.maxRegion != maxRegion { - if High < c { - // There is usually a small difference between languages across regions. - c = High - } - } - - // We store the results of the computations of the tie-breaker rules along - // with the best match. There is no need to do the checks once we determine - // we have a winner, but we do still need to do the tie-breaker computations. - // We use "beaten" to keep track if we still need to do the checks. - beaten := false // true if the new pair defeats the current one. - if c != m.conf { - if c < m.conf { - return - } - beaten = true - } - - // Tie-breaker rules: - // We prefer if the pre-maximized language was specified and identical. - origLang := have.tag.LangID == tag.LangID && tag.LangID != 0 - if !beaten && m.origLang != origLang { - if m.origLang { - return - } - beaten = true - } - - // We prefer if the pre-maximized region was specified and identical. - origReg := have.tag.RegionID == tag.RegionID && tag.RegionID != 0 - if !beaten && m.origReg != origReg { - if m.origReg { - return - } - beaten = true - } - - regGroupDist, sameGroup := regionGroupDist(have.maxRegion, maxRegion, maxScript, tag.LangID) - if !beaten && m.regGroupDist != regGroupDist { - if regGroupDist > m.regGroupDist { - return - } - beaten = true - } - - paradigmReg := isParadigmLocale(tag.LangID, have.maxRegion) - if !beaten && m.paradigmReg != paradigmReg { - if !paradigmReg { - return - } - beaten = true - } - - // Next we prefer if the pre-maximized script was specified and identical. - origScript := have.tag.ScriptID == tag.ScriptID && tag.ScriptID != 0 - if !beaten && m.origScript != origScript { - if m.origScript { - return - } - beaten = true - } - - // Update m to the newly found best match. - if beaten { - m.have = have - m.want = tag - m.conf = c - m.pinnedRegion = maxRegion - m.sameRegionGroup = sameGroup - m.origLang = origLang - m.origReg = origReg - m.paradigmReg = paradigmReg - m.origScript = origScript - m.regGroupDist = regGroupDist - } -} - -func isParadigmLocale(lang language.Language, r language.Region) bool { - for _, e := range paradigmLocales { - if language.Language(e[0]) == lang && (r == language.Region(e[1]) || r == language.Region(e[2])) { - return true - } - } - return false -} - -// regionGroupDist computes the distance between two regions based on their -// CLDR grouping. -func regionGroupDist(a, b language.Region, script language.Script, lang language.Language) (dist uint8, same bool) { - const defaultDistance = 4 - - aGroup := uint(regionToGroups[a]) << 1 - bGroup := uint(regionToGroups[b]) << 1 - for _, ri := range matchRegion { - if language.Language(ri.lang) == lang && (ri.script == 0 || language.Script(ri.script) == script) { - group := uint(1 << (ri.group &^ 0x80)) - if 0x80&ri.group == 0 { - if aGroup&bGroup&group != 0 { // Both regions are in the group. - return ri.distance, ri.distance == defaultDistance - } - } else { - if (aGroup|bGroup)&group == 0 { // Both regions are not in the group. - return ri.distance, ri.distance == defaultDistance - } - } - } - } - return defaultDistance, true -} - -// equalsRest compares everything except the language. -func equalsRest(a, b language.Tag) bool { - // TODO: don't include extensions in this comparison. To do this efficiently, - // though, we should handle private tags separately. - return a.ScriptID == b.ScriptID && a.RegionID == b.RegionID && a.VariantOrPrivateUseTags() == b.VariantOrPrivateUseTags() -} - -// isExactEquivalent returns true if canonicalizing the language will not alter -// the script or region of a tag. -func isExactEquivalent(l language.Language) bool { - for _, o := range notEquivalent { - if o == l { - return false - } - } - return true -} - -var notEquivalent []language.Language - -func init() { - // Create a list of all languages for which canonicalization may alter the - // script or region. - for _, lm := range language.AliasMap { - tag := language.Tag{LangID: language.Language(lm.From)} - if tag, _ = canonicalize(All, tag); tag.ScriptID != 0 || tag.RegionID != 0 { - notEquivalent = append(notEquivalent, language.Language(lm.From)) - } - } - // Maximize undefined regions of paradigm locales. - for i, v := range paradigmLocales { - t := language.Tag{LangID: language.Language(v[0])} - max, _ := t.Maximize() - if v[1] == 0 { - paradigmLocales[i][1] = uint16(max.RegionID) - } - if v[2] == 0 { - paradigmLocales[i][2] = uint16(max.RegionID) - } - } -} diff --git a/vendor/golang.org/x/text/language/parse.go b/vendor/golang.org/x/text/language/parse.go deleted file mode 100644 index 4d57222..0000000 --- a/vendor/golang.org/x/text/language/parse.go +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2013 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 language - -import ( - "errors" - "sort" - "strconv" - "strings" - - "golang.org/x/text/internal/language" -) - -// ValueError is returned by any of the parsing functions when the -// input is well-formed but the respective subtag is not recognized -// as a valid value. -type ValueError interface { - error - - // Subtag returns the subtag for which the error occurred. - Subtag() string -} - -// Parse parses the given BCP 47 string and returns a valid Tag. If parsing -// failed it returns an error and any part of the tag that could be parsed. -// If parsing succeeded but an unknown value was found, it returns -// ValueError. The Tag returned in this case is just stripped of the unknown -// value. All other values are preserved. It accepts tags in the BCP 47 format -// and extensions to this standard defined in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -// The resulting tag is canonicalized using the default canonicalization type. -func Parse(s string) (t Tag, err error) { - return Default.Parse(s) -} - -// Parse parses the given BCP 47 string and returns a valid Tag. If parsing -// failed it returns an error and any part of the tag that could be parsed. -// If parsing succeeded but an unknown value was found, it returns -// ValueError. The Tag returned in this case is just stripped of the unknown -// value. All other values are preserved. It accepts tags in the BCP 47 format -// and extensions to this standard defined in -// https://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. -// The resulting tag is canonicalized using the canonicalization type c. -func (c CanonType) Parse(s string) (t Tag, err error) { - defer func() { - if recover() != nil { - t = Tag{} - err = language.ErrSyntax - } - }() - - tt, err := language.Parse(s) - if err != nil { - return makeTag(tt), err - } - tt, changed := canonicalize(c, tt) - if changed { - tt.RemakeString() - } - return makeTag(tt), err -} - -// Compose creates a Tag from individual parts, which may be of type Tag, Base, -// Script, Region, Variant, []Variant, Extension, []Extension or error. If a -// Base, Script or Region or slice of type Variant or Extension is passed more -// than once, the latter will overwrite the former. Variants and Extensions are -// accumulated, but if two extensions of the same type are passed, the latter -// will replace the former. For -u extensions, though, the key-type pairs are -// added, where later values overwrite older ones. A Tag overwrites all former -// values and typically only makes sense as the first argument. The resulting -// tag is returned after canonicalizing using the Default CanonType. If one or -// more errors are encountered, one of the errors is returned. -func Compose(part ...interface{}) (t Tag, err error) { - return Default.Compose(part...) -} - -// Compose creates a Tag from individual parts, which may be of type Tag, Base, -// Script, Region, Variant, []Variant, Extension, []Extension or error. If a -// Base, Script or Region or slice of type Variant or Extension is passed more -// than once, the latter will overwrite the former. Variants and Extensions are -// accumulated, but if two extensions of the same type are passed, the latter -// will replace the former. For -u extensions, though, the key-type pairs are -// added, where later values overwrite older ones. A Tag overwrites all former -// values and typically only makes sense as the first argument. The resulting -// tag is returned after canonicalizing using CanonType c. If one or more errors -// are encountered, one of the errors is returned. -func (c CanonType) Compose(part ...interface{}) (t Tag, err error) { - defer func() { - if recover() != nil { - t = Tag{} - err = language.ErrSyntax - } - }() - - var b language.Builder - if err = update(&b, part...); err != nil { - return und, err - } - b.Tag, _ = canonicalize(c, b.Tag) - return makeTag(b.Make()), err -} - -var errInvalidArgument = errors.New("invalid Extension or Variant") - -func update(b *language.Builder, part ...interface{}) (err error) { - for _, x := range part { - switch v := x.(type) { - case Tag: - b.SetTag(v.tag()) - case Base: - b.Tag.LangID = v.langID - case Script: - b.Tag.ScriptID = v.scriptID - case Region: - b.Tag.RegionID = v.regionID - case Variant: - if v.variant == "" { - err = errInvalidArgument - break - } - b.AddVariant(v.variant) - case Extension: - if v.s == "" { - err = errInvalidArgument - break - } - b.SetExt(v.s) - case []Variant: - b.ClearVariants() - for _, v := range v { - b.AddVariant(v.variant) - } - case []Extension: - b.ClearExtensions() - for _, e := range v { - b.SetExt(e.s) - } - // TODO: support parsing of raw strings based on morphology or just extensions? - case error: - if v != nil { - err = v - } - } - } - return -} - -var errInvalidWeight = errors.New("ParseAcceptLanguage: invalid weight") -var errTagListTooLarge = errors.New("tag list exceeds max length") - -// ParseAcceptLanguage parses the contents of an Accept-Language header as -// defined in http://www.ietf.org/rfc/rfc2616.txt and returns a list of Tags and -// a list of corresponding quality weights. It is more permissive than RFC 2616 -// and may return non-nil slices even if the input is not valid. -// The Tags will be sorted by highest weight first and then by first occurrence. -// Tags with a weight of zero will be dropped. An error will be returned if the -// input could not be parsed. -func ParseAcceptLanguage(s string) (tag []Tag, q []float32, err error) { - defer func() { - if recover() != nil { - tag = nil - q = nil - err = language.ErrSyntax - } - }() - - if strings.Count(s, "-") > 1000 { - return nil, nil, errTagListTooLarge - } - - var entry string - for s != "" { - if entry, s = split(s, ','); entry == "" { - continue - } - - entry, weight := split(entry, ';') - - // Scan the language. - t, err := Parse(entry) - if err != nil { - id, ok := acceptFallback[entry] - if !ok { - return nil, nil, err - } - t = makeTag(language.Tag{LangID: id}) - } - - // Scan the optional weight. - w := 1.0 - if weight != "" { - weight = consume(weight, 'q') - weight = consume(weight, '=') - // consume returns the empty string when a token could not be - // consumed, resulting in an error for ParseFloat. - if w, err = strconv.ParseFloat(weight, 32); err != nil { - return nil, nil, errInvalidWeight - } - // Drop tags with a quality weight of 0. - if w <= 0 { - continue - } - } - - tag = append(tag, t) - q = append(q, float32(w)) - } - sort.Stable(&tagSort{tag, q}) - return tag, q, nil -} - -// consume removes a leading token c from s and returns the result or the empty -// string if there is no such token. -func consume(s string, c byte) string { - if s == "" || s[0] != c { - return "" - } - return strings.TrimSpace(s[1:]) -} - -func split(s string, c byte) (head, tail string) { - if i := strings.IndexByte(s, c); i >= 0 { - return strings.TrimSpace(s[:i]), strings.TrimSpace(s[i+1:]) - } - return strings.TrimSpace(s), "" -} - -// Add hack mapping to deal with a small number of cases that occur -// in Accept-Language (with reasonable frequency). -var acceptFallback = map[string]language.Language{ - "english": _en, - "deutsch": _de, - "italian": _it, - "french": _fr, - "*": _mul, // defined in the spec to match all languages. -} - -type tagSort struct { - tag []Tag - q []float32 -} - -func (s *tagSort) Len() int { - return len(s.q) -} - -func (s *tagSort) Less(i, j int) bool { - return s.q[i] > s.q[j] -} - -func (s *tagSort) Swap(i, j int) { - s.tag[i], s.tag[j] = s.tag[j], s.tag[i] - s.q[i], s.q[j] = s.q[j], s.q[i] -} diff --git a/vendor/golang.org/x/text/language/tables.go b/vendor/golang.org/x/text/language/tables.go deleted file mode 100644 index 34a732b..0000000 --- a/vendor/golang.org/x/text/language/tables.go +++ /dev/null @@ -1,298 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -package language - -// CLDRVersion is the CLDR version from which the tables in this package are derived. -const CLDRVersion = "32" - -const ( - _de = 269 - _en = 313 - _fr = 350 - _it = 505 - _mo = 784 - _no = 879 - _nb = 839 - _pt = 960 - _sh = 1031 - _mul = 806 - _und = 0 -) -const ( - _001 = 1 - _419 = 31 - _BR = 65 - _CA = 73 - _ES = 110 - _GB = 123 - _MD = 188 - _PT = 238 - _UK = 306 - _US = 309 - _ZZ = 357 - _XA = 323 - _XC = 325 - _XK = 333 -) -const ( - _Latn = 90 - _Hani = 57 - _Hans = 59 - _Hant = 60 - _Qaaa = 147 - _Qaai = 155 - _Qabx = 196 - _Zinh = 252 - _Zyyy = 257 - _Zzzz = 258 -) - -var regionToGroups = []uint8{ // 358 elements - // Entry 0 - 3F - 0x00, 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x04, 0x01, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x00, 0x04, - // Entry 40 - 7F - 0x04, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, - 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x00, 0x08, - 0x00, 0x04, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, - // Entry 80 - BF - 0x00, 0x00, 0x04, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x04, 0x01, 0x00, 0x04, 0x02, 0x00, 0x04, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x08, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, - // Entry C0 - FF - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x01, - 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x04, 0x00, 0x05, 0x00, 0x00, 0x00, - 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // Entry 100 - 13F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, - 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x00, 0x04, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x04, 0x00, - 0x00, 0x04, 0x00, 0x04, 0x04, 0x05, 0x00, 0x00, - // Entry 140 - 17F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -} // Size: 382 bytes - -var paradigmLocales = [][3]uint16{ // 3 elements - 0: [3]uint16{0x139, 0x0, 0x7b}, - 1: [3]uint16{0x13e, 0x0, 0x1f}, - 2: [3]uint16{0x3c0, 0x41, 0xee}, -} // Size: 42 bytes - -type mutualIntelligibility struct { - want uint16 - have uint16 - distance uint8 - oneway bool -} -type scriptIntelligibility struct { - wantLang uint16 - haveLang uint16 - wantScript uint8 - haveScript uint8 - distance uint8 -} -type regionIntelligibility struct { - lang uint16 - script uint8 - group uint8 - distance uint8 -} - -// matchLang holds pairs of langIDs of base languages that are typically -// mutually intelligible. Each pair is associated with a confidence and -// whether the intelligibility goes one or both ways. -var matchLang = []mutualIntelligibility{ // 113 elements - 0: {want: 0x1d1, have: 0xb7, distance: 0x4, oneway: false}, - 1: {want: 0x407, have: 0xb7, distance: 0x4, oneway: false}, - 2: {want: 0x407, have: 0x1d1, distance: 0x4, oneway: false}, - 3: {want: 0x407, have: 0x432, distance: 0x4, oneway: false}, - 4: {want: 0x43a, have: 0x1, distance: 0x4, oneway: false}, - 5: {want: 0x1a3, have: 0x10d, distance: 0x4, oneway: true}, - 6: {want: 0x295, have: 0x10d, distance: 0x4, oneway: true}, - 7: {want: 0x101, have: 0x36f, distance: 0x8, oneway: false}, - 8: {want: 0x101, have: 0x347, distance: 0x8, oneway: false}, - 9: {want: 0x5, have: 0x3e2, distance: 0xa, oneway: true}, - 10: {want: 0xd, have: 0x139, distance: 0xa, oneway: true}, - 11: {want: 0x16, have: 0x367, distance: 0xa, oneway: true}, - 12: {want: 0x21, have: 0x139, distance: 0xa, oneway: true}, - 13: {want: 0x56, have: 0x13e, distance: 0xa, oneway: true}, - 14: {want: 0x58, have: 0x3e2, distance: 0xa, oneway: true}, - 15: {want: 0x71, have: 0x3e2, distance: 0xa, oneway: true}, - 16: {want: 0x75, have: 0x139, distance: 0xa, oneway: true}, - 17: {want: 0x82, have: 0x1be, distance: 0xa, oneway: true}, - 18: {want: 0xa5, have: 0x139, distance: 0xa, oneway: true}, - 19: {want: 0xb2, have: 0x15e, distance: 0xa, oneway: true}, - 20: {want: 0xdd, have: 0x153, distance: 0xa, oneway: true}, - 21: {want: 0xe5, have: 0x139, distance: 0xa, oneway: true}, - 22: {want: 0xe9, have: 0x3a, distance: 0xa, oneway: true}, - 23: {want: 0xf0, have: 0x15e, distance: 0xa, oneway: true}, - 24: {want: 0xf9, have: 0x15e, distance: 0xa, oneway: true}, - 25: {want: 0x100, have: 0x139, distance: 0xa, oneway: true}, - 26: {want: 0x130, have: 0x139, distance: 0xa, oneway: true}, - 27: {want: 0x13c, have: 0x139, distance: 0xa, oneway: true}, - 28: {want: 0x140, have: 0x151, distance: 0xa, oneway: true}, - 29: {want: 0x145, have: 0x13e, distance: 0xa, oneway: true}, - 30: {want: 0x158, have: 0x101, distance: 0xa, oneway: true}, - 31: {want: 0x16d, have: 0x367, distance: 0xa, oneway: true}, - 32: {want: 0x16e, have: 0x139, distance: 0xa, oneway: true}, - 33: {want: 0x16f, have: 0x139, distance: 0xa, oneway: true}, - 34: {want: 0x17e, have: 0x139, distance: 0xa, oneway: true}, - 35: {want: 0x190, have: 0x13e, distance: 0xa, oneway: true}, - 36: {want: 0x194, have: 0x13e, distance: 0xa, oneway: true}, - 37: {want: 0x1a4, have: 0x1be, distance: 0xa, oneway: true}, - 38: {want: 0x1b4, have: 0x139, distance: 0xa, oneway: true}, - 39: {want: 0x1b8, have: 0x139, distance: 0xa, oneway: true}, - 40: {want: 0x1d4, have: 0x15e, distance: 0xa, oneway: true}, - 41: {want: 0x1d7, have: 0x3e2, distance: 0xa, oneway: true}, - 42: {want: 0x1d9, have: 0x139, distance: 0xa, oneway: true}, - 43: {want: 0x1e7, have: 0x139, distance: 0xa, oneway: true}, - 44: {want: 0x1f8, have: 0x139, distance: 0xa, oneway: true}, - 45: {want: 0x20e, have: 0x1e1, distance: 0xa, oneway: true}, - 46: {want: 0x210, have: 0x139, distance: 0xa, oneway: true}, - 47: {want: 0x22d, have: 0x15e, distance: 0xa, oneway: true}, - 48: {want: 0x242, have: 0x3e2, distance: 0xa, oneway: true}, - 49: {want: 0x24a, have: 0x139, distance: 0xa, oneway: true}, - 50: {want: 0x251, have: 0x139, distance: 0xa, oneway: true}, - 51: {want: 0x265, have: 0x139, distance: 0xa, oneway: true}, - 52: {want: 0x274, have: 0x48a, distance: 0xa, oneway: true}, - 53: {want: 0x28a, have: 0x3e2, distance: 0xa, oneway: true}, - 54: {want: 0x28e, have: 0x1f9, distance: 0xa, oneway: true}, - 55: {want: 0x2a3, have: 0x139, distance: 0xa, oneway: true}, - 56: {want: 0x2b5, have: 0x15e, distance: 0xa, oneway: true}, - 57: {want: 0x2b8, have: 0x139, distance: 0xa, oneway: true}, - 58: {want: 0x2be, have: 0x139, distance: 0xa, oneway: true}, - 59: {want: 0x2c3, have: 0x15e, distance: 0xa, oneway: true}, - 60: {want: 0x2ed, have: 0x139, distance: 0xa, oneway: true}, - 61: {want: 0x2f1, have: 0x15e, distance: 0xa, oneway: true}, - 62: {want: 0x2fa, have: 0x139, distance: 0xa, oneway: true}, - 63: {want: 0x2ff, have: 0x7e, distance: 0xa, oneway: true}, - 64: {want: 0x304, have: 0x139, distance: 0xa, oneway: true}, - 65: {want: 0x30b, have: 0x3e2, distance: 0xa, oneway: true}, - 66: {want: 0x31b, have: 0x1be, distance: 0xa, oneway: true}, - 67: {want: 0x31f, have: 0x1e1, distance: 0xa, oneway: true}, - 68: {want: 0x320, have: 0x139, distance: 0xa, oneway: true}, - 69: {want: 0x331, have: 0x139, distance: 0xa, oneway: true}, - 70: {want: 0x351, have: 0x139, distance: 0xa, oneway: true}, - 71: {want: 0x36a, have: 0x347, distance: 0xa, oneway: false}, - 72: {want: 0x36a, have: 0x36f, distance: 0xa, oneway: true}, - 73: {want: 0x37a, have: 0x139, distance: 0xa, oneway: true}, - 74: {want: 0x387, have: 0x139, distance: 0xa, oneway: true}, - 75: {want: 0x389, have: 0x139, distance: 0xa, oneway: true}, - 76: {want: 0x38b, have: 0x15e, distance: 0xa, oneway: true}, - 77: {want: 0x390, have: 0x139, distance: 0xa, oneway: true}, - 78: {want: 0x395, have: 0x139, distance: 0xa, oneway: true}, - 79: {want: 0x39d, have: 0x139, distance: 0xa, oneway: true}, - 80: {want: 0x3a5, have: 0x139, distance: 0xa, oneway: true}, - 81: {want: 0x3be, have: 0x139, distance: 0xa, oneway: true}, - 82: {want: 0x3c4, have: 0x13e, distance: 0xa, oneway: true}, - 83: {want: 0x3d4, have: 0x10d, distance: 0xa, oneway: true}, - 84: {want: 0x3d9, have: 0x139, distance: 0xa, oneway: true}, - 85: {want: 0x3e5, have: 0x15e, distance: 0xa, oneway: true}, - 86: {want: 0x3e9, have: 0x1be, distance: 0xa, oneway: true}, - 87: {want: 0x3fa, have: 0x139, distance: 0xa, oneway: true}, - 88: {want: 0x40c, have: 0x139, distance: 0xa, oneway: true}, - 89: {want: 0x423, have: 0x139, distance: 0xa, oneway: true}, - 90: {want: 0x429, have: 0x139, distance: 0xa, oneway: true}, - 91: {want: 0x431, have: 0x139, distance: 0xa, oneway: true}, - 92: {want: 0x43b, have: 0x139, distance: 0xa, oneway: true}, - 93: {want: 0x43e, have: 0x1e1, distance: 0xa, oneway: true}, - 94: {want: 0x445, have: 0x139, distance: 0xa, oneway: true}, - 95: {want: 0x450, have: 0x139, distance: 0xa, oneway: true}, - 96: {want: 0x461, have: 0x139, distance: 0xa, oneway: true}, - 97: {want: 0x467, have: 0x3e2, distance: 0xa, oneway: true}, - 98: {want: 0x46f, have: 0x139, distance: 0xa, oneway: true}, - 99: {want: 0x476, have: 0x3e2, distance: 0xa, oneway: true}, - 100: {want: 0x3883, have: 0x139, distance: 0xa, oneway: true}, - 101: {want: 0x480, have: 0x139, distance: 0xa, oneway: true}, - 102: {want: 0x482, have: 0x139, distance: 0xa, oneway: true}, - 103: {want: 0x494, have: 0x3e2, distance: 0xa, oneway: true}, - 104: {want: 0x49d, have: 0x139, distance: 0xa, oneway: true}, - 105: {want: 0x4ac, have: 0x529, distance: 0xa, oneway: true}, - 106: {want: 0x4b4, have: 0x139, distance: 0xa, oneway: true}, - 107: {want: 0x4bc, have: 0x3e2, distance: 0xa, oneway: true}, - 108: {want: 0x4e5, have: 0x15e, distance: 0xa, oneway: true}, - 109: {want: 0x4f2, have: 0x139, distance: 0xa, oneway: true}, - 110: {want: 0x512, have: 0x139, distance: 0xa, oneway: true}, - 111: {want: 0x518, have: 0x139, distance: 0xa, oneway: true}, - 112: {want: 0x52f, have: 0x139, distance: 0xa, oneway: true}, -} // Size: 702 bytes - -// matchScript holds pairs of scriptIDs where readers of one script -// can typically also read the other. Each is associated with a confidence. -var matchScript = []scriptIntelligibility{ // 26 elements - 0: {wantLang: 0x432, haveLang: 0x432, wantScript: 0x5a, haveScript: 0x20, distance: 0x5}, - 1: {wantLang: 0x432, haveLang: 0x432, wantScript: 0x20, haveScript: 0x5a, distance: 0x5}, - 2: {wantLang: 0x58, haveLang: 0x3e2, wantScript: 0x5a, haveScript: 0x20, distance: 0xa}, - 3: {wantLang: 0xa5, haveLang: 0x139, wantScript: 0xe, haveScript: 0x5a, distance: 0xa}, - 4: {wantLang: 0x1d7, haveLang: 0x3e2, wantScript: 0x8, haveScript: 0x20, distance: 0xa}, - 5: {wantLang: 0x210, haveLang: 0x139, wantScript: 0x2e, haveScript: 0x5a, distance: 0xa}, - 6: {wantLang: 0x24a, haveLang: 0x139, wantScript: 0x4e, haveScript: 0x5a, distance: 0xa}, - 7: {wantLang: 0x251, haveLang: 0x139, wantScript: 0x52, haveScript: 0x5a, distance: 0xa}, - 8: {wantLang: 0x2b8, haveLang: 0x139, wantScript: 0x57, haveScript: 0x5a, distance: 0xa}, - 9: {wantLang: 0x304, haveLang: 0x139, wantScript: 0x6e, haveScript: 0x5a, distance: 0xa}, - 10: {wantLang: 0x331, haveLang: 0x139, wantScript: 0x75, haveScript: 0x5a, distance: 0xa}, - 11: {wantLang: 0x351, haveLang: 0x139, wantScript: 0x22, haveScript: 0x5a, distance: 0xa}, - 12: {wantLang: 0x395, haveLang: 0x139, wantScript: 0x81, haveScript: 0x5a, distance: 0xa}, - 13: {wantLang: 0x39d, haveLang: 0x139, wantScript: 0x36, haveScript: 0x5a, distance: 0xa}, - 14: {wantLang: 0x3be, haveLang: 0x139, wantScript: 0x5, haveScript: 0x5a, distance: 0xa}, - 15: {wantLang: 0x3fa, haveLang: 0x139, wantScript: 0x5, haveScript: 0x5a, distance: 0xa}, - 16: {wantLang: 0x40c, haveLang: 0x139, wantScript: 0xd4, haveScript: 0x5a, distance: 0xa}, - 17: {wantLang: 0x450, haveLang: 0x139, wantScript: 0xe3, haveScript: 0x5a, distance: 0xa}, - 18: {wantLang: 0x461, haveLang: 0x139, wantScript: 0xe6, haveScript: 0x5a, distance: 0xa}, - 19: {wantLang: 0x46f, haveLang: 0x139, wantScript: 0x2c, haveScript: 0x5a, distance: 0xa}, - 20: {wantLang: 0x476, haveLang: 0x3e2, wantScript: 0x5a, haveScript: 0x20, distance: 0xa}, - 21: {wantLang: 0x4b4, haveLang: 0x139, wantScript: 0x5, haveScript: 0x5a, distance: 0xa}, - 22: {wantLang: 0x4bc, haveLang: 0x3e2, wantScript: 0x5a, haveScript: 0x20, distance: 0xa}, - 23: {wantLang: 0x512, haveLang: 0x139, wantScript: 0x3e, haveScript: 0x5a, distance: 0xa}, - 24: {wantLang: 0x529, haveLang: 0x529, wantScript: 0x3b, haveScript: 0x3c, distance: 0xf}, - 25: {wantLang: 0x529, haveLang: 0x529, wantScript: 0x3c, haveScript: 0x3b, distance: 0x13}, -} // Size: 232 bytes - -var matchRegion = []regionIntelligibility{ // 15 elements - 0: {lang: 0x3a, script: 0x0, group: 0x4, distance: 0x4}, - 1: {lang: 0x3a, script: 0x0, group: 0x84, distance: 0x4}, - 2: {lang: 0x139, script: 0x0, group: 0x1, distance: 0x4}, - 3: {lang: 0x139, script: 0x0, group: 0x81, distance: 0x4}, - 4: {lang: 0x13e, script: 0x0, group: 0x3, distance: 0x4}, - 5: {lang: 0x13e, script: 0x0, group: 0x83, distance: 0x4}, - 6: {lang: 0x3c0, script: 0x0, group: 0x3, distance: 0x4}, - 7: {lang: 0x3c0, script: 0x0, group: 0x83, distance: 0x4}, - 8: {lang: 0x529, script: 0x3c, group: 0x2, distance: 0x4}, - 9: {lang: 0x529, script: 0x3c, group: 0x82, distance: 0x4}, - 10: {lang: 0x3a, script: 0x0, group: 0x80, distance: 0x5}, - 11: {lang: 0x139, script: 0x0, group: 0x80, distance: 0x5}, - 12: {lang: 0x13e, script: 0x0, group: 0x80, distance: 0x5}, - 13: {lang: 0x3c0, script: 0x0, group: 0x80, distance: 0x5}, - 14: {lang: 0x529, script: 0x3c, group: 0x80, distance: 0x5}, -} // Size: 114 bytes - -// Total table size 1472 bytes (1KiB); checksum: F86C669 diff --git a/vendor/golang.org/x/text/language/tags.go b/vendor/golang.org/x/text/language/tags.go deleted file mode 100644 index 42ea792..0000000 --- a/vendor/golang.org/x/text/language/tags.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2013 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 language - -import "golang.org/x/text/internal/language/compact" - -// TODO: Various sets of commonly use tags and regions. - -// MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. -// It simplifies safe initialization of Tag values. -func MustParse(s string) Tag { - t, err := Parse(s) - if err != nil { - panic(err) - } - return t -} - -// MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. -// It simplifies safe initialization of Tag values. -func (c CanonType) MustParse(s string) Tag { - t, err := c.Parse(s) - if err != nil { - panic(err) - } - return t -} - -// MustParseBase is like ParseBase, but panics if the given base cannot be parsed. -// It simplifies safe initialization of Base values. -func MustParseBase(s string) Base { - b, err := ParseBase(s) - if err != nil { - panic(err) - } - return b -} - -// MustParseScript is like ParseScript, but panics if the given script cannot be -// parsed. It simplifies safe initialization of Script values. -func MustParseScript(s string) Script { - scr, err := ParseScript(s) - if err != nil { - panic(err) - } - return scr -} - -// MustParseRegion is like ParseRegion, but panics if the given region cannot be -// parsed. It simplifies safe initialization of Region values. -func MustParseRegion(s string) Region { - r, err := ParseRegion(s) - if err != nil { - panic(err) - } - return r -} - -var ( - und = Tag{} - - Und Tag = Tag{} - - Afrikaans Tag = Tag(compact.Afrikaans) - Amharic Tag = Tag(compact.Amharic) - Arabic Tag = Tag(compact.Arabic) - ModernStandardArabic Tag = Tag(compact.ModernStandardArabic) - Azerbaijani Tag = Tag(compact.Azerbaijani) - Bulgarian Tag = Tag(compact.Bulgarian) - Bengali Tag = Tag(compact.Bengali) - Catalan Tag = Tag(compact.Catalan) - Czech Tag = Tag(compact.Czech) - Danish Tag = Tag(compact.Danish) - German Tag = Tag(compact.German) - Greek Tag = Tag(compact.Greek) - English Tag = Tag(compact.English) - AmericanEnglish Tag = Tag(compact.AmericanEnglish) - BritishEnglish Tag = Tag(compact.BritishEnglish) - Spanish Tag = Tag(compact.Spanish) - EuropeanSpanish Tag = Tag(compact.EuropeanSpanish) - LatinAmericanSpanish Tag = Tag(compact.LatinAmericanSpanish) - Estonian Tag = Tag(compact.Estonian) - Persian Tag = Tag(compact.Persian) - Finnish Tag = Tag(compact.Finnish) - Filipino Tag = Tag(compact.Filipino) - French Tag = Tag(compact.French) - CanadianFrench Tag = Tag(compact.CanadianFrench) - Gujarati Tag = Tag(compact.Gujarati) - Hebrew Tag = Tag(compact.Hebrew) - Hindi Tag = Tag(compact.Hindi) - Croatian Tag = Tag(compact.Croatian) - Hungarian Tag = Tag(compact.Hungarian) - Armenian Tag = Tag(compact.Armenian) - Indonesian Tag = Tag(compact.Indonesian) - Icelandic Tag = Tag(compact.Icelandic) - Italian Tag = Tag(compact.Italian) - Japanese Tag = Tag(compact.Japanese) - Georgian Tag = Tag(compact.Georgian) - Kazakh Tag = Tag(compact.Kazakh) - Khmer Tag = Tag(compact.Khmer) - Kannada Tag = Tag(compact.Kannada) - Korean Tag = Tag(compact.Korean) - Kirghiz Tag = Tag(compact.Kirghiz) - Lao Tag = Tag(compact.Lao) - Lithuanian Tag = Tag(compact.Lithuanian) - Latvian Tag = Tag(compact.Latvian) - Macedonian Tag = Tag(compact.Macedonian) - Malayalam Tag = Tag(compact.Malayalam) - Mongolian Tag = Tag(compact.Mongolian) - Marathi Tag = Tag(compact.Marathi) - Malay Tag = Tag(compact.Malay) - Burmese Tag = Tag(compact.Burmese) - Nepali Tag = Tag(compact.Nepali) - Dutch Tag = Tag(compact.Dutch) - Norwegian Tag = Tag(compact.Norwegian) - Punjabi Tag = Tag(compact.Punjabi) - Polish Tag = Tag(compact.Polish) - Portuguese Tag = Tag(compact.Portuguese) - BrazilianPortuguese Tag = Tag(compact.BrazilianPortuguese) - EuropeanPortuguese Tag = Tag(compact.EuropeanPortuguese) - Romanian Tag = Tag(compact.Romanian) - Russian Tag = Tag(compact.Russian) - Sinhala Tag = Tag(compact.Sinhala) - Slovak Tag = Tag(compact.Slovak) - Slovenian Tag = Tag(compact.Slovenian) - Albanian Tag = Tag(compact.Albanian) - Serbian Tag = Tag(compact.Serbian) - SerbianLatin Tag = Tag(compact.SerbianLatin) - Swedish Tag = Tag(compact.Swedish) - Swahili Tag = Tag(compact.Swahili) - Tamil Tag = Tag(compact.Tamil) - Telugu Tag = Tag(compact.Telugu) - Thai Tag = Tag(compact.Thai) - Turkish Tag = Tag(compact.Turkish) - Ukrainian Tag = Tag(compact.Ukrainian) - Urdu Tag = Tag(compact.Urdu) - Uzbek Tag = Tag(compact.Uzbek) - Vietnamese Tag = Tag(compact.Vietnamese) - Chinese Tag = Tag(compact.Chinese) - SimplifiedChinese Tag = Tag(compact.SimplifiedChinese) - TraditionalChinese Tag = Tag(compact.TraditionalChinese) - Zulu Tag = Tag(compact.Zulu) -) diff --git a/vendor/gopkg.in/yaml.v3/LICENSE b/vendor/gopkg.in/yaml.v3/LICENSE deleted file mode 100644 index 2683e4b..0000000 --- a/vendor/gopkg.in/yaml.v3/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ - -This project is covered by two different licenses: MIT and Apache. - -#### MIT License #### - -The following files were ported to Go from C files of libyaml, and thus -are still covered by their original MIT license, with the additional -copyright staring in 2011 when the project was ported over: - - apic.go emitterc.go parserc.go readerc.go scannerc.go - writerc.go yamlh.go yamlprivateh.go - -Copyright (c) 2006-2010 Kirill Simonov -Copyright (c) 2006-2011 Kirill Simonov - -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. - -### Apache License ### - -All the remaining project files are covered by the Apache license: - -Copyright (c) 2011-2019 Canonical Ltd - -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/gopkg.in/yaml.v3/NOTICE b/vendor/gopkg.in/yaml.v3/NOTICE deleted file mode 100644 index 866d74a..0000000 --- a/vendor/gopkg.in/yaml.v3/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2011-2016 Canonical Ltd. - -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/gopkg.in/yaml.v3/README.md b/vendor/gopkg.in/yaml.v3/README.md deleted file mode 100644 index 08eb1ba..0000000 --- a/vendor/gopkg.in/yaml.v3/README.md +++ /dev/null @@ -1,150 +0,0 @@ -# YAML support for the Go language - -Introduction ------------- - -The yaml package enables Go programs to comfortably encode and decode YAML -values. It was developed within [Canonical](https://www.canonical.com) as -part of the [juju](https://juju.ubuntu.com) project, and is based on a -pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) -C library to parse and generate YAML data quickly and reliably. - -Compatibility -------------- - -The yaml package supports most of YAML 1.2, but preserves some behavior -from 1.1 for backwards compatibility. - -Specifically, as of v3 of the yaml package: - - - YAML 1.1 bools (_yes/no, on/off_) are supported as long as they are being - decoded into a typed bool value. Otherwise they behave as a string. Booleans - in YAML 1.2 are _true/false_ only. - - Octals encode and decode as _0777_ per YAML 1.1, rather than _0o777_ - as specified in YAML 1.2, because most parsers still use the old format. - Octals in the _0o777_ format are supported though, so new files work. - - Does not support base-60 floats. These are gone from YAML 1.2, and were - actually never supported by this package as it's clearly a poor choice. - -and offers backwards -compatibility with YAML 1.1 in some cases. -1.2, including support for -anchors, tags, map merging, etc. Multi-document unmarshalling is not yet -implemented, and base-60 floats from YAML 1.1 are purposefully not -supported since they're a poor design and are gone in YAML 1.2. - -Installation and usage ----------------------- - -The import path for the package is *gopkg.in/yaml.v3*. - -To install it, run: - - go get gopkg.in/yaml.v3 - -API documentation ------------------ - -If opened in a browser, the import path itself leads to the API documentation: - - - [https://gopkg.in/yaml.v3](https://gopkg.in/yaml.v3) - -API stability -------------- - -The package API for yaml v3 will remain stable as described in [gopkg.in](https://gopkg.in). - - -License -------- - -The yaml package is licensed under the MIT and Apache License 2.0 licenses. -Please see the LICENSE file for details. - - -Example -------- - -```Go -package main - -import ( - "fmt" - "log" - - "gopkg.in/yaml.v3" -) - -var data = ` -a: Easy! -b: - c: 2 - d: [3, 4] -` - -// Note: struct fields must be public in order for unmarshal to -// correctly populate the data. -type T struct { - A string - B struct { - RenamedC int `yaml:"c"` - D []int `yaml:",flow"` - } -} - -func main() { - t := T{} - - err := yaml.Unmarshal([]byte(data), &t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t:\n%v\n\n", t) - - d, err := yaml.Marshal(&t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t dump:\n%s\n\n", string(d)) - - m := make(map[interface{}]interface{}) - - err = yaml.Unmarshal([]byte(data), &m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m:\n%v\n\n", m) - - d, err = yaml.Marshal(&m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m dump:\n%s\n\n", string(d)) -} -``` - -This example will generate the following output: - -``` ---- t: -{Easy! {2 [3 4]}} - ---- t dump: -a: Easy! -b: - c: 2 - d: [3, 4] - - ---- m: -map[a:Easy! b:map[c:2 d:[3 4]]] - ---- m dump: -a: Easy! -b: - c: 2 - d: - - 3 - - 4 -``` - diff --git a/vendor/gopkg.in/yaml.v3/apic.go b/vendor/gopkg.in/yaml.v3/apic.go deleted file mode 100644 index ae7d049..0000000 --- a/vendor/gopkg.in/yaml.v3/apic.go +++ /dev/null @@ -1,747 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -import ( - "io" -) - -func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) - - // Check if we can move the queue at the beginning of the buffer. - if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { - if parser.tokens_head != len(parser.tokens) { - copy(parser.tokens, parser.tokens[parser.tokens_head:]) - } - parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] - parser.tokens_head = 0 - } - parser.tokens = append(parser.tokens, *token) - if pos < 0 { - return - } - copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) - parser.tokens[parser.tokens_head+pos] = *token -} - -// Create a new parser object. -func yaml_parser_initialize(parser *yaml_parser_t) bool { - *parser = yaml_parser_t{ - raw_buffer: make([]byte, 0, input_raw_buffer_size), - buffer: make([]byte, 0, input_buffer_size), - } - return true -} - -// Destroy a parser object. -func yaml_parser_delete(parser *yaml_parser_t) { - *parser = yaml_parser_t{} -} - -// String read handler. -func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - if parser.input_pos == len(parser.input) { - return 0, io.EOF - } - n = copy(buffer, parser.input[parser.input_pos:]) - parser.input_pos += n - return n, nil -} - -// Reader read handler. -func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - return parser.input_reader.Read(buffer) -} - -// Set a string input. -func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_string_read_handler - parser.input = input - parser.input_pos = 0 -} - -// Set a file input. -func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_reader_read_handler - parser.input_reader = r -} - -// Set the source encoding. -func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { - if parser.encoding != yaml_ANY_ENCODING { - panic("must set the encoding only once") - } - parser.encoding = encoding -} - -// Create a new emitter object. -func yaml_emitter_initialize(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{ - buffer: make([]byte, output_buffer_size), - raw_buffer: make([]byte, 0, output_raw_buffer_size), - states: make([]yaml_emitter_state_t, 0, initial_stack_size), - events: make([]yaml_event_t, 0, initial_queue_size), - best_width: -1, - } -} - -// Destroy an emitter object. -func yaml_emitter_delete(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{} -} - -// String write handler. -func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - *emitter.output_buffer = append(*emitter.output_buffer, buffer...) - return nil -} - -// yaml_writer_write_handler uses emitter.output_writer to write the -// emitted text. -func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - _, err := emitter.output_writer.Write(buffer) - return err -} - -// Set a string output. -func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_string_write_handler - emitter.output_buffer = output_buffer -} - -// Set a file output. -func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_writer_write_handler - emitter.output_writer = w -} - -// Set the output encoding. -func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { - if emitter.encoding != yaml_ANY_ENCODING { - panic("must set the output encoding only once") - } - emitter.encoding = encoding -} - -// Set the canonical output style. -func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { - emitter.canonical = canonical -} - -// Set the indentation increment. -func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { - if indent < 2 || indent > 9 { - indent = 2 - } - emitter.best_indent = indent -} - -// Set the preferred line width. -func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { - if width < 0 { - width = -1 - } - emitter.best_width = width -} - -// Set if unescaped non-ASCII characters are allowed. -func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { - emitter.unicode = unicode -} - -// Set the preferred line break character. -func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { - emitter.line_break = line_break -} - -///* -// * Destroy a token object. -// */ -// -//YAML_DECLARE(void) -//yaml_token_delete(yaml_token_t *token) -//{ -// assert(token); // Non-NULL token object expected. -// -// switch (token.type) -// { -// case YAML_TAG_DIRECTIVE_TOKEN: -// yaml_free(token.data.tag_directive.handle); -// yaml_free(token.data.tag_directive.prefix); -// break; -// -// case YAML_ALIAS_TOKEN: -// yaml_free(token.data.alias.value); -// break; -// -// case YAML_ANCHOR_TOKEN: -// yaml_free(token.data.anchor.value); -// break; -// -// case YAML_TAG_TOKEN: -// yaml_free(token.data.tag.handle); -// yaml_free(token.data.tag.suffix); -// break; -// -// case YAML_SCALAR_TOKEN: -// yaml_free(token.data.scalar.value); -// break; -// -// default: -// break; -// } -// -// memset(token, 0, sizeof(yaml_token_t)); -//} -// -///* -// * Check if a string is a valid UTF-8 sequence. -// * -// * Check 'reader.c' for more details on UTF-8 encoding. -// */ -// -//static int -//yaml_check_utf8(yaml_char_t *start, size_t length) -//{ -// yaml_char_t *end = start+length; -// yaml_char_t *pointer = start; -// -// while (pointer < end) { -// unsigned char octet; -// unsigned int width; -// unsigned int value; -// size_t k; -// -// octet = pointer[0]; -// width = (octet & 0x80) == 0x00 ? 1 : -// (octet & 0xE0) == 0xC0 ? 2 : -// (octet & 0xF0) == 0xE0 ? 3 : -// (octet & 0xF8) == 0xF0 ? 4 : 0; -// value = (octet & 0x80) == 0x00 ? octet & 0x7F : -// (octet & 0xE0) == 0xC0 ? octet & 0x1F : -// (octet & 0xF0) == 0xE0 ? octet & 0x0F : -// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; -// if (!width) return 0; -// if (pointer+width > end) return 0; -// for (k = 1; k < width; k ++) { -// octet = pointer[k]; -// if ((octet & 0xC0) != 0x80) return 0; -// value = (value << 6) + (octet & 0x3F); -// } -// if (!((width == 1) || -// (width == 2 && value >= 0x80) || -// (width == 3 && value >= 0x800) || -// (width == 4 && value >= 0x10000))) return 0; -// -// pointer += width; -// } -// -// return 1; -//} -// - -// Create STREAM-START. -func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - encoding: encoding, - } -} - -// Create STREAM-END. -func yaml_stream_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - } -} - -// Create DOCUMENT-START. -func yaml_document_start_event_initialize( - event *yaml_event_t, - version_directive *yaml_version_directive_t, - tag_directives []yaml_tag_directive_t, - implicit bool, -) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: implicit, - } -} - -// Create DOCUMENT-END. -func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - implicit: implicit, - } -} - -// Create ALIAS. -func yaml_alias_event_initialize(event *yaml_event_t, anchor []byte) bool { - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - anchor: anchor, - } - return true -} - -// Create SCALAR. -func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - anchor: anchor, - tag: tag, - value: value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-START. -func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-END. -func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - } - return true -} - -// Create MAPPING-START. -func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } -} - -// Create MAPPING-END. -func yaml_mapping_end_event_initialize(event *yaml_event_t) { - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - } -} - -// Destroy an event object. -func yaml_event_delete(event *yaml_event_t) { - *event = yaml_event_t{} -} - -///* -// * Create a document object. -// */ -// -//YAML_DECLARE(int) -//yaml_document_initialize(document *yaml_document_t, -// version_directive *yaml_version_directive_t, -// tag_directives_start *yaml_tag_directive_t, -// tag_directives_end *yaml_tag_directive_t, -// start_implicit int, end_implicit int) -//{ -// struct { -// error yaml_error_type_t -// } context -// struct { -// start *yaml_node_t -// end *yaml_node_t -// top *yaml_node_t -// } nodes = { NULL, NULL, NULL } -// version_directive_copy *yaml_version_directive_t = NULL -// struct { -// start *yaml_tag_directive_t -// end *yaml_tag_directive_t -// top *yaml_tag_directive_t -// } tag_directives_copy = { NULL, NULL, NULL } -// value yaml_tag_directive_t = { NULL, NULL } -// mark yaml_mark_t = { 0, 0, 0 } -// -// assert(document) // Non-NULL document object is expected. -// assert((tag_directives_start && tag_directives_end) || -// (tag_directives_start == tag_directives_end)) -// // Valid tag directives are expected. -// -// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error -// -// if (version_directive) { -// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) -// if (!version_directive_copy) goto error -// version_directive_copy.major = version_directive.major -// version_directive_copy.minor = version_directive.minor -// } -// -// if (tag_directives_start != tag_directives_end) { -// tag_directive *yaml_tag_directive_t -// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) -// goto error -// for (tag_directive = tag_directives_start -// tag_directive != tag_directives_end; tag_directive ++) { -// assert(tag_directive.handle) -// assert(tag_directive.prefix) -// if (!yaml_check_utf8(tag_directive.handle, -// strlen((char *)tag_directive.handle))) -// goto error -// if (!yaml_check_utf8(tag_directive.prefix, -// strlen((char *)tag_directive.prefix))) -// goto error -// value.handle = yaml_strdup(tag_directive.handle) -// value.prefix = yaml_strdup(tag_directive.prefix) -// if (!value.handle || !value.prefix) goto error -// if (!PUSH(&context, tag_directives_copy, value)) -// goto error -// value.handle = NULL -// value.prefix = NULL -// } -// } -// -// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, -// tag_directives_copy.start, tag_directives_copy.top, -// start_implicit, end_implicit, mark, mark) -// -// return 1 -// -//error: -// STACK_DEL(&context, nodes) -// yaml_free(version_directive_copy) -// while (!STACK_EMPTY(&context, tag_directives_copy)) { -// value yaml_tag_directive_t = POP(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// } -// STACK_DEL(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// -// return 0 -//} -// -///* -// * Destroy a document object. -// */ -// -//YAML_DECLARE(void) -//yaml_document_delete(document *yaml_document_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// tag_directive *yaml_tag_directive_t -// -// context.error = YAML_NO_ERROR // Eliminate a compiler warning. -// -// assert(document) // Non-NULL document object is expected. -// -// while (!STACK_EMPTY(&context, document.nodes)) { -// node yaml_node_t = POP(&context, document.nodes) -// yaml_free(node.tag) -// switch (node.type) { -// case YAML_SCALAR_NODE: -// yaml_free(node.data.scalar.value) -// break -// case YAML_SEQUENCE_NODE: -// STACK_DEL(&context, node.data.sequence.items) -// break -// case YAML_MAPPING_NODE: -// STACK_DEL(&context, node.data.mapping.pairs) -// break -// default: -// assert(0) // Should not happen. -// } -// } -// STACK_DEL(&context, document.nodes) -// -// yaml_free(document.version_directive) -// for (tag_directive = document.tag_directives.start -// tag_directive != document.tag_directives.end -// tag_directive++) { -// yaml_free(tag_directive.handle) -// yaml_free(tag_directive.prefix) -// } -// yaml_free(document.tag_directives.start) -// -// memset(document, 0, sizeof(yaml_document_t)) -//} -// -///** -// * Get a document node. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_node(document *yaml_document_t, index int) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (index > 0 && document.nodes.start + index <= document.nodes.top) { -// return document.nodes.start + index - 1 -// } -// return NULL -//} -// -///** -// * Get the root object. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_root_node(document *yaml_document_t) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (document.nodes.top != document.nodes.start) { -// return document.nodes.start -// } -// return NULL -//} -// -///* -// * Add a scalar node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_scalar(document *yaml_document_t, -// tag *yaml_char_t, value *yaml_char_t, length int, -// style yaml_scalar_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// value_copy *yaml_char_t = NULL -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// assert(value) // Non-NULL value is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (length < 0) { -// length = strlen((char *)value) -// } -// -// if (!yaml_check_utf8(value, length)) goto error -// value_copy = yaml_malloc(length+1) -// if (!value_copy) goto error -// memcpy(value_copy, value, length) -// value_copy[length] = '\0' -// -// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// yaml_free(tag_copy) -// yaml_free(value_copy) -// -// return 0 -//} -// -///* -// * Add a sequence node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_sequence(document *yaml_document_t, -// tag *yaml_char_t, style yaml_sequence_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_item_t -// end *yaml_node_item_t -// top *yaml_node_item_t -// } items = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error -// -// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, items) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Add a mapping node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_mapping(document *yaml_document_t, -// tag *yaml_char_t, style yaml_mapping_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_pair_t -// end *yaml_node_pair_t -// top *yaml_node_pair_t -// } pairs = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error -// -// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, pairs) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Append an item to a sequence node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_sequence_item(document *yaml_document_t, -// sequence int, item int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// assert(document) // Non-NULL document is required. -// assert(sequence > 0 -// && document.nodes.start + sequence <= document.nodes.top) -// // Valid sequence id is required. -// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) -// // A sequence node is required. -// assert(item > 0 && document.nodes.start + item <= document.nodes.top) -// // Valid item id is required. -// -// if (!PUSH(&context, -// document.nodes.start[sequence-1].data.sequence.items, item)) -// return 0 -// -// return 1 -//} -// -///* -// * Append a pair of a key and a value to a mapping node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_mapping_pair(document *yaml_document_t, -// mapping int, key int, value int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// pair yaml_node_pair_t -// -// assert(document) // Non-NULL document is required. -// assert(mapping > 0 -// && document.nodes.start + mapping <= document.nodes.top) -// // Valid mapping id is required. -// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) -// // A mapping node is required. -// assert(key > 0 && document.nodes.start + key <= document.nodes.top) -// // Valid key id is required. -// assert(value > 0 && document.nodes.start + value <= document.nodes.top) -// // Valid value id is required. -// -// pair.key = key -// pair.value = value -// -// if (!PUSH(&context, -// document.nodes.start[mapping-1].data.mapping.pairs, pair)) -// return 0 -// -// return 1 -//} -// -// diff --git a/vendor/gopkg.in/yaml.v3/decode.go b/vendor/gopkg.in/yaml.v3/decode.go deleted file mode 100644 index 0173b69..0000000 --- a/vendor/gopkg.in/yaml.v3/decode.go +++ /dev/null @@ -1,1000 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// 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 yaml - -import ( - "encoding" - "encoding/base64" - "fmt" - "io" - "math" - "reflect" - "strconv" - "time" -) - -// ---------------------------------------------------------------------------- -// Parser, produces a node tree out of a libyaml event stream. - -type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *Node - anchors map[string]*Node - doneInit bool - textless bool -} - -func newParser(b []byte) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - if len(b) == 0 { - b = []byte{'\n'} - } - yaml_parser_set_input_string(&p.parser, b) - return &p -} - -func newParserFromReader(r io.Reader) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - yaml_parser_set_input_reader(&p.parser, r) - return &p -} - -func (p *parser) init() { - if p.doneInit { - return - } - p.anchors = make(map[string]*Node) - p.expect(yaml_STREAM_START_EVENT) - p.doneInit = true -} - -func (p *parser) destroy() { - if p.event.typ != yaml_NO_EVENT { - yaml_event_delete(&p.event) - } - yaml_parser_delete(&p.parser) -} - -// expect consumes an event from the event stream and -// checks that it's of the expected type. -func (p *parser) expect(e yaml_event_type_t) { - if p.event.typ == yaml_NO_EVENT { - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } - } - if p.event.typ == yaml_STREAM_END_EVENT { - failf("attempted to go past the end of stream; corrupted value?") - } - if p.event.typ != e { - p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) - p.fail() - } - yaml_event_delete(&p.event) - p.event.typ = yaml_NO_EVENT -} - -// peek peeks at the next event in the event stream, -// puts the results into p.event and returns the event type. -func (p *parser) peek() yaml_event_type_t { - if p.event.typ != yaml_NO_EVENT { - return p.event.typ - } - // It's curious choice from the underlying API to generally return a - // positive result on success, but on this case return true in an error - // scenario. This was the source of bugs in the past (issue #666). - if !yaml_parser_parse(&p.parser, &p.event) || p.parser.error != yaml_NO_ERROR { - p.fail() - } - return p.event.typ -} - -func (p *parser) fail() { - var where string - var line int - if p.parser.context_mark.line != 0 { - line = p.parser.context_mark.line - // Scanner errors don't iterate line before returning error - if p.parser.error == yaml_SCANNER_ERROR { - line++ - } - } else if p.parser.problem_mark.line != 0 { - line = p.parser.problem_mark.line - // Scanner errors don't iterate line before returning error - if p.parser.error == yaml_SCANNER_ERROR { - line++ - } - } - if line != 0 { - where = "line " + strconv.Itoa(line) + ": " - } - var msg string - if len(p.parser.problem) > 0 { - msg = p.parser.problem - } else { - msg = "unknown problem parsing YAML content" - } - failf("%s%s", where, msg) -} - -func (p *parser) anchor(n *Node, anchor []byte) { - if anchor != nil { - n.Anchor = string(anchor) - p.anchors[n.Anchor] = n - } -} - -func (p *parser) parse() *Node { - p.init() - switch p.peek() { - case yaml_SCALAR_EVENT: - return p.scalar() - case yaml_ALIAS_EVENT: - return p.alias() - case yaml_MAPPING_START_EVENT: - return p.mapping() - case yaml_SEQUENCE_START_EVENT: - return p.sequence() - case yaml_DOCUMENT_START_EVENT: - return p.document() - case yaml_STREAM_END_EVENT: - // Happens when attempting to decode an empty buffer. - return nil - case yaml_TAIL_COMMENT_EVENT: - panic("internal error: unexpected tail comment event (please report)") - default: - panic("internal error: attempted to parse unknown event (please report): " + p.event.typ.String()) - } -} - -func (p *parser) node(kind Kind, defaultTag, tag, value string) *Node { - var style Style - if tag != "" && tag != "!" { - tag = shortTag(tag) - style = TaggedStyle - } else if defaultTag != "" { - tag = defaultTag - } else if kind == ScalarNode { - tag, _ = resolve("", value) - } - n := &Node{ - Kind: kind, - Tag: tag, - Value: value, - Style: style, - } - if !p.textless { - n.Line = p.event.start_mark.line + 1 - n.Column = p.event.start_mark.column + 1 - n.HeadComment = string(p.event.head_comment) - n.LineComment = string(p.event.line_comment) - n.FootComment = string(p.event.foot_comment) - } - return n -} - -func (p *parser) parseChild(parent *Node) *Node { - child := p.parse() - parent.Content = append(parent.Content, child) - return child -} - -func (p *parser) document() *Node { - n := p.node(DocumentNode, "", "", "") - p.doc = n - p.expect(yaml_DOCUMENT_START_EVENT) - p.parseChild(n) - if p.peek() == yaml_DOCUMENT_END_EVENT { - n.FootComment = string(p.event.foot_comment) - } - p.expect(yaml_DOCUMENT_END_EVENT) - return n -} - -func (p *parser) alias() *Node { - n := p.node(AliasNode, "", "", string(p.event.anchor)) - n.Alias = p.anchors[n.Value] - if n.Alias == nil { - failf("unknown anchor '%s' referenced", n.Value) - } - p.expect(yaml_ALIAS_EVENT) - return n -} - -func (p *parser) scalar() *Node { - var parsedStyle = p.event.scalar_style() - var nodeStyle Style - switch { - case parsedStyle&yaml_DOUBLE_QUOTED_SCALAR_STYLE != 0: - nodeStyle = DoubleQuotedStyle - case parsedStyle&yaml_SINGLE_QUOTED_SCALAR_STYLE != 0: - nodeStyle = SingleQuotedStyle - case parsedStyle&yaml_LITERAL_SCALAR_STYLE != 0: - nodeStyle = LiteralStyle - case parsedStyle&yaml_FOLDED_SCALAR_STYLE != 0: - nodeStyle = FoldedStyle - } - var nodeValue = string(p.event.value) - var nodeTag = string(p.event.tag) - var defaultTag string - if nodeStyle == 0 { - if nodeValue == "<<" { - defaultTag = mergeTag - } - } else { - defaultTag = strTag - } - n := p.node(ScalarNode, defaultTag, nodeTag, nodeValue) - n.Style |= nodeStyle - p.anchor(n, p.event.anchor) - p.expect(yaml_SCALAR_EVENT) - return n -} - -func (p *parser) sequence() *Node { - n := p.node(SequenceNode, seqTag, string(p.event.tag), "") - if p.event.sequence_style()&yaml_FLOW_SEQUENCE_STYLE != 0 { - n.Style |= FlowStyle - } - p.anchor(n, p.event.anchor) - p.expect(yaml_SEQUENCE_START_EVENT) - for p.peek() != yaml_SEQUENCE_END_EVENT { - p.parseChild(n) - } - n.LineComment = string(p.event.line_comment) - n.FootComment = string(p.event.foot_comment) - p.expect(yaml_SEQUENCE_END_EVENT) - return n -} - -func (p *parser) mapping() *Node { - n := p.node(MappingNode, mapTag, string(p.event.tag), "") - block := true - if p.event.mapping_style()&yaml_FLOW_MAPPING_STYLE != 0 { - block = false - n.Style |= FlowStyle - } - p.anchor(n, p.event.anchor) - p.expect(yaml_MAPPING_START_EVENT) - for p.peek() != yaml_MAPPING_END_EVENT { - k := p.parseChild(n) - if block && k.FootComment != "" { - // Must be a foot comment for the prior value when being dedented. - if len(n.Content) > 2 { - n.Content[len(n.Content)-3].FootComment = k.FootComment - k.FootComment = "" - } - } - v := p.parseChild(n) - if k.FootComment == "" && v.FootComment != "" { - k.FootComment = v.FootComment - v.FootComment = "" - } - if p.peek() == yaml_TAIL_COMMENT_EVENT { - if k.FootComment == "" { - k.FootComment = string(p.event.foot_comment) - } - p.expect(yaml_TAIL_COMMENT_EVENT) - } - } - n.LineComment = string(p.event.line_comment) - n.FootComment = string(p.event.foot_comment) - if n.Style&FlowStyle == 0 && n.FootComment != "" && len(n.Content) > 1 { - n.Content[len(n.Content)-2].FootComment = n.FootComment - n.FootComment = "" - } - p.expect(yaml_MAPPING_END_EVENT) - return n -} - -// ---------------------------------------------------------------------------- -// Decoder, unmarshals a node into a provided value. - -type decoder struct { - doc *Node - aliases map[*Node]bool - terrors []string - - stringMapType reflect.Type - generalMapType reflect.Type - - knownFields bool - uniqueKeys bool - decodeCount int - aliasCount int - aliasDepth int - - mergedFields map[interface{}]bool -} - -var ( - nodeType = reflect.TypeOf(Node{}) - durationType = reflect.TypeOf(time.Duration(0)) - stringMapType = reflect.TypeOf(map[string]interface{}{}) - generalMapType = reflect.TypeOf(map[interface{}]interface{}{}) - ifaceType = generalMapType.Elem() - timeType = reflect.TypeOf(time.Time{}) - ptrTimeType = reflect.TypeOf(&time.Time{}) -) - -func newDecoder() *decoder { - d := &decoder{ - stringMapType: stringMapType, - generalMapType: generalMapType, - uniqueKeys: true, - } - d.aliases = make(map[*Node]bool) - return d -} - -func (d *decoder) terror(n *Node, tag string, out reflect.Value) { - if n.Tag != "" { - tag = n.Tag - } - value := n.Value - if tag != seqTag && tag != mapTag { - if len(value) > 10 { - value = " `" + value[:7] + "...`" - } else { - value = " `" + value + "`" - } - } - d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.Line, shortTag(tag), value, out.Type())) -} - -func (d *decoder) callUnmarshaler(n *Node, u Unmarshaler) (good bool) { - err := u.UnmarshalYAML(n) - if e, ok := err.(*TypeError); ok { - d.terrors = append(d.terrors, e.Errors...) - return false - } - if err != nil { - fail(err) - } - return true -} - -func (d *decoder) callObsoleteUnmarshaler(n *Node, u obsoleteUnmarshaler) (good bool) { - terrlen := len(d.terrors) - err := u.UnmarshalYAML(func(v interface{}) (err error) { - defer handleErr(&err) - d.unmarshal(n, reflect.ValueOf(v)) - if len(d.terrors) > terrlen { - issues := d.terrors[terrlen:] - d.terrors = d.terrors[:terrlen] - return &TypeError{issues} - } - return nil - }) - if e, ok := err.(*TypeError); ok { - d.terrors = append(d.terrors, e.Errors...) - return false - } - if err != nil { - fail(err) - } - return true -} - -// d.prepare initializes and dereferences pointers and calls UnmarshalYAML -// if a value is found to implement it. -// It returns the initialized and dereferenced out value, whether -// unmarshalling was already done by UnmarshalYAML, and if so whether -// its types unmarshalled appropriately. -// -// If n holds a null value, prepare returns before doing anything. -func (d *decoder) prepare(n *Node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { - if n.ShortTag() == nullTag { - return out, false, false - } - again := true - for again { - again = false - if out.Kind() == reflect.Ptr { - if out.IsNil() { - out.Set(reflect.New(out.Type().Elem())) - } - out = out.Elem() - again = true - } - if out.CanAddr() { - outi := out.Addr().Interface() - if u, ok := outi.(Unmarshaler); ok { - good = d.callUnmarshaler(n, u) - return out, true, good - } - if u, ok := outi.(obsoleteUnmarshaler); ok { - good = d.callObsoleteUnmarshaler(n, u) - return out, true, good - } - } - } - return out, false, false -} - -func (d *decoder) fieldByIndex(n *Node, v reflect.Value, index []int) (field reflect.Value) { - if n.ShortTag() == nullTag { - return reflect.Value{} - } - for _, num := range index { - for { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - continue - } - break - } - v = v.Field(num) - } - return v -} - -const ( - // 400,000 decode operations is ~500kb of dense object declarations, or - // ~5kb of dense object declarations with 10000% alias expansion - alias_ratio_range_low = 400000 - - // 4,000,000 decode operations is ~5MB of dense object declarations, or - // ~4.5MB of dense object declarations with 10% alias expansion - alias_ratio_range_high = 4000000 - - // alias_ratio_range is the range over which we scale allowed alias ratios - alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) -) - -func allowedAliasRatio(decodeCount int) float64 { - switch { - case decodeCount <= alias_ratio_range_low: - // allow 99% to come from alias expansion for small-to-medium documents - return 0.99 - case decodeCount >= alias_ratio_range_high: - // allow 10% to come from alias expansion for very large documents - return 0.10 - default: - // scale smoothly from 99% down to 10% over the range. - // this maps to 396,000 - 400,000 allowed alias-driven decodes over the range. - // 400,000 decode operations is ~100MB of allocations in worst-case scenarios (single-item maps). - return 0.99 - 0.89*(float64(decodeCount-alias_ratio_range_low)/alias_ratio_range) - } -} - -func (d *decoder) unmarshal(n *Node, out reflect.Value) (good bool) { - d.decodeCount++ - if d.aliasDepth > 0 { - d.aliasCount++ - } - if d.aliasCount > 100 && d.decodeCount > 1000 && float64(d.aliasCount)/float64(d.decodeCount) > allowedAliasRatio(d.decodeCount) { - failf("document contains excessive aliasing") - } - if out.Type() == nodeType { - out.Set(reflect.ValueOf(n).Elem()) - return true - } - switch n.Kind { - case DocumentNode: - return d.document(n, out) - case AliasNode: - return d.alias(n, out) - } - out, unmarshaled, good := d.prepare(n, out) - if unmarshaled { - return good - } - switch n.Kind { - case ScalarNode: - good = d.scalar(n, out) - case MappingNode: - good = d.mapping(n, out) - case SequenceNode: - good = d.sequence(n, out) - case 0: - if n.IsZero() { - return d.null(out) - } - fallthrough - default: - failf("cannot decode node with unknown kind %d", n.Kind) - } - return good -} - -func (d *decoder) document(n *Node, out reflect.Value) (good bool) { - if len(n.Content) == 1 { - d.doc = n - d.unmarshal(n.Content[0], out) - return true - } - return false -} - -func (d *decoder) alias(n *Node, out reflect.Value) (good bool) { - if d.aliases[n] { - // TODO this could actually be allowed in some circumstances. - failf("anchor '%s' value contains itself", n.Value) - } - d.aliases[n] = true - d.aliasDepth++ - good = d.unmarshal(n.Alias, out) - d.aliasDepth-- - delete(d.aliases, n) - return good -} - -var zeroValue reflect.Value - -func resetMap(out reflect.Value) { - for _, k := range out.MapKeys() { - out.SetMapIndex(k, zeroValue) - } -} - -func (d *decoder) null(out reflect.Value) bool { - if out.CanAddr() { - switch out.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - out.Set(reflect.Zero(out.Type())) - return true - } - } - return false -} - -func (d *decoder) scalar(n *Node, out reflect.Value) bool { - var tag string - var resolved interface{} - if n.indicatedString() { - tag = strTag - resolved = n.Value - } else { - tag, resolved = resolve(n.Tag, n.Value) - if tag == binaryTag { - data, err := base64.StdEncoding.DecodeString(resolved.(string)) - if err != nil { - failf("!!binary value contains invalid base64 data") - } - resolved = string(data) - } - } - if resolved == nil { - return d.null(out) - } - if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { - // We've resolved to exactly the type we want, so use that. - out.Set(resolvedv) - return true - } - // Perhaps we can use the value as a TextUnmarshaler to - // set its value. - if out.CanAddr() { - u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) - if ok { - var text []byte - if tag == binaryTag { - text = []byte(resolved.(string)) - } else { - // We let any value be unmarshaled into TextUnmarshaler. - // That might be more lax than we'd like, but the - // TextUnmarshaler itself should bowl out any dubious values. - text = []byte(n.Value) - } - err := u.UnmarshalText(text) - if err != nil { - fail(err) - } - return true - } - } - switch out.Kind() { - case reflect.String: - if tag == binaryTag { - out.SetString(resolved.(string)) - return true - } - out.SetString(n.Value) - return true - case reflect.Interface: - out.Set(reflect.ValueOf(resolved)) - return true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - // This used to work in v2, but it's very unfriendly. - isDuration := out.Type() == durationType - - switch resolved := resolved.(type) { - case int: - if !isDuration && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case int64: - if !isDuration && !out.OverflowInt(resolved) { - out.SetInt(resolved) - return true - } - case uint64: - if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case float64: - if !isDuration && resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - return true - } - case string: - if out.Type() == durationType { - d, err := time.ParseDuration(resolved) - if err == nil { - out.SetInt(int64(d)) - return true - } - } - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch resolved := resolved.(type) { - case int: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case int64: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case uint64: - if !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - case float64: - if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - return true - } - } - case reflect.Bool: - switch resolved := resolved.(type) { - case bool: - out.SetBool(resolved) - return true - case string: - // This offers some compatibility with the 1.1 spec (https://yaml.org/type/bool.html). - // It only works if explicitly attempting to unmarshal into a typed bool value. - switch resolved { - case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON": - out.SetBool(true) - return true - case "n", "N", "no", "No", "NO", "off", "Off", "OFF": - out.SetBool(false) - return true - } - } - case reflect.Float32, reflect.Float64: - switch resolved := resolved.(type) { - case int: - out.SetFloat(float64(resolved)) - return true - case int64: - out.SetFloat(float64(resolved)) - return true - case uint64: - out.SetFloat(float64(resolved)) - return true - case float64: - out.SetFloat(resolved) - return true - } - case reflect.Struct: - if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { - out.Set(resolvedv) - return true - } - case reflect.Ptr: - panic("yaml internal error: please report the issue") - } - d.terror(n, tag, out) - return false -} - -func settableValueOf(i interface{}) reflect.Value { - v := reflect.ValueOf(i) - sv := reflect.New(v.Type()).Elem() - sv.Set(v) - return sv -} - -func (d *decoder) sequence(n *Node, out reflect.Value) (good bool) { - l := len(n.Content) - - var iface reflect.Value - switch out.Kind() { - case reflect.Slice: - out.Set(reflect.MakeSlice(out.Type(), l, l)) - case reflect.Array: - if l != out.Len() { - failf("invalid array: want %d elements but got %d", out.Len(), l) - } - case reflect.Interface: - // No type hints. Will have to use a generic sequence. - iface = out - out = settableValueOf(make([]interface{}, l)) - default: - d.terror(n, seqTag, out) - return false - } - et := out.Type().Elem() - - j := 0 - for i := 0; i < l; i++ { - e := reflect.New(et).Elem() - if ok := d.unmarshal(n.Content[i], e); ok { - out.Index(j).Set(e) - j++ - } - } - if out.Kind() != reflect.Array { - out.Set(out.Slice(0, j)) - } - if iface.IsValid() { - iface.Set(out) - } - return true -} - -func (d *decoder) mapping(n *Node, out reflect.Value) (good bool) { - l := len(n.Content) - if d.uniqueKeys { - nerrs := len(d.terrors) - for i := 0; i < l; i += 2 { - ni := n.Content[i] - for j := i + 2; j < l; j += 2 { - nj := n.Content[j] - if ni.Kind == nj.Kind && ni.Value == nj.Value { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: mapping key %#v already defined at line %d", nj.Line, nj.Value, ni.Line)) - } - } - } - if len(d.terrors) > nerrs { - return false - } - } - switch out.Kind() { - case reflect.Struct: - return d.mappingStruct(n, out) - case reflect.Map: - // okay - case reflect.Interface: - iface := out - if isStringMap(n) { - out = reflect.MakeMap(d.stringMapType) - } else { - out = reflect.MakeMap(d.generalMapType) - } - iface.Set(out) - default: - d.terror(n, mapTag, out) - return false - } - - outt := out.Type() - kt := outt.Key() - et := outt.Elem() - - stringMapType := d.stringMapType - generalMapType := d.generalMapType - if outt.Elem() == ifaceType { - if outt.Key().Kind() == reflect.String { - d.stringMapType = outt - } else if outt.Key() == ifaceType { - d.generalMapType = outt - } - } - - mergedFields := d.mergedFields - d.mergedFields = nil - - var mergeNode *Node - - mapIsNew := false - if out.IsNil() { - out.Set(reflect.MakeMap(outt)) - mapIsNew = true - } - for i := 0; i < l; i += 2 { - if isMerge(n.Content[i]) { - mergeNode = n.Content[i+1] - continue - } - k := reflect.New(kt).Elem() - if d.unmarshal(n.Content[i], k) { - if mergedFields != nil { - ki := k.Interface() - if mergedFields[ki] { - continue - } - mergedFields[ki] = true - } - kkind := k.Kind() - if kkind == reflect.Interface { - kkind = k.Elem().Kind() - } - if kkind == reflect.Map || kkind == reflect.Slice { - failf("invalid map key: %#v", k.Interface()) - } - e := reflect.New(et).Elem() - if d.unmarshal(n.Content[i+1], e) || n.Content[i+1].ShortTag() == nullTag && (mapIsNew || !out.MapIndex(k).IsValid()) { - out.SetMapIndex(k, e) - } - } - } - - d.mergedFields = mergedFields - if mergeNode != nil { - d.merge(n, mergeNode, out) - } - - d.stringMapType = stringMapType - d.generalMapType = generalMapType - return true -} - -func isStringMap(n *Node) bool { - if n.Kind != MappingNode { - return false - } - l := len(n.Content) - for i := 0; i < l; i += 2 { - shortTag := n.Content[i].ShortTag() - if shortTag != strTag && shortTag != mergeTag { - return false - } - } - return true -} - -func (d *decoder) mappingStruct(n *Node, out reflect.Value) (good bool) { - sinfo, err := getStructInfo(out.Type()) - if err != nil { - panic(err) - } - - var inlineMap reflect.Value - var elemType reflect.Type - if sinfo.InlineMap != -1 { - inlineMap = out.Field(sinfo.InlineMap) - elemType = inlineMap.Type().Elem() - } - - for _, index := range sinfo.InlineUnmarshalers { - field := d.fieldByIndex(n, out, index) - d.prepare(n, field) - } - - mergedFields := d.mergedFields - d.mergedFields = nil - var mergeNode *Node - var doneFields []bool - if d.uniqueKeys { - doneFields = make([]bool, len(sinfo.FieldsList)) - } - name := settableValueOf("") - l := len(n.Content) - for i := 0; i < l; i += 2 { - ni := n.Content[i] - if isMerge(ni) { - mergeNode = n.Content[i+1] - continue - } - if !d.unmarshal(ni, name) { - continue - } - sname := name.String() - if mergedFields != nil { - if mergedFields[sname] { - continue - } - mergedFields[sname] = true - } - if info, ok := sinfo.FieldsMap[sname]; ok { - if d.uniqueKeys { - if doneFields[info.Id] { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.Line, name.String(), out.Type())) - continue - } - doneFields[info.Id] = true - } - var field reflect.Value - if info.Inline == nil { - field = out.Field(info.Num) - } else { - field = d.fieldByIndex(n, out, info.Inline) - } - d.unmarshal(n.Content[i+1], field) - } else if sinfo.InlineMap != -1 { - if inlineMap.IsNil() { - inlineMap.Set(reflect.MakeMap(inlineMap.Type())) - } - value := reflect.New(elemType).Elem() - d.unmarshal(n.Content[i+1], value) - inlineMap.SetMapIndex(name, value) - } else if d.knownFields { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.Line, name.String(), out.Type())) - } - } - - d.mergedFields = mergedFields - if mergeNode != nil { - d.merge(n, mergeNode, out) - } - return true -} - -func failWantMap() { - failf("map merge requires map or sequence of maps as the value") -} - -func (d *decoder) merge(parent *Node, merge *Node, out reflect.Value) { - mergedFields := d.mergedFields - if mergedFields == nil { - d.mergedFields = make(map[interface{}]bool) - for i := 0; i < len(parent.Content); i += 2 { - k := reflect.New(ifaceType).Elem() - if d.unmarshal(parent.Content[i], k) { - d.mergedFields[k.Interface()] = true - } - } - } - - switch merge.Kind { - case MappingNode: - d.unmarshal(merge, out) - case AliasNode: - if merge.Alias != nil && merge.Alias.Kind != MappingNode { - failWantMap() - } - d.unmarshal(merge, out) - case SequenceNode: - for i := 0; i < len(merge.Content); i++ { - ni := merge.Content[i] - if ni.Kind == AliasNode { - if ni.Alias != nil && ni.Alias.Kind != MappingNode { - failWantMap() - } - } else if ni.Kind != MappingNode { - failWantMap() - } - d.unmarshal(ni, out) - } - default: - failWantMap() - } - - d.mergedFields = mergedFields -} - -func isMerge(n *Node) bool { - return n.Kind == ScalarNode && n.Value == "<<" && (n.Tag == "" || n.Tag == "!" || shortTag(n.Tag) == mergeTag) -} diff --git a/vendor/gopkg.in/yaml.v3/emitterc.go b/vendor/gopkg.in/yaml.v3/emitterc.go deleted file mode 100644 index 0f47c9c..0000000 --- a/vendor/gopkg.in/yaml.v3/emitterc.go +++ /dev/null @@ -1,2020 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -import ( - "bytes" - "fmt" -) - -// Flush the buffer if needed. -func flush(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) { - return yaml_emitter_flush(emitter) - } - return true -} - -// Put a character to the output buffer. -func put(emitter *yaml_emitter_t, value byte) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - emitter.buffer[emitter.buffer_pos] = value - emitter.buffer_pos++ - emitter.column++ - return true -} - -// Put a line break to the output buffer. -func put_break(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - switch emitter.line_break { - case yaml_CR_BREAK: - emitter.buffer[emitter.buffer_pos] = '\r' - emitter.buffer_pos += 1 - case yaml_LN_BREAK: - emitter.buffer[emitter.buffer_pos] = '\n' - emitter.buffer_pos += 1 - case yaml_CRLN_BREAK: - emitter.buffer[emitter.buffer_pos+0] = '\r' - emitter.buffer[emitter.buffer_pos+1] = '\n' - emitter.buffer_pos += 2 - default: - panic("unknown line break setting") - } - if emitter.column == 0 { - emitter.space_above = true - } - emitter.column = 0 - emitter.line++ - // [Go] Do this here and below and drop from everywhere else (see commented lines). - emitter.indention = true - return true -} - -// Copy a character from a string into buffer. -func write(emitter *yaml_emitter_t, s []byte, i *int) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - p := emitter.buffer_pos - w := width(s[*i]) - switch w { - case 4: - emitter.buffer[p+3] = s[*i+3] - fallthrough - case 3: - emitter.buffer[p+2] = s[*i+2] - fallthrough - case 2: - emitter.buffer[p+1] = s[*i+1] - fallthrough - case 1: - emitter.buffer[p+0] = s[*i+0] - default: - panic("unknown character width") - } - emitter.column++ - emitter.buffer_pos += w - *i += w - return true -} - -// Write a whole string into buffer. -func write_all(emitter *yaml_emitter_t, s []byte) bool { - for i := 0; i < len(s); { - if !write(emitter, s, &i) { - return false - } - } - return true -} - -// Copy a line break character from a string into buffer. -func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { - if s[*i] == '\n' { - if !put_break(emitter) { - return false - } - *i++ - } else { - if !write(emitter, s, i) { - return false - } - if emitter.column == 0 { - emitter.space_above = true - } - emitter.column = 0 - emitter.line++ - // [Go] Do this here and above and drop from everywhere else (see commented lines). - emitter.indention = true - } - return true -} - -// Set an emitter error and return false. -func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_EMITTER_ERROR - emitter.problem = problem - return false -} - -// Emit an event. -func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.events = append(emitter.events, *event) - for !yaml_emitter_need_more_events(emitter) { - event := &emitter.events[emitter.events_head] - if !yaml_emitter_analyze_event(emitter, event) { - return false - } - if !yaml_emitter_state_machine(emitter, event) { - return false - } - yaml_event_delete(event) - emitter.events_head++ - } - return true -} - -// Check if we need to accumulate more events before emitting. -// -// We accumulate extra -// - 1 event for DOCUMENT-START -// - 2 events for SEQUENCE-START -// - 3 events for MAPPING-START -// -func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { - if emitter.events_head == len(emitter.events) { - return true - } - var accumulate int - switch emitter.events[emitter.events_head].typ { - case yaml_DOCUMENT_START_EVENT: - accumulate = 1 - break - case yaml_SEQUENCE_START_EVENT: - accumulate = 2 - break - case yaml_MAPPING_START_EVENT: - accumulate = 3 - break - default: - return false - } - if len(emitter.events)-emitter.events_head > accumulate { - return false - } - var level int - for i := emitter.events_head; i < len(emitter.events); i++ { - switch emitter.events[i].typ { - case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: - level++ - case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: - level-- - } - if level == 0 { - return false - } - } - return true -} - -// Append a directive to the directives stack. -func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { - for i := 0; i < len(emitter.tag_directives); i++ { - if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") - } - } - - // [Go] Do we actually need to copy this given garbage collection - // and the lack of deallocating destructors? - tag_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(tag_copy.handle, value.handle) - copy(tag_copy.prefix, value.prefix) - emitter.tag_directives = append(emitter.tag_directives, tag_copy) - return true -} - -// Increase the indentation level. -func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { - emitter.indents = append(emitter.indents, emitter.indent) - if emitter.indent < 0 { - if flow { - emitter.indent = emitter.best_indent - } else { - emitter.indent = 0 - } - } else if !indentless { - // [Go] This was changed so that indentations are more regular. - if emitter.states[len(emitter.states)-1] == yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE { - // The first indent inside a sequence will just skip the "- " indicator. - emitter.indent += 2 - } else { - // Everything else aligns to the chosen indentation. - emitter.indent = emitter.best_indent*((emitter.indent+emitter.best_indent)/emitter.best_indent) - } - } - return true -} - -// State dispatcher. -func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { - switch emitter.state { - default: - case yaml_EMIT_STREAM_START_STATE: - return yaml_emitter_emit_stream_start(emitter, event) - - case yaml_EMIT_FIRST_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, true) - - case yaml_EMIT_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, false) - - case yaml_EMIT_DOCUMENT_CONTENT_STATE: - return yaml_emitter_emit_document_content(emitter, event) - - case yaml_EMIT_DOCUMENT_END_STATE: - return yaml_emitter_emit_document_end(emitter, event) - - case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, true, false) - - case yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false, true) - - case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false, false) - - case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, true, false) - - case yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false, true) - - case yaml_EMIT_FLOW_MAPPING_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false, false) - - case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, true) - - case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, false) - - case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, true) - - case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, false) - - case yaml_EMIT_END_STATE: - return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") - } - panic("invalid emitter state") -} - -// Expect STREAM-START. -func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_STREAM_START_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") - } - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = event.encoding - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = yaml_UTF8_ENCODING - } - } - if emitter.best_indent < 2 || emitter.best_indent > 9 { - emitter.best_indent = 2 - } - if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { - emitter.best_width = 80 - } - if emitter.best_width < 0 { - emitter.best_width = 1<<31 - 1 - } - if emitter.line_break == yaml_ANY_BREAK { - emitter.line_break = yaml_LN_BREAK - } - - emitter.indent = -1 - emitter.line = 0 - emitter.column = 0 - emitter.whitespace = true - emitter.indention = true - emitter.space_above = true - emitter.foot_indent = -1 - - if emitter.encoding != yaml_UTF8_ENCODING { - if !yaml_emitter_write_bom(emitter) { - return false - } - } - emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE - return true -} - -// Expect DOCUMENT-START or STREAM-END. -func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - - if event.typ == yaml_DOCUMENT_START_EVENT { - - if event.version_directive != nil { - if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { - return false - } - } - - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { - return false - } - if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { - return false - } - } - - for i := 0; i < len(default_tag_directives); i++ { - tag_directive := &default_tag_directives[i] - if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { - return false - } - } - - implicit := event.implicit - if !first || emitter.canonical { - implicit = false - } - - if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if event.version_directive != nil { - implicit = false - if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if len(event.tag_directives) > 0 { - implicit = false - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { - return false - } - if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - if yaml_emitter_check_empty_document(emitter) { - implicit = false - } - if !implicit { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { - return false - } - if emitter.canonical || true { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - if len(emitter.head_comment) > 0 { - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if !put_break(emitter) { - return false - } - } - - emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE - return true - } - - if event.typ == yaml_STREAM_END_EVENT { - if emitter.open_ended { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_END_STATE - return true - } - - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") -} - -// Expect the root node. -func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) - - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if !yaml_emitter_emit_node(emitter, event, true, false, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect DOCUMENT-END. -func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_DOCUMENT_END_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") - } - // [Go] Force document foot separation. - emitter.foot_indent = 0 - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - emitter.foot_indent = -1 - if !yaml_emitter_write_indent(emitter) { - return false - } - if !event.implicit { - // [Go] Allocate the slice elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_DOCUMENT_START_STATE - emitter.tag_directives = emitter.tag_directives[:0] - return true -} - -// Expect a flow item node. -func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_SEQUENCE_END_EVENT { - if emitter.canonical && !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.column == 0 || emitter.canonical && !first { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - - return true - } - - if !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if emitter.column == 0 { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE) - } else { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) - } - if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { - return false - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect a flow key node. -func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first, trail bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_MAPPING_END_EVENT { - if (emitter.canonical || len(emitter.head_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0) && !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if !yaml_emitter_process_head_comment(emitter) { - return false - } - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - - if !first && !trail { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - - if !yaml_emitter_process_head_comment(emitter) { - return false - } - - if emitter.column == 0 { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a flow value node. -func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { - return false - } - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE) - } else { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) - } - if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { - return false - } - if len(emitter.line_comment)+len(emitter.foot_comment)+len(emitter.tail_comment) > 0 { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect a block item node. -func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, false) { - return false - } - } - if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) - if !yaml_emitter_emit_node(emitter, event, false, true, false, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -// Expect a block key node. -func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, false) { - return false - } - } - if !yaml_emitter_process_head_comment(emitter) { - return false - } - if event.typ == yaml_MAPPING_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if len(emitter.line_comment) > 0 { - // [Go] A line comment was provided for the key. That's unusual as the - // scanner associates line comments with the value. Either way, - // save the line comment and render it appropriately later. - emitter.key_line_comment = emitter.line_comment - emitter.line_comment = nil - } - if yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a block value node. -func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { - return false - } - } - if len(emitter.key_line_comment) > 0 { - // [Go] Line comments are generally associated with the value, but when there's - // no value on the same line as a mapping key they end up attached to the - // key itself. - if event.typ == yaml_SCALAR_EVENT { - if len(emitter.line_comment) == 0 { - // A scalar is coming and it has no line comments by itself yet, - // so just let it handle the line comment as usual. If it has a - // line comment, we can't have both so the one from the key is lost. - emitter.line_comment = emitter.key_line_comment - emitter.key_line_comment = nil - } - } else if event.sequence_style() != yaml_FLOW_SEQUENCE_STYLE && (event.typ == yaml_MAPPING_START_EVENT || event.typ == yaml_SEQUENCE_START_EVENT) { - // An indented block follows, so write the comment right now. - emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment - if !yaml_emitter_process_line_comment(emitter) { - return false - } - emitter.line_comment, emitter.key_line_comment = emitter.key_line_comment, emitter.line_comment - } - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) - if !yaml_emitter_emit_node(emitter, event, false, false, true, false) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - if !yaml_emitter_process_foot_comment(emitter) { - return false - } - return true -} - -func yaml_emitter_silent_nil_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - return event.typ == yaml_SCALAR_EVENT && event.implicit && !emitter.canonical && len(emitter.scalar_data.value) == 0 -} - -// Expect a node. -func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, - root bool, sequence bool, mapping bool, simple_key bool) bool { - - emitter.root_context = root - emitter.sequence_context = sequence - emitter.mapping_context = mapping - emitter.simple_key_context = simple_key - - switch event.typ { - case yaml_ALIAS_EVENT: - return yaml_emitter_emit_alias(emitter, event) - case yaml_SCALAR_EVENT: - return yaml_emitter_emit_scalar(emitter, event) - case yaml_SEQUENCE_START_EVENT: - return yaml_emitter_emit_sequence_start(emitter, event) - case yaml_MAPPING_START_EVENT: - return yaml_emitter_emit_mapping_start(emitter, event) - default: - return yaml_emitter_set_emitter_error(emitter, - fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) - } -} - -// Expect ALIAS. -func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SCALAR. -func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_select_scalar_style(emitter, event) { - return false - } - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - if !yaml_emitter_process_scalar(emitter) { - return false - } - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SEQUENCE-START. -func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || - yaml_emitter_check_empty_sequence(emitter) { - emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE - } - return true -} - -// Expect MAPPING-START. -func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || - yaml_emitter_check_empty_mapping(emitter) { - emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE - } - return true -} - -// Check if the document content is an empty scalar. -func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { - return false // [Go] Huh? -} - -// Check if the next events represent an empty sequence. -func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT -} - -// Check if the next events represent an empty mapping. -func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT -} - -// Check if the next node can be expressed as a simple key. -func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { - length := 0 - switch emitter.events[emitter.events_head].typ { - case yaml_ALIAS_EVENT: - length += len(emitter.anchor_data.anchor) - case yaml_SCALAR_EVENT: - if emitter.scalar_data.multiline { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) + - len(emitter.scalar_data.value) - case yaml_SEQUENCE_START_EVENT: - if !yaml_emitter_check_empty_sequence(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - case yaml_MAPPING_START_EVENT: - if !yaml_emitter_check_empty_mapping(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - default: - return false - } - return length <= 128 -} - -// Determine an acceptable scalar style. -func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 - if no_tag && !event.implicit && !event.quoted_implicit { - return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") - } - - style := event.scalar_style() - if style == yaml_ANY_SCALAR_STYLE { - style = yaml_PLAIN_SCALAR_STYLE - } - if emitter.canonical { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - if emitter.simple_key_context && emitter.scalar_data.multiline { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - - if style == yaml_PLAIN_SCALAR_STYLE { - if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || - emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if no_tag && !event.implicit { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { - if !emitter.scalar_data.single_quoted_allowed { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { - if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - - if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { - emitter.tag_data.handle = []byte{'!'} - } - emitter.scalar_data.style = style - return true -} - -// Write an anchor. -func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { - if emitter.anchor_data.anchor == nil { - return true - } - c := []byte{'&'} - if emitter.anchor_data.alias { - c[0] = '*' - } - if !yaml_emitter_write_indicator(emitter, c, true, false, false) { - return false - } - return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) -} - -// Write a tag. -func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { - if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { - return true - } - if len(emitter.tag_data.handle) > 0 { - if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { - return false - } - if len(emitter.tag_data.suffix) > 0 { - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - } - } else { - // [Go] Allocate these slices elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { - return false - } - } - return true -} - -// Write a scalar. -func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { - switch emitter.scalar_data.style { - case yaml_PLAIN_SCALAR_STYLE: - return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_SINGLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_DOUBLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_LITERAL_SCALAR_STYLE: - return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) - - case yaml_FOLDED_SCALAR_STYLE: - return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) - } - panic("unknown scalar style") -} - -// Write a head comment. -func yaml_emitter_process_head_comment(emitter *yaml_emitter_t) bool { - if len(emitter.tail_comment) > 0 { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_comment(emitter, emitter.tail_comment) { - return false - } - emitter.tail_comment = emitter.tail_comment[:0] - emitter.foot_indent = emitter.indent - if emitter.foot_indent < 0 { - emitter.foot_indent = 0 - } - } - - if len(emitter.head_comment) == 0 { - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_comment(emitter, emitter.head_comment) { - return false - } - emitter.head_comment = emitter.head_comment[:0] - return true -} - -// Write an line comment. -func yaml_emitter_process_line_comment(emitter *yaml_emitter_t) bool { - if len(emitter.line_comment) == 0 { - return true - } - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !yaml_emitter_write_comment(emitter, emitter.line_comment) { - return false - } - emitter.line_comment = emitter.line_comment[:0] - return true -} - -// Write a foot comment. -func yaml_emitter_process_foot_comment(emitter *yaml_emitter_t) bool { - if len(emitter.foot_comment) == 0 { - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_comment(emitter, emitter.foot_comment) { - return false - } - emitter.foot_comment = emitter.foot_comment[:0] - emitter.foot_indent = emitter.indent - if emitter.foot_indent < 0 { - emitter.foot_indent = 0 - } - return true -} - -// Check if a %YAML directive is valid. -func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { - if version_directive.major != 1 || version_directive.minor != 1 { - return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") - } - return true -} - -// Check if a %TAG directive is valid. -func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { - handle := tag_directive.handle - prefix := tag_directive.prefix - if len(handle) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") - } - if handle[0] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") - } - if handle[len(handle)-1] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") - } - for i := 1; i < len(handle)-1; i += width(handle[i]) { - if !is_alpha(handle, i) { - return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") - } - } - if len(prefix) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") - } - return true -} - -// Check if an anchor is valid. -func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { - if len(anchor) == 0 { - problem := "anchor value must not be empty" - if alias { - problem = "alias value must not be empty" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - for i := 0; i < len(anchor); i += width(anchor[i]) { - if !is_alpha(anchor, i) { - problem := "anchor value must contain alphanumerical characters only" - if alias { - problem = "alias value must contain alphanumerical characters only" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - } - emitter.anchor_data.anchor = anchor - emitter.anchor_data.alias = alias - return true -} - -// Check if a tag is valid. -func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { - if len(tag) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") - } - for i := 0; i < len(emitter.tag_directives); i++ { - tag_directive := &emitter.tag_directives[i] - if bytes.HasPrefix(tag, tag_directive.prefix) { - emitter.tag_data.handle = tag_directive.handle - emitter.tag_data.suffix = tag[len(tag_directive.prefix):] - return true - } - } - emitter.tag_data.suffix = tag - return true -} - -// Check if a scalar is valid. -func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { - var ( - block_indicators = false - flow_indicators = false - line_breaks = false - special_characters = false - tab_characters = false - - leading_space = false - leading_break = false - trailing_space = false - trailing_break = false - break_space = false - space_break = false - - preceded_by_whitespace = false - followed_by_whitespace = false - previous_space = false - previous_break = false - ) - - emitter.scalar_data.value = value - - if len(value) == 0 { - emitter.scalar_data.multiline = false - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = false - return true - } - - if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { - block_indicators = true - flow_indicators = true - } - - preceded_by_whitespace = true - for i, w := 0, 0; i < len(value); i += w { - w = width(value[i]) - followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) - - if i == 0 { - switch value[i] { - case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': - flow_indicators = true - block_indicators = true - case '?', ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '-': - if followed_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } else { - switch value[i] { - case ',', '?', '[', ']', '{', '}': - flow_indicators = true - case ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '#': - if preceded_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } - - if value[i] == '\t' { - tab_characters = true - } else if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { - special_characters = true - } - if is_space(value, i) { - if i == 0 { - leading_space = true - } - if i+width(value[i]) == len(value) { - trailing_space = true - } - if previous_break { - break_space = true - } - previous_space = true - previous_break = false - } else if is_break(value, i) { - line_breaks = true - if i == 0 { - leading_break = true - } - if i+width(value[i]) == len(value) { - trailing_break = true - } - if previous_space { - space_break = true - } - previous_space = false - previous_break = true - } else { - previous_space = false - previous_break = false - } - - // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. - preceded_by_whitespace = is_blankz(value, i) - } - - emitter.scalar_data.multiline = line_breaks - emitter.scalar_data.flow_plain_allowed = true - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = true - - if leading_space || leading_break || trailing_space || trailing_break { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if trailing_space { - emitter.scalar_data.block_allowed = false - } - if break_space { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - } - if space_break || tab_characters || special_characters { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - } - if space_break || special_characters { - emitter.scalar_data.block_allowed = false - } - if line_breaks { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if flow_indicators { - emitter.scalar_data.flow_plain_allowed = false - } - if block_indicators { - emitter.scalar_data.block_plain_allowed = false - } - return true -} - -// Check if the event data is valid. -func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - emitter.anchor_data.anchor = nil - emitter.tag_data.handle = nil - emitter.tag_data.suffix = nil - emitter.scalar_data.value = nil - - if len(event.head_comment) > 0 { - emitter.head_comment = event.head_comment - } - if len(event.line_comment) > 0 { - emitter.line_comment = event.line_comment - } - if len(event.foot_comment) > 0 { - emitter.foot_comment = event.foot_comment - } - if len(event.tail_comment) > 0 { - emitter.tail_comment = event.tail_comment - } - - switch event.typ { - case yaml_ALIAS_EVENT: - if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { - return false - } - - case yaml_SCALAR_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - if !yaml_emitter_analyze_scalar(emitter, event.value) { - return false - } - - case yaml_SEQUENCE_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - - case yaml_MAPPING_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - } - return true -} - -// Write the BOM character. -func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { - if !flush(emitter) { - return false - } - pos := emitter.buffer_pos - emitter.buffer[pos+0] = '\xEF' - emitter.buffer[pos+1] = '\xBB' - emitter.buffer[pos+2] = '\xBF' - emitter.buffer_pos += 3 - return true -} - -func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { - indent := emitter.indent - if indent < 0 { - indent = 0 - } - if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { - if !put_break(emitter) { - return false - } - } - if emitter.foot_indent == indent { - if !put_break(emitter) { - return false - } - } - for emitter.column < indent { - if !put(emitter, ' ') { - return false - } - } - emitter.whitespace = true - //emitter.indention = true - emitter.space_above = false - emitter.foot_indent = -1 - return true -} - -func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, indicator) { - return false - } - emitter.whitespace = is_whitespace - emitter.indention = (emitter.indention && is_indention) - emitter.open_ended = false - return true -} - -func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - for i := 0; i < len(value); { - var must_write bool - switch value[i] { - case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': - must_write = true - default: - must_write = is_alpha(value, i) - } - if must_write { - if !write(emitter, value, &i) { - return false - } - } else { - w := width(value[i]) - for k := 0; k < w; k++ { - octet := value[i] - i++ - if !put(emitter, '%') { - return false - } - - c := octet >> 4 - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - - c = octet & 0x0f - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - } - } - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if len(value) > 0 && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - - if len(value) > 0 { - emitter.whitespace = false - } - emitter.indention = false - if emitter.root_context { - emitter.open_ended = true - } - - return true -} - -func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { - return false - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if value[i] == '\'' { - if !put(emitter, '\'') { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - spaces := false - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { - return false - } - - for i := 0; i < len(value); { - if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || - is_bom(value, i) || is_break(value, i) || - value[i] == '"' || value[i] == '\\' { - - octet := value[i] - - var w int - var v rune - switch { - case octet&0x80 == 0x00: - w, v = 1, rune(octet&0x7F) - case octet&0xE0 == 0xC0: - w, v = 2, rune(octet&0x1F) - case octet&0xF0 == 0xE0: - w, v = 3, rune(octet&0x0F) - case octet&0xF8 == 0xF0: - w, v = 4, rune(octet&0x07) - } - for k := 1; k < w; k++ { - octet = value[i+k] - v = (v << 6) + (rune(octet) & 0x3F) - } - i += w - - if !put(emitter, '\\') { - return false - } - - var ok bool - switch v { - case 0x00: - ok = put(emitter, '0') - case 0x07: - ok = put(emitter, 'a') - case 0x08: - ok = put(emitter, 'b') - case 0x09: - ok = put(emitter, 't') - case 0x0A: - ok = put(emitter, 'n') - case 0x0b: - ok = put(emitter, 'v') - case 0x0c: - ok = put(emitter, 'f') - case 0x0d: - ok = put(emitter, 'r') - case 0x1b: - ok = put(emitter, 'e') - case 0x22: - ok = put(emitter, '"') - case 0x5c: - ok = put(emitter, '\\') - case 0x85: - ok = put(emitter, 'N') - case 0xA0: - ok = put(emitter, '_') - case 0x2028: - ok = put(emitter, 'L') - case 0x2029: - ok = put(emitter, 'P') - default: - if v <= 0xFF { - ok = put(emitter, 'x') - w = 2 - } else if v <= 0xFFFF { - ok = put(emitter, 'u') - w = 4 - } else { - ok = put(emitter, 'U') - w = 8 - } - for k := (w - 1) * 4; ok && k >= 0; k -= 4 { - digit := byte((v >> uint(k)) & 0x0F) - if digit < 10 { - ok = put(emitter, digit+'0') - } else { - ok = put(emitter, digit+'A'-10) - } - } - } - if !ok { - return false - } - spaces = false - } else if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { - if !yaml_emitter_write_indent(emitter) { - return false - } - if is_space(value, i+1) { - if !put(emitter, '\\') { - return false - } - } - i += width(value[i]) - } else if !write(emitter, value, &i) { - return false - } - spaces = true - } else { - if !write(emitter, value, &i) { - return false - } - spaces = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { - if is_space(value, 0) || is_break(value, 0) { - indent_hint := []byte{'0' + byte(emitter.best_indent)} - if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { - return false - } - } - - emitter.open_ended = false - - var chomp_hint [1]byte - if len(value) == 0 { - chomp_hint[0] = '-' - } else { - i := len(value) - 1 - for value[i]&0xC0 == 0x80 { - i-- - } - if !is_break(value, i) { - chomp_hint[0] = '-' - } else if i == 0 { - chomp_hint[0] = '+' - emitter.open_ended = true - } else { - i-- - for value[i]&0xC0 == 0x80 { - i-- - } - if is_break(value, i) { - chomp_hint[0] = '+' - emitter.open_ended = true - } - } - } - if chomp_hint[0] != 0 { - if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { - return false - } - } - return true -} - -func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - //emitter.indention = true - emitter.whitespace = true - breaks := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - breaks = false - } - } - - return true -} - -func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - if !yaml_emitter_process_line_comment(emitter) { - return false - } - - //emitter.indention = true - emitter.whitespace = true - - breaks := true - leading_spaces := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !breaks && !leading_spaces && value[i] == '\n' { - k := 0 - for is_break(value, k) { - k += width(value[k]) - } - if !is_blankz(value, k) { - if !put_break(emitter) { - return false - } - } - } - if !write_break(emitter, value, &i) { - return false - } - //emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - leading_spaces = is_blank(value, i) - } - if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - emitter.indention = false - breaks = false - } - } - return true -} - -func yaml_emitter_write_comment(emitter *yaml_emitter_t, comment []byte) bool { - breaks := false - pound := false - for i := 0; i < len(comment); { - if is_break(comment, i) { - if !write_break(emitter, comment, &i) { - return false - } - //emitter.indention = true - breaks = true - pound = false - } else { - if breaks && !yaml_emitter_write_indent(emitter) { - return false - } - if !pound { - if comment[i] != '#' && (!put(emitter, '#') || !put(emitter, ' ')) { - return false - } - pound = true - } - if !write(emitter, comment, &i) { - return false - } - emitter.indention = false - breaks = false - } - } - if !breaks && !put_break(emitter) { - return false - } - - emitter.whitespace = true - //emitter.indention = true - return true -} diff --git a/vendor/gopkg.in/yaml.v3/encode.go b/vendor/gopkg.in/yaml.v3/encode.go deleted file mode 100644 index de9e72a..0000000 --- a/vendor/gopkg.in/yaml.v3/encode.go +++ /dev/null @@ -1,577 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// 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 yaml - -import ( - "encoding" - "fmt" - "io" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -type encoder struct { - emitter yaml_emitter_t - event yaml_event_t - out []byte - flow bool - indent int - doneInit bool -} - -func newEncoder() *encoder { - e := &encoder{} - yaml_emitter_initialize(&e.emitter) - yaml_emitter_set_output_string(&e.emitter, &e.out) - yaml_emitter_set_unicode(&e.emitter, true) - return e -} - -func newEncoderWithWriter(w io.Writer) *encoder { - e := &encoder{} - yaml_emitter_initialize(&e.emitter) - yaml_emitter_set_output_writer(&e.emitter, w) - yaml_emitter_set_unicode(&e.emitter, true) - return e -} - -func (e *encoder) init() { - if e.doneInit { - return - } - if e.indent == 0 { - e.indent = 4 - } - e.emitter.best_indent = e.indent - yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) - e.emit() - e.doneInit = true -} - -func (e *encoder) finish() { - e.emitter.open_ended = false - yaml_stream_end_event_initialize(&e.event) - e.emit() -} - -func (e *encoder) destroy() { - yaml_emitter_delete(&e.emitter) -} - -func (e *encoder) emit() { - // This will internally delete the e.event value. - e.must(yaml_emitter_emit(&e.emitter, &e.event)) -} - -func (e *encoder) must(ok bool) { - if !ok { - msg := e.emitter.problem - if msg == "" { - msg = "unknown problem generating YAML content" - } - failf("%s", msg) - } -} - -func (e *encoder) marshalDoc(tag string, in reflect.Value) { - e.init() - var node *Node - if in.IsValid() { - node, _ = in.Interface().(*Node) - } - if node != nil && node.Kind == DocumentNode { - e.nodev(in) - } else { - yaml_document_start_event_initialize(&e.event, nil, nil, true) - e.emit() - e.marshal(tag, in) - yaml_document_end_event_initialize(&e.event, true) - e.emit() - } -} - -func (e *encoder) marshal(tag string, in reflect.Value) { - tag = shortTag(tag) - if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { - e.nilv() - return - } - iface := in.Interface() - switch value := iface.(type) { - case *Node: - e.nodev(in) - return - case Node: - if !in.CanAddr() { - var n = reflect.New(in.Type()).Elem() - n.Set(in) - in = n - } - e.nodev(in.Addr()) - return - case time.Time: - e.timev(tag, in) - return - case *time.Time: - e.timev(tag, in.Elem()) - return - case time.Duration: - e.stringv(tag, reflect.ValueOf(value.String())) - return - case Marshaler: - v, err := value.MarshalYAML() - if err != nil { - fail(err) - } - if v == nil { - e.nilv() - return - } - e.marshal(tag, reflect.ValueOf(v)) - return - case encoding.TextMarshaler: - text, err := value.MarshalText() - if err != nil { - fail(err) - } - in = reflect.ValueOf(string(text)) - case nil: - e.nilv() - return - } - switch in.Kind() { - case reflect.Interface: - e.marshal(tag, in.Elem()) - case reflect.Map: - e.mapv(tag, in) - case reflect.Ptr: - e.marshal(tag, in.Elem()) - case reflect.Struct: - e.structv(tag, in) - case reflect.Slice, reflect.Array: - e.slicev(tag, in) - case reflect.String: - e.stringv(tag, in) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - e.intv(tag, in) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - e.uintv(tag, in) - case reflect.Float32, reflect.Float64: - e.floatv(tag, in) - case reflect.Bool: - e.boolv(tag, in) - default: - panic("cannot marshal type: " + in.Type().String()) - } -} - -func (e *encoder) mapv(tag string, in reflect.Value) { - e.mappingv(tag, func() { - keys := keyList(in.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - e.marshal("", k) - e.marshal("", in.MapIndex(k)) - } - }) -} - -func (e *encoder) fieldByIndex(v reflect.Value, index []int) (field reflect.Value) { - for _, num := range index { - for { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - return reflect.Value{} - } - v = v.Elem() - continue - } - break - } - v = v.Field(num) - } - return v -} - -func (e *encoder) structv(tag string, in reflect.Value) { - sinfo, err := getStructInfo(in.Type()) - if err != nil { - panic(err) - } - e.mappingv(tag, func() { - for _, info := range sinfo.FieldsList { - var value reflect.Value - if info.Inline == nil { - value = in.Field(info.Num) - } else { - value = e.fieldByIndex(in, info.Inline) - if !value.IsValid() { - continue - } - } - if info.OmitEmpty && isZero(value) { - continue - } - e.marshal("", reflect.ValueOf(info.Key)) - e.flow = info.Flow - e.marshal("", value) - } - if sinfo.InlineMap >= 0 { - m := in.Field(sinfo.InlineMap) - if m.Len() > 0 { - e.flow = false - keys := keyList(m.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - if _, found := sinfo.FieldsMap[k.String()]; found { - panic(fmt.Sprintf("cannot have key %q in inlined map: conflicts with struct field", k.String())) - } - e.marshal("", k) - e.flow = false - e.marshal("", m.MapIndex(k)) - } - } - } - }) -} - -func (e *encoder) mappingv(tag string, f func()) { - implicit := tag == "" - style := yaml_BLOCK_MAPPING_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_MAPPING_STYLE - } - yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) - e.emit() - f() - yaml_mapping_end_event_initialize(&e.event) - e.emit() -} - -func (e *encoder) slicev(tag string, in reflect.Value) { - implicit := tag == "" - style := yaml_BLOCK_SEQUENCE_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_SEQUENCE_STYLE - } - e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) - e.emit() - n := in.Len() - for i := 0; i < n; i++ { - e.marshal("", in.Index(i)) - } - e.must(yaml_sequence_end_event_initialize(&e.event)) - e.emit() -} - -// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. -// -// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported -// in YAML 1.2 and by this package, but these should be marshalled quoted for -// the time being for compatibility with other parsers. -func isBase60Float(s string) (result bool) { - // Fast path. - if s == "" { - return false - } - c := s[0] - if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { - return false - } - // Do the full match. - return base60float.MatchString(s) -} - -// From http://yaml.org/type/float.html, except the regular expression there -// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. -var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) - -// isOldBool returns whether s is bool notation as defined in YAML 1.1. -// -// We continue to force strings that YAML 1.1 would interpret as booleans to be -// rendered as quotes strings so that the marshalled output valid for YAML 1.1 -// parsing. -func isOldBool(s string) (result bool) { - switch s { - case "y", "Y", "yes", "Yes", "YES", "on", "On", "ON", - "n", "N", "no", "No", "NO", "off", "Off", "OFF": - return true - default: - return false - } -} - -func (e *encoder) stringv(tag string, in reflect.Value) { - var style yaml_scalar_style_t - s := in.String() - canUsePlain := true - switch { - case !utf8.ValidString(s): - if tag == binaryTag { - failf("explicitly tagged !!binary data must be base64-encoded") - } - if tag != "" { - failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) - } - // It can't be encoded directly as YAML so use a binary tag - // and encode it as base64. - tag = binaryTag - s = encodeBase64(s) - case tag == "": - // Check to see if it would resolve to a specific - // tag when encoded unquoted. If it doesn't, - // there's no need to quote it. - rtag, _ := resolve("", s) - canUsePlain = rtag == strTag && !(isBase60Float(s) || isOldBool(s)) - } - // Note: it's possible for user code to emit invalid YAML - // if they explicitly specify a tag and a string containing - // text that's incompatible with that tag. - switch { - case strings.Contains(s, "\n"): - if e.flow { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } else { - style = yaml_LITERAL_SCALAR_STYLE - } - case canUsePlain: - style = yaml_PLAIN_SCALAR_STYLE - default: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - e.emitScalar(s, "", tag, style, nil, nil, nil, nil) -} - -func (e *encoder) boolv(tag string, in reflect.Value) { - var s string - if in.Bool() { - s = "true" - } else { - s = "false" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) intv(tag string, in reflect.Value) { - s := strconv.FormatInt(in.Int(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) uintv(tag string, in reflect.Value) { - s := strconv.FormatUint(in.Uint(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) timev(tag string, in reflect.Value) { - t := in.Interface().(time.Time) - s := t.Format(time.RFC3339Nano) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) floatv(tag string, in reflect.Value) { - // Issue #352: When formatting, use the precision of the underlying value - precision := 64 - if in.Kind() == reflect.Float32 { - precision = 32 - } - - s := strconv.FormatFloat(in.Float(), 'g', -1, precision) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) nilv() { - e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE, nil, nil, nil, nil) -} - -func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t, head, line, foot, tail []byte) { - // TODO Kill this function. Replace all initialize calls by their underlining Go literals. - implicit := tag == "" - if !implicit { - tag = longTag(tag) - } - e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) - e.event.head_comment = head - e.event.line_comment = line - e.event.foot_comment = foot - e.event.tail_comment = tail - e.emit() -} - -func (e *encoder) nodev(in reflect.Value) { - e.node(in.Interface().(*Node), "") -} - -func (e *encoder) node(node *Node, tail string) { - // Zero nodes behave as nil. - if node.Kind == 0 && node.IsZero() { - e.nilv() - return - } - - // If the tag was not explicitly requested, and dropping it won't change the - // implicit tag of the value, don't include it in the presentation. - var tag = node.Tag - var stag = shortTag(tag) - var forceQuoting bool - if tag != "" && node.Style&TaggedStyle == 0 { - if node.Kind == ScalarNode { - if stag == strTag && node.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0 { - tag = "" - } else { - rtag, _ := resolve("", node.Value) - if rtag == stag { - tag = "" - } else if stag == strTag { - tag = "" - forceQuoting = true - } - } - } else { - var rtag string - switch node.Kind { - case MappingNode: - rtag = mapTag - case SequenceNode: - rtag = seqTag - } - if rtag == stag { - tag = "" - } - } - } - - switch node.Kind { - case DocumentNode: - yaml_document_start_event_initialize(&e.event, nil, nil, true) - e.event.head_comment = []byte(node.HeadComment) - e.emit() - for _, node := range node.Content { - e.node(node, "") - } - yaml_document_end_event_initialize(&e.event, true) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case SequenceNode: - style := yaml_BLOCK_SEQUENCE_STYLE - if node.Style&FlowStyle != 0 { - style = yaml_FLOW_SEQUENCE_STYLE - } - e.must(yaml_sequence_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style)) - e.event.head_comment = []byte(node.HeadComment) - e.emit() - for _, node := range node.Content { - e.node(node, "") - } - e.must(yaml_sequence_end_event_initialize(&e.event)) - e.event.line_comment = []byte(node.LineComment) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case MappingNode: - style := yaml_BLOCK_MAPPING_STYLE - if node.Style&FlowStyle != 0 { - style = yaml_FLOW_MAPPING_STYLE - } - yaml_mapping_start_event_initialize(&e.event, []byte(node.Anchor), []byte(longTag(tag)), tag == "", style) - e.event.tail_comment = []byte(tail) - e.event.head_comment = []byte(node.HeadComment) - e.emit() - - // The tail logic below moves the foot comment of prior keys to the following key, - // since the value for each key may be a nested structure and the foot needs to be - // processed only the entirety of the value is streamed. The last tail is processed - // with the mapping end event. - var tail string - for i := 0; i+1 < len(node.Content); i += 2 { - k := node.Content[i] - foot := k.FootComment - if foot != "" { - kopy := *k - kopy.FootComment = "" - k = &kopy - } - e.node(k, tail) - tail = foot - - v := node.Content[i+1] - e.node(v, "") - } - - yaml_mapping_end_event_initialize(&e.event) - e.event.tail_comment = []byte(tail) - e.event.line_comment = []byte(node.LineComment) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case AliasNode: - yaml_alias_event_initialize(&e.event, []byte(node.Value)) - e.event.head_comment = []byte(node.HeadComment) - e.event.line_comment = []byte(node.LineComment) - e.event.foot_comment = []byte(node.FootComment) - e.emit() - - case ScalarNode: - value := node.Value - if !utf8.ValidString(value) { - if stag == binaryTag { - failf("explicitly tagged !!binary data must be base64-encoded") - } - if stag != "" { - failf("cannot marshal invalid UTF-8 data as %s", stag) - } - // It can't be encoded directly as YAML so use a binary tag - // and encode it as base64. - tag = binaryTag - value = encodeBase64(value) - } - - style := yaml_PLAIN_SCALAR_STYLE - switch { - case node.Style&DoubleQuotedStyle != 0: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - case node.Style&SingleQuotedStyle != 0: - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - case node.Style&LiteralStyle != 0: - style = yaml_LITERAL_SCALAR_STYLE - case node.Style&FoldedStyle != 0: - style = yaml_FOLDED_SCALAR_STYLE - case strings.Contains(value, "\n"): - style = yaml_LITERAL_SCALAR_STYLE - case forceQuoting: - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - - e.emitScalar(value, node.Anchor, tag, style, []byte(node.HeadComment), []byte(node.LineComment), []byte(node.FootComment), []byte(tail)) - default: - failf("cannot encode node with unknown kind %d", node.Kind) - } -} diff --git a/vendor/gopkg.in/yaml.v3/parserc.go b/vendor/gopkg.in/yaml.v3/parserc.go deleted file mode 100644 index 268558a..0000000 --- a/vendor/gopkg.in/yaml.v3/parserc.go +++ /dev/null @@ -1,1258 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -import ( - "bytes" -) - -// The parser implements the following grammar: -// -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// implicit_document ::= block_node DOCUMENT-END* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// block_node_or_indentless_sequence ::= -// ALIAS -// | properties (block_content | indentless_block_sequence)? -// | block_content -// | indentless_block_sequence -// block_node ::= ALIAS -// | properties block_content? -// | block_content -// flow_node ::= ALIAS -// | properties flow_content? -// | flow_content -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// block_content ::= block_collection | flow_collection | SCALAR -// flow_content ::= flow_collection | SCALAR -// block_collection ::= block_sequence | block_mapping -// flow_collection ::= flow_sequence | flow_mapping -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// block_mapping ::= BLOCK-MAPPING_START -// ((KEY block_node_or_indentless_sequence?)? -// (VALUE block_node_or_indentless_sequence?)?)* -// BLOCK-END -// flow_sequence ::= FLOW-SEQUENCE-START -// (flow_sequence_entry FLOW-ENTRY)* -// flow_sequence_entry? -// FLOW-SEQUENCE-END -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// flow_mapping ::= FLOW-MAPPING-START -// (flow_mapping_entry FLOW-ENTRY)* -// flow_mapping_entry? -// FLOW-MAPPING-END -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - -// Peek the next token in the token queue. -func peek_token(parser *yaml_parser_t) *yaml_token_t { - if parser.token_available || yaml_parser_fetch_more_tokens(parser) { - token := &parser.tokens[parser.tokens_head] - yaml_parser_unfold_comments(parser, token) - return token - } - return nil -} - -// yaml_parser_unfold_comments walks through the comments queue and joins all -// comments behind the position of the provided token into the respective -// top-level comment slices in the parser. -func yaml_parser_unfold_comments(parser *yaml_parser_t, token *yaml_token_t) { - for parser.comments_head < len(parser.comments) && token.start_mark.index >= parser.comments[parser.comments_head].token_mark.index { - comment := &parser.comments[parser.comments_head] - if len(comment.head) > 0 { - if token.typ == yaml_BLOCK_END_TOKEN { - // No heads on ends, so keep comment.head for a follow up token. - break - } - if len(parser.head_comment) > 0 { - parser.head_comment = append(parser.head_comment, '\n') - } - parser.head_comment = append(parser.head_comment, comment.head...) - } - if len(comment.foot) > 0 { - if len(parser.foot_comment) > 0 { - parser.foot_comment = append(parser.foot_comment, '\n') - } - parser.foot_comment = append(parser.foot_comment, comment.foot...) - } - if len(comment.line) > 0 { - if len(parser.line_comment) > 0 { - parser.line_comment = append(parser.line_comment, '\n') - } - parser.line_comment = append(parser.line_comment, comment.line...) - } - *comment = yaml_comment_t{} - parser.comments_head++ - } -} - -// Remove the next token from the queue (must be called after peek_token). -func skip_token(parser *yaml_parser_t) { - parser.token_available = false - parser.tokens_parsed++ - parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN - parser.tokens_head++ -} - -// Get the next event. -func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { - // Erase the event object. - *event = yaml_event_t{} - - // No events after the end of the stream or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { - return true - } - - // Generate the next event. - return yaml_parser_state_machine(parser, event) -} - -// Set parser error. -func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -// State dispatcher. -func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) - - switch parser.state { - case yaml_PARSE_STREAM_START_STATE: - return yaml_parser_parse_stream_start(parser, event) - - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, true) - - case yaml_PARSE_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, false) - - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return yaml_parser_parse_document_content(parser, event) - - case yaml_PARSE_DOCUMENT_END_STATE: - return yaml_parser_parse_document_end(parser, event) - - case yaml_PARSE_BLOCK_NODE_STATE: - return yaml_parser_parse_node(parser, event, true, false) - - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return yaml_parser_parse_node(parser, event, true, true) - - case yaml_PARSE_FLOW_NODE_STATE: - return yaml_parser_parse_node(parser, event, false, false) - - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, true) - - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, false) - - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_indentless_sequence_entry(parser, event) - - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, true) - - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, false) - - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return yaml_parser_parse_block_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, true) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, false) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) - - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, true) - - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, true) - - default: - panic("invalid parser state") - } -} - -// Parse the production: -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// ************ -func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_STREAM_START_TOKEN { - return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) - } - parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - encoding: token.encoding, - } - skip_token(parser) - return true -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// * -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// ************************* -func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - - token := peek_token(parser) - if token == nil { - return false - } - - // Parse extra document end indicators. - if !implicit { - for token.typ == yaml_DOCUMENT_END_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && - token.typ != yaml_TAG_DIRECTIVE_TOKEN && - token.typ != yaml_DOCUMENT_START_TOKEN && - token.typ != yaml_STREAM_END_TOKEN { - // Parse an implicit document. - if !yaml_parser_process_directives(parser, nil, nil) { - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_BLOCK_NODE_STATE - - var head_comment []byte - if len(parser.head_comment) > 0 { - // [Go] Scan the header comment backwards, and if an empty line is found, break - // the header so the part before the last empty line goes into the - // document header, while the bottom of it goes into a follow up event. - for i := len(parser.head_comment) - 1; i > 0; i-- { - if parser.head_comment[i] == '\n' { - if i == len(parser.head_comment)-1 { - head_comment = parser.head_comment[:i] - parser.head_comment = parser.head_comment[i+1:] - break - } else if parser.head_comment[i-1] == '\n' { - head_comment = parser.head_comment[:i-1] - parser.head_comment = parser.head_comment[i+1:] - break - } - } - } - } - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - - head_comment: head_comment, - } - - } else if token.typ != yaml_STREAM_END_TOKEN { - // Parse an explicit document. - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - start_mark := token.start_mark - if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { - return false - } - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_DOCUMENT_START_TOKEN { - yaml_parser_set_parser_error(parser, - "did not find expected ", token.start_mark) - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE - end_mark := token.end_mark - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: false, - } - skip_token(parser) - - } else { - // Parse the stream end. - parser.state = yaml_PARSE_END_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - } - - return true -} - -// Parse the productions: -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// *********** -// -func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || - token.typ == yaml_TAG_DIRECTIVE_TOKEN || - token.typ == yaml_DOCUMENT_START_TOKEN || - token.typ == yaml_DOCUMENT_END_TOKEN || - token.typ == yaml_STREAM_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - return yaml_parser_process_empty_scalar(parser, event, - token.start_mark) - } - return yaml_parser_parse_node(parser, event, true, false) -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// ************* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - start_mark := token.start_mark - end_mark := token.start_mark - - implicit := true - if token.typ == yaml_DOCUMENT_END_TOKEN { - end_mark = token.end_mark - skip_token(parser) - implicit = false - } - - parser.tag_directives = parser.tag_directives[:0] - - parser.state = yaml_PARSE_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - start_mark: start_mark, - end_mark: end_mark, - implicit: implicit, - } - yaml_parser_set_event_comments(parser, event) - if len(event.head_comment) > 0 && len(event.foot_comment) == 0 { - event.foot_comment = event.head_comment - event.head_comment = nil - } - return true -} - -func yaml_parser_set_event_comments(parser *yaml_parser_t, event *yaml_event_t) { - event.head_comment = parser.head_comment - event.line_comment = parser.line_comment - event.foot_comment = parser.foot_comment - parser.head_comment = nil - parser.line_comment = nil - parser.foot_comment = nil - parser.tail_comment = nil - parser.stem_comment = nil -} - -// Parse the productions: -// block_node_or_indentless_sequence ::= -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// block_node ::= ALIAS -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// flow_node ::= ALIAS -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// ************************* -// block_content ::= block_collection | flow_collection | SCALAR -// ****** -// flow_content ::= flow_collection | SCALAR -// ****** -func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_ALIAS_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - anchor: token.value, - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true - } - - start_mark := token.start_mark - end_mark := token.start_mark - - var tag_token bool - var tag_handle, tag_suffix, anchor []byte - var tag_mark yaml_mark_t - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - start_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } else if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - start_mark = token.start_mark - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - var tag []byte - if tag_token { - if len(tag_handle) == 0 { - tag = tag_suffix - tag_suffix = nil - } else { - for i := range parser.tag_directives { - if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { - tag = append([]byte(nil), parser.tag_directives[i].prefix...) - tag = append(tag, tag_suffix...) - break - } - } - if len(tag) == 0 { - yaml_parser_set_parser_error_context(parser, - "while parsing a node", start_mark, - "found undefined tag handle", tag_mark) - return false - } - } - } - - implicit := len(tag) == 0 - if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_SCALAR_TOKEN { - var plain_implicit, quoted_implicit bool - end_mark = token.end_mark - if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { - plain_implicit = true - } else if len(tag) == 0 { - quoted_implicit = true - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - value: token.value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(token.style), - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true - } - if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { - // [Go] Some of the events below can be merged as they differ only on style. - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), - } - yaml_parser_set_event_comments(parser, event) - return true - } - if token.typ == yaml_FLOW_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - yaml_parser_set_event_comments(parser, event) - return true - } - if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - if parser.stem_comment != nil { - event.head_comment = parser.stem_comment - parser.stem_comment = nil - } - return true - } - if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), - } - if parser.stem_comment != nil { - event.head_comment = parser.stem_comment - parser.stem_comment = nil - } - return true - } - if len(anchor) > 0 || len(tag) > 0 { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - quoted_implicit: false, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true - } - - context := "while parsing a flow node" - if block { - context = "while parsing a block node" - } - yaml_parser_set_parser_error_context(parser, context, start_mark, - "did not find expected node content", token.start_mark) - return false -} - -// Parse the productions: -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// ******************** *********** * ********* -// -func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - if token == nil { - return false - } - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - prior_head_len := len(parser.head_comment) - skip_token(parser) - yaml_parser_split_stem_comment(parser, prior_head_len) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } else { - parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } - if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block collection", context_mark, - "did not find expected '-' indicator", token.start_mark) -} - -// Parse the productions: -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// *********** * -func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - prior_head_len := len(parser.head_comment) - skip_token(parser) - yaml_parser_split_stem_comment(parser, prior_head_len) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && - token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? - } - return true -} - -// Split stem comment from head comment. -// -// When a sequence or map is found under a sequence entry, the former head comment -// is assigned to the underlying sequence or map as a whole, not the individual -// sequence or map entry as would be expected otherwise. To handle this case the -// previous head comment is moved aside as the stem comment. -func yaml_parser_split_stem_comment(parser *yaml_parser_t, stem_len int) { - if stem_len == 0 { - return - } - - token := peek_token(parser) - if token == nil || token.typ != yaml_BLOCK_SEQUENCE_START_TOKEN && token.typ != yaml_BLOCK_MAPPING_START_TOKEN { - return - } - - parser.stem_comment = parser.head_comment[:stem_len] - if len(parser.head_comment) == stem_len { - parser.head_comment = nil - } else { - // Copy suffix to prevent very strange bugs if someone ever appends - // further bytes to the prefix in the stem_comment slice above. - parser.head_comment = append([]byte(nil), parser.head_comment[stem_len+1:]...) - } -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* -// -// BLOCK-END -// ********* -// -func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - if token == nil { - return false - } - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - // [Go] A tail comment was left from the prior mapping value processed. Emit an event - // as it needs to be processed with that value and not the following key. - if len(parser.tail_comment) > 0 { - *event = yaml_event_t{ - typ: yaml_TAIL_COMMENT_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - foot_comment: parser.tail_comment, - } - parser.tail_comment = nil - return true - } - - if token.typ == yaml_KEY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } else { - parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } else if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block mapping", context_mark, - "did not find expected key", token.start_mark) -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// -// ((KEY block_node_or_indentless_sequence?)? -// -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END -// -// -func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence ::= FLOW-SEQUENCE-START -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - if token == nil { - return false - } - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow sequence", context_mark, - "did not find expected ',' or ']'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - implicit: true, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - skip_token(parser) - return true - } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - yaml_parser_set_event_comments(parser, event) - - skip_token(parser) - return true -} - -// -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// *** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - mark := token.end_mark - skip_token(parser) - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// ***** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? - } - return true -} - -// Parse the productions: -// flow_mapping ::= FLOW-MAPPING-START -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * *** * -// -func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow mapping", context_mark, - "did not find expected ',' or '}'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } else { - parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - yaml_parser_set_event_comments(parser, event) - skip_token(parser) - return true -} - -// Parse the productions: -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * ***** * -// -func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { - token := peek_token(parser) - if token == nil { - return false - } - if empty { - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Generate an empty scalar event. -func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: mark, - end_mark: mark, - value: nil, // Empty - implicit: true, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true -} - -var default_tag_directives = []yaml_tag_directive_t{ - {[]byte("!"), []byte("!")}, - {[]byte("!!"), []byte("tag:yaml.org,2002:")}, -} - -// Parse directives. -func yaml_parser_process_directives(parser *yaml_parser_t, - version_directive_ref **yaml_version_directive_t, - tag_directives_ref *[]yaml_tag_directive_t) bool { - - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - - token := peek_token(parser) - if token == nil { - return false - } - - for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { - if version_directive != nil { - yaml_parser_set_parser_error(parser, - "found duplicate %YAML directive", token.start_mark) - return false - } - if token.major != 1 || token.minor != 1 { - yaml_parser_set_parser_error(parser, - "found incompatible YAML document", token.start_mark) - return false - } - version_directive = &yaml_version_directive_t{ - major: token.major, - minor: token.minor, - } - } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { - value := yaml_tag_directive_t{ - handle: token.value, - prefix: token.prefix, - } - if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { - return false - } - tag_directives = append(tag_directives, value) - } - - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - - for i := range default_tag_directives { - if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { - return false - } - } - - if version_directive_ref != nil { - *version_directive_ref = version_directive - } - if tag_directives_ref != nil { - *tag_directives_ref = tag_directives - } - return true -} - -// Append a tag directive to the directives stack. -func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { - for i := range parser.tag_directives { - if bytes.Equal(value.handle, parser.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) - } - } - - // [Go] I suspect the copy is unnecessary. This was likely done - // because there was no way to track ownership of the data. - value_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(value_copy.handle, value.handle) - copy(value_copy.prefix, value.prefix) - parser.tag_directives = append(parser.tag_directives, value_copy) - return true -} diff --git a/vendor/gopkg.in/yaml.v3/readerc.go b/vendor/gopkg.in/yaml.v3/readerc.go deleted file mode 100644 index b7de0a8..0000000 --- a/vendor/gopkg.in/yaml.v3/readerc.go +++ /dev/null @@ -1,434 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -import ( - "io" -) - -// Set the reader error and return 0. -func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { - parser.error = yaml_READER_ERROR - parser.problem = problem - parser.problem_offset = offset - parser.problem_value = value - return false -} - -// Byte order marks. -const ( - bom_UTF8 = "\xef\xbb\xbf" - bom_UTF16LE = "\xff\xfe" - bom_UTF16BE = "\xfe\xff" -) - -// Determine the input stream encoding by checking the BOM symbol. If no BOM is -// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. -func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { - // Ensure that we had enough bytes in the raw buffer. - for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { - if !yaml_parser_update_raw_buffer(parser) { - return false - } - } - - // Determine the encoding. - buf := parser.raw_buffer - pos := parser.raw_buffer_pos - avail := len(buf) - pos - if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { - parser.encoding = yaml_UTF16LE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { - parser.encoding = yaml_UTF16BE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { - parser.encoding = yaml_UTF8_ENCODING - parser.raw_buffer_pos += 3 - parser.offset += 3 - } else { - parser.encoding = yaml_UTF8_ENCODING - } - return true -} - -// Update the raw buffer. -func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { - size_read := 0 - - // Return if the raw buffer is full. - if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { - return true - } - - // Return on EOF. - if parser.eof { - return true - } - - // Move the remaining bytes in the raw buffer to the beginning. - if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { - copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) - } - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] - parser.raw_buffer_pos = 0 - - // Call the read handler to fill the buffer. - size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] - if err == io.EOF { - parser.eof = true - } else if err != nil { - return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) - } - return true -} - -// Ensure that the buffer contains at least `length` characters. -// Return true on success, false on failure. -// -// The length is supposed to be significantly less that the buffer size. -func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { - if parser.read_handler == nil { - panic("read handler must be set") - } - - // [Go] This function was changed to guarantee the requested length size at EOF. - // The fact we need to do this is pretty awful, but the description above implies - // for that to be the case, and there are tests - - // If the EOF flag is set and the raw buffer is empty, do nothing. - if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { - // [Go] ACTUALLY! Read the documentation of this function above. - // This is just broken. To return true, we need to have the - // given length in the buffer. Not doing that means every single - // check that calls this function to make sure the buffer has a - // given length is Go) panicking; or C) accessing invalid memory. - //return true - } - - // Return if the buffer contains enough characters. - if parser.unread >= length { - return true - } - - // Determine the input encoding if it is not known yet. - if parser.encoding == yaml_ANY_ENCODING { - if !yaml_parser_determine_encoding(parser) { - return false - } - } - - // Move the unread characters to the beginning of the buffer. - buffer_len := len(parser.buffer) - if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { - copy(parser.buffer, parser.buffer[parser.buffer_pos:]) - buffer_len -= parser.buffer_pos - parser.buffer_pos = 0 - } else if parser.buffer_pos == buffer_len { - buffer_len = 0 - parser.buffer_pos = 0 - } - - // Open the whole buffer for writing, and cut it before returning. - parser.buffer = parser.buffer[:cap(parser.buffer)] - - // Fill the buffer until it has enough characters. - first := true - for parser.unread < length { - - // Fill the raw buffer if necessary. - if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { - if !yaml_parser_update_raw_buffer(parser) { - parser.buffer = parser.buffer[:buffer_len] - return false - } - } - first = false - - // Decode the raw buffer. - inner: - for parser.raw_buffer_pos != len(parser.raw_buffer) { - var value rune - var width int - - raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos - - // Decode the next character. - switch parser.encoding { - case yaml_UTF8_ENCODING: - // Decode a UTF-8 character. Check RFC 3629 - // (http://www.ietf.org/rfc/rfc3629.txt) for more details. - // - // The following table (taken from the RFC) is used for - // decoding. - // - // Char. number range | UTF-8 octet sequence - // (hexadecimal) | (binary) - // --------------------+------------------------------------ - // 0000 0000-0000 007F | 0xxxxxxx - // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx - // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx - // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // - // Additionally, the characters in the range 0xD800-0xDFFF - // are prohibited as they are reserved for use with UTF-16 - // surrogate pairs. - - // Determine the length of the UTF-8 sequence. - octet := parser.raw_buffer[parser.raw_buffer_pos] - switch { - case octet&0x80 == 0x00: - width = 1 - case octet&0xE0 == 0xC0: - width = 2 - case octet&0xF0 == 0xE0: - width = 3 - case octet&0xF8 == 0xF0: - width = 4 - default: - // The leading octet is invalid. - return yaml_parser_set_reader_error(parser, - "invalid leading UTF-8 octet", - parser.offset, int(octet)) - } - - // Check if the raw buffer contains an incomplete character. - if width > raw_unread { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-8 octet sequence", - parser.offset, -1) - } - break inner - } - - // Decode the leading octet. - switch { - case octet&0x80 == 0x00: - value = rune(octet & 0x7F) - case octet&0xE0 == 0xC0: - value = rune(octet & 0x1F) - case octet&0xF0 == 0xE0: - value = rune(octet & 0x0F) - case octet&0xF8 == 0xF0: - value = rune(octet & 0x07) - default: - value = 0 - } - - // Check and decode the trailing octets. - for k := 1; k < width; k++ { - octet = parser.raw_buffer[parser.raw_buffer_pos+k] - - // Check if the octet is valid. - if (octet & 0xC0) != 0x80 { - return yaml_parser_set_reader_error(parser, - "invalid trailing UTF-8 octet", - parser.offset+k, int(octet)) - } - - // Decode the octet. - value = (value << 6) + rune(octet&0x3F) - } - - // Check the length of the sequence against the value. - switch { - case width == 1: - case width == 2 && value >= 0x80: - case width == 3 && value >= 0x800: - case width == 4 && value >= 0x10000: - default: - return yaml_parser_set_reader_error(parser, - "invalid length of a UTF-8 sequence", - parser.offset, -1) - } - - // Check the range of the value. - if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { - return yaml_parser_set_reader_error(parser, - "invalid Unicode character", - parser.offset, int(value)) - } - - case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: - var low, high int - if parser.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - low, high = 1, 0 - } - - // The UTF-16 encoding is not as simple as one might - // naively think. Check RFC 2781 - // (http://www.ietf.org/rfc/rfc2781.txt). - // - // Normally, two subsequent bytes describe a Unicode - // character. However a special technique (called a - // surrogate pair) is used for specifying character - // values larger than 0xFFFF. - // - // A surrogate pair consists of two pseudo-characters: - // high surrogate area (0xD800-0xDBFF) - // low surrogate area (0xDC00-0xDFFF) - // - // The following formulas are used for decoding - // and encoding characters using surrogate pairs: - // - // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) - // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) - // W1 = 110110yyyyyyyyyy - // W2 = 110111xxxxxxxxxx - // - // where U is the character value, W1 is the high surrogate - // area, W2 is the low surrogate area. - - // Check for incomplete UTF-16 character. - if raw_unread < 2 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 character", - parser.offset, -1) - } - break inner - } - - // Get the character. - value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) - - // Check for unexpected low surrogate area. - if value&0xFC00 == 0xDC00 { - return yaml_parser_set_reader_error(parser, - "unexpected low surrogate area", - parser.offset, int(value)) - } - - // Check for a high surrogate area. - if value&0xFC00 == 0xD800 { - width = 4 - - // Check for incomplete surrogate pair. - if raw_unread < 4 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 surrogate pair", - parser.offset, -1) - } - break inner - } - - // Get the next character. - value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) - - // Check for a low surrogate area. - if value2&0xFC00 != 0xDC00 { - return yaml_parser_set_reader_error(parser, - "expected low surrogate area", - parser.offset+2, int(value2)) - } - - // Generate the value of the surrogate pair. - value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) - } else { - width = 2 - } - - default: - panic("impossible") - } - - // Check if the character is in the allowed range: - // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) - // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) - // | [#x10000-#x10FFFF] (32 bit) - switch { - case value == 0x09: - case value == 0x0A: - case value == 0x0D: - case value >= 0x20 && value <= 0x7E: - case value == 0x85: - case value >= 0xA0 && value <= 0xD7FF: - case value >= 0xE000 && value <= 0xFFFD: - case value >= 0x10000 && value <= 0x10FFFF: - default: - return yaml_parser_set_reader_error(parser, - "control characters are not allowed", - parser.offset, int(value)) - } - - // Move the raw pointers. - parser.raw_buffer_pos += width - parser.offset += width - - // Finally put the character into the buffer. - if value <= 0x7F { - // 0000 0000-0000 007F . 0xxxxxxx - parser.buffer[buffer_len+0] = byte(value) - buffer_len += 1 - } else if value <= 0x7FF { - // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) - parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) - buffer_len += 2 - } else if value <= 0xFFFF { - // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) - buffer_len += 3 - } else { - // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) - buffer_len += 4 - } - - parser.unread++ - } - - // On EOF, put NUL into the buffer and return. - if parser.eof { - parser.buffer[buffer_len] = 0 - buffer_len++ - parser.unread++ - break - } - } - // [Go] Read the documentation of this function above. To return true, - // we need to have the given length in the buffer. Not doing that means - // every single check that calls this function to make sure the buffer - // has a given length is Go) panicking; or C) accessing invalid memory. - // This happens here due to the EOF above breaking early. - for buffer_len < length { - parser.buffer[buffer_len] = 0 - buffer_len++ - } - parser.buffer = parser.buffer[:buffer_len] - return true -} diff --git a/vendor/gopkg.in/yaml.v3/resolve.go b/vendor/gopkg.in/yaml.v3/resolve.go deleted file mode 100644 index 64ae888..0000000 --- a/vendor/gopkg.in/yaml.v3/resolve.go +++ /dev/null @@ -1,326 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// 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 yaml - -import ( - "encoding/base64" - "math" - "regexp" - "strconv" - "strings" - "time" -) - -type resolveMapItem struct { - value interface{} - tag string -} - -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) - -func init() { - t := resolveTable - t[int('+')] = 'S' // Sign - t[int('-')] = 'S' - for _, c := range "0123456789" { - t[int(c)] = 'D' // Digit - } - for _, c := range "yYnNtTfFoO~" { - t[int(c)] = 'M' // In map - } - t[int('.')] = '.' // Float (potentially in map) - - var resolveMapList = []struct { - v interface{} - tag string - l []string - }{ - {true, boolTag, []string{"true", "True", "TRUE"}}, - {false, boolTag, []string{"false", "False", "FALSE"}}, - {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}}, - {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}}, - {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}}, - {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}}, - {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}}, - {"<<", mergeTag, []string{"<<"}}, - } - - m := resolveMap - for _, item := range resolveMapList { - for _, s := range item.l { - m[s] = resolveMapItem{item.v, item.tag} - } - } -} - -const ( - nullTag = "!!null" - boolTag = "!!bool" - strTag = "!!str" - intTag = "!!int" - floatTag = "!!float" - timestampTag = "!!timestamp" - seqTag = "!!seq" - mapTag = "!!map" - binaryTag = "!!binary" - mergeTag = "!!merge" -) - -var longTags = make(map[string]string) -var shortTags = make(map[string]string) - -func init() { - for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} { - ltag := longTag(stag) - longTags[stag] = ltag - shortTags[ltag] = stag - } -} - -const longTagPrefix = "tag:yaml.org,2002:" - -func shortTag(tag string) string { - if strings.HasPrefix(tag, longTagPrefix) { - if stag, ok := shortTags[tag]; ok { - return stag - } - return "!!" + tag[len(longTagPrefix):] - } - return tag -} - -func longTag(tag string) string { - if strings.HasPrefix(tag, "!!") { - if ltag, ok := longTags[tag]; ok { - return ltag - } - return longTagPrefix + tag[2:] - } - return tag -} - -func resolvableTag(tag string) bool { - switch tag { - case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag: - return true - } - return false -} - -var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`) - -func resolve(tag string, in string) (rtag string, out interface{}) { - tag = shortTag(tag) - if !resolvableTag(tag) { - return tag, in - } - - defer func() { - switch tag { - case "", rtag, strTag, binaryTag: - return - case floatTag: - if rtag == intTag { - switch v := out.(type) { - case int64: - rtag = floatTag - out = float64(v) - return - case int: - rtag = floatTag - out = float64(v) - return - } - } - } - failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) - }() - - // Any data is accepted as a !!str or !!binary. - // Otherwise, the prefix is enough of a hint about what it might be. - hint := byte('N') - if in != "" { - hint = resolveTable[in[0]] - } - if hint != 0 && tag != strTag && tag != binaryTag { - // Handle things we can lookup in a map. - if item, ok := resolveMap[in]; ok { - return item.tag, item.value - } - - // Base 60 floats are a bad idea, were dropped in YAML 1.2, and - // are purposefully unsupported here. They're still quoted on - // the way out for compatibility with other parser, though. - - switch hint { - case 'M': - // We've already checked the map above. - - case '.': - // Not in the map, so maybe a normal float. - floatv, err := strconv.ParseFloat(in, 64) - if err == nil { - return floatTag, floatv - } - - case 'D', 'S': - // Int, float, or timestamp. - // Only try values as a timestamp if the value is unquoted or there's an explicit - // !!timestamp tag. - if tag == "" || tag == timestampTag { - t, ok := parseTimestamp(in) - if ok { - return timestampTag, t - } - } - - plain := strings.Replace(in, "_", "", -1) - intv, err := strconv.ParseInt(plain, 0, 64) - if err == nil { - if intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - uintv, err := strconv.ParseUint(plain, 0, 64) - if err == nil { - return intTag, uintv - } - if yamlStyleFloat.MatchString(plain) { - floatv, err := strconv.ParseFloat(plain, 64) - if err == nil { - return floatTag, floatv - } - } - if strings.HasPrefix(plain, "0b") { - intv, err := strconv.ParseInt(plain[2:], 2, 64) - if err == nil { - if intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 2, 64) - if err == nil { - return intTag, uintv - } - } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt("-"+plain[3:], 2, 64) - if err == nil { - if true || intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - } - // Octals as introduced in version 1.2 of the spec. - // Octals from the 1.1 spec, spelled as 0777, are still - // decoded by default in v3 as well for compatibility. - // May be dropped in v4 depending on how usage evolves. - if strings.HasPrefix(plain, "0o") { - intv, err := strconv.ParseInt(plain[2:], 8, 64) - if err == nil { - if intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 8, 64) - if err == nil { - return intTag, uintv - } - } else if strings.HasPrefix(plain, "-0o") { - intv, err := strconv.ParseInt("-"+plain[3:], 8, 64) - if err == nil { - if true || intv == int64(int(intv)) { - return intTag, int(intv) - } else { - return intTag, intv - } - } - } - default: - panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")") - } - } - return strTag, in -} - -// encodeBase64 encodes s as base64 that is broken up into multiple lines -// as appropriate for the resulting length. -func encodeBase64(s string) string { - const lineLen = 70 - encLen := base64.StdEncoding.EncodedLen(len(s)) - lines := encLen/lineLen + 1 - buf := make([]byte, encLen*2+lines) - in := buf[0:encLen] - out := buf[encLen:] - base64.StdEncoding.Encode(in, []byte(s)) - k := 0 - for i := 0; i < len(in); i += lineLen { - j := i + lineLen - if j > len(in) { - j = len(in) - } - k += copy(out[k:], in[i:j]) - if lines > 1 { - out[k] = '\n' - k++ - } - } - return string(out[:k]) -} - -// This is a subset of the formats allowed by the regular expression -// defined at http://yaml.org/type/timestamp.html. -var allowedTimestampFormats = []string{ - "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. - "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". - "2006-1-2 15:4:5.999999999", // space separated with no time zone - "2006-1-2", // date only - // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" - // from the set of examples. -} - -// parseTimestamp parses s as a timestamp string and -// returns the timestamp and reports whether it succeeded. -// Timestamp formats are defined at http://yaml.org/type/timestamp.html -func parseTimestamp(s string) (time.Time, bool) { - // TODO write code to check all the formats supported by - // http://yaml.org/type/timestamp.html instead of using time.Parse. - - // Quick check: all date formats start with YYYY-. - i := 0 - for ; i < len(s); i++ { - if c := s[i]; c < '0' || c > '9' { - break - } - } - if i != 4 || i == len(s) || s[i] != '-' { - return time.Time{}, false - } - for _, format := range allowedTimestampFormats { - if t, err := time.Parse(format, s); err == nil { - return t, true - } - } - return time.Time{}, false -} diff --git a/vendor/gopkg.in/yaml.v3/scannerc.go b/vendor/gopkg.in/yaml.v3/scannerc.go deleted file mode 100644 index ca00701..0000000 --- a/vendor/gopkg.in/yaml.v3/scannerc.go +++ /dev/null @@ -1,3038 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -import ( - "bytes" - "fmt" -) - -// Introduction -// ************ -// -// The following notes assume that you are familiar with the YAML specification -// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in -// some cases we are less restrictive that it requires. -// -// The process of transforming a YAML stream into a sequence of events is -// divided on two steps: Scanning and Parsing. -// -// The Scanner transforms the input stream into a sequence of tokens, while the -// parser transform the sequence of tokens produced by the Scanner into a -// sequence of parsing events. -// -// The Scanner is rather clever and complicated. The Parser, on the contrary, -// is a straightforward implementation of a recursive-descendant parser (or, -// LL(1) parser, as it is usually called). -// -// Actually there are two issues of Scanning that might be called "clever", the -// rest is quite straightforward. The issues are "block collection start" and -// "simple keys". Both issues are explained below in details. -// -// Here the Scanning step is explained and implemented. We start with the list -// of all the tokens produced by the Scanner together with short descriptions. -// -// Now, tokens: -// -// STREAM-START(encoding) # The stream start. -// STREAM-END # The stream end. -// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. -// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. -// DOCUMENT-START # '---' -// DOCUMENT-END # '...' -// BLOCK-SEQUENCE-START # Indentation increase denoting a block -// BLOCK-MAPPING-START # sequence or a block mapping. -// BLOCK-END # Indentation decrease. -// FLOW-SEQUENCE-START # '[' -// FLOW-SEQUENCE-END # ']' -// BLOCK-SEQUENCE-START # '{' -// BLOCK-SEQUENCE-END # '}' -// BLOCK-ENTRY # '-' -// FLOW-ENTRY # ',' -// KEY # '?' or nothing (simple keys). -// VALUE # ':' -// ALIAS(anchor) # '*anchor' -// ANCHOR(anchor) # '&anchor' -// TAG(handle,suffix) # '!handle!suffix' -// SCALAR(value,style) # A scalar. -// -// The following two tokens are "virtual" tokens denoting the beginning and the -// end of the stream: -// -// STREAM-START(encoding) -// STREAM-END -// -// We pass the information about the input stream encoding with the -// STREAM-START token. -// -// The next two tokens are responsible for tags: -// -// VERSION-DIRECTIVE(major,minor) -// TAG-DIRECTIVE(handle,prefix) -// -// Example: -// -// %YAML 1.1 -// %TAG ! !foo -// %TAG !yaml! tag:yaml.org,2002: -// --- -// -// The correspoding sequence of tokens: -// -// STREAM-START(utf-8) -// VERSION-DIRECTIVE(1,1) -// TAG-DIRECTIVE("!","!foo") -// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") -// DOCUMENT-START -// STREAM-END -// -// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole -// line. -// -// The document start and end indicators are represented by: -// -// DOCUMENT-START -// DOCUMENT-END -// -// Note that if a YAML stream contains an implicit document (without '---' -// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be -// produced. -// -// In the following examples, we present whole documents together with the -// produced tokens. -// -// 1. An implicit document: -// -// 'a scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// STREAM-END -// -// 2. An explicit document: -// -// --- -// 'a scalar' -// ... -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// SCALAR("a scalar",single-quoted) -// DOCUMENT-END -// STREAM-END -// -// 3. Several documents in a stream: -// -// 'a scalar' -// --- -// 'another scalar' -// --- -// 'yet another scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// DOCUMENT-START -// SCALAR("another scalar",single-quoted) -// DOCUMENT-START -// SCALAR("yet another scalar",single-quoted) -// STREAM-END -// -// We have already introduced the SCALAR token above. The following tokens are -// used to describe aliases, anchors, tag, and scalars: -// -// ALIAS(anchor) -// ANCHOR(anchor) -// TAG(handle,suffix) -// SCALAR(value,style) -// -// The following series of examples illustrate the usage of these tokens: -// -// 1. A recursive sequence: -// -// &A [ *A ] -// -// Tokens: -// -// STREAM-START(utf-8) -// ANCHOR("A") -// FLOW-SEQUENCE-START -// ALIAS("A") -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A tagged scalar: -// -// !!float "3.14" # A good approximation. -// -// Tokens: -// -// STREAM-START(utf-8) -// TAG("!!","float") -// SCALAR("3.14",double-quoted) -// STREAM-END -// -// 3. Various scalar styles: -// -// --- # Implicit empty plain scalars do not produce tokens. -// --- a plain scalar -// --- 'a single-quoted scalar' -// --- "a double-quoted scalar" -// --- |- -// a literal scalar -// --- >- -// a folded -// scalar -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// DOCUMENT-START -// SCALAR("a plain scalar",plain) -// DOCUMENT-START -// SCALAR("a single-quoted scalar",single-quoted) -// DOCUMENT-START -// SCALAR("a double-quoted scalar",double-quoted) -// DOCUMENT-START -// SCALAR("a literal scalar",literal) -// DOCUMENT-START -// SCALAR("a folded scalar",folded) -// STREAM-END -// -// Now it's time to review collection-related tokens. We will start with -// flow collections: -// -// FLOW-SEQUENCE-START -// FLOW-SEQUENCE-END -// FLOW-MAPPING-START -// FLOW-MAPPING-END -// FLOW-ENTRY -// KEY -// VALUE -// -// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and -// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' -// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the -// indicators '?' and ':', which are used for denoting mapping keys and values, -// are represented by the KEY and VALUE tokens. -// -// The following examples show flow collections: -// -// 1. A flow sequence: -// -// [item 1, item 2, item 3] -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-SEQUENCE-START -// SCALAR("item 1",plain) -// FLOW-ENTRY -// SCALAR("item 2",plain) -// FLOW-ENTRY -// SCALAR("item 3",plain) -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A flow mapping: -// -// { -// a simple key: a value, # Note that the KEY token is produced. -// ? a complex key: another value, -// } -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// FLOW-ENTRY -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// FLOW-ENTRY -// FLOW-MAPPING-END -// STREAM-END -// -// A simple key is a key which is not denoted by the '?' indicator. Note that -// the Scanner still produce the KEY token whenever it encounters a simple key. -// -// For scanning block collections, the following tokens are used (note that we -// repeat KEY and VALUE here): -// -// BLOCK-SEQUENCE-START -// BLOCK-MAPPING-START -// BLOCK-END -// BLOCK-ENTRY -// KEY -// VALUE -// -// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation -// increase that precedes a block collection (cf. the INDENT token in Python). -// The token BLOCK-END denote indentation decrease that ends a block collection -// (cf. the DEDENT token in Python). However YAML has some syntax pecularities -// that makes detections of these tokens more complex. -// -// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators -// '-', '?', and ':' correspondingly. -// -// The following examples show how the tokens BLOCK-SEQUENCE-START, -// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: -// -// 1. Block sequences: -// -// - item 1 -// - item 2 -// - -// - item 3.1 -// - item 3.2 -// - -// key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 3.1",plain) -// BLOCK-ENTRY -// SCALAR("item 3.2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Block mappings: -// -// a simple key: a value # The KEY token is produced here. -// ? a complex key -// : another value -// a mapping: -// key 1: value 1 -// key 2: value 2 -// a sequence: -// - item 1 -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// KEY -// SCALAR("a mapping",plain) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML does not always require to start a new block collection from a new -// line. If the current line contains only '-', '?', and ':' indicators, a new -// block collection may start at the current line. The following examples -// illustrate this case: -// -// 1. Collections in a sequence: -// -// - - item 1 -// - item 2 -// - key 1: value 1 -// key 2: value 2 -// - ? complex key -// : complex value -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("complex key") -// VALUE -// SCALAR("complex value") -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Collections in a mapping: -// -// ? a sequence -// : - item 1 -// - item 2 -// ? a mapping -// : key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// KEY -// SCALAR("a mapping",plain) -// VALUE -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML also permits non-indented sequences if they are included into a block -// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: -// -// key: -// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key",plain) -// VALUE -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// - -// Ensure that the buffer contains the required number of characters. -// Return true on success, false on failure (reader error or memory error). -func cache(parser *yaml_parser_t, length int) bool { - // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) - return parser.unread >= length || yaml_parser_update_buffer(parser, length) -} - -// Advance the buffer pointer. -func skip(parser *yaml_parser_t) { - if !is_blank(parser.buffer, parser.buffer_pos) { - parser.newlines = 0 - } - parser.mark.index++ - parser.mark.column++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) -} - -func skip_line(parser *yaml_parser_t) { - if is_crlf(parser.buffer, parser.buffer_pos) { - parser.mark.index += 2 - parser.mark.column = 0 - parser.mark.line++ - parser.unread -= 2 - parser.buffer_pos += 2 - parser.newlines++ - } else if is_break(parser.buffer, parser.buffer_pos) { - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) - parser.newlines++ - } -} - -// Copy a character to a string buffer and advance pointers. -func read(parser *yaml_parser_t, s []byte) []byte { - if !is_blank(parser.buffer, parser.buffer_pos) { - parser.newlines = 0 - } - w := width(parser.buffer[parser.buffer_pos]) - if w == 0 { - panic("invalid character sequence") - } - if len(s) == 0 { - s = make([]byte, 0, 32) - } - if w == 1 && len(s)+w <= cap(s) { - s = s[:len(s)+1] - s[len(s)-1] = parser.buffer[parser.buffer_pos] - parser.buffer_pos++ - } else { - s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) - parser.buffer_pos += w - } - parser.mark.index++ - parser.mark.column++ - parser.unread-- - return s -} - -// Copy a line break character to a string buffer and advance pointers. -func read_line(parser *yaml_parser_t, s []byte) []byte { - buf := parser.buffer - pos := parser.buffer_pos - switch { - case buf[pos] == '\r' && buf[pos+1] == '\n': - // CR LF . LF - s = append(s, '\n') - parser.buffer_pos += 2 - parser.mark.index++ - parser.unread-- - case buf[pos] == '\r' || buf[pos] == '\n': - // CR|LF . LF - s = append(s, '\n') - parser.buffer_pos += 1 - case buf[pos] == '\xC2' && buf[pos+1] == '\x85': - // NEL . LF - s = append(s, '\n') - parser.buffer_pos += 2 - case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): - // LS|PS . LS|PS - s = append(s, buf[parser.buffer_pos:pos+3]...) - parser.buffer_pos += 3 - default: - return s - } - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.newlines++ - return s -} - -// Get the next token. -func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { - // Erase the token object. - *token = yaml_token_t{} // [Go] Is this necessary? - - // No tokens after STREAM-END or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR { - return true - } - - // Ensure that the tokens queue contains enough tokens. - if !parser.token_available { - if !yaml_parser_fetch_more_tokens(parser) { - return false - } - } - - // Fetch the next token from the queue. - *token = parser.tokens[parser.tokens_head] - parser.tokens_head++ - parser.tokens_parsed++ - parser.token_available = false - - if token.typ == yaml_STREAM_END_TOKEN { - parser.stream_end_produced = true - } - return true -} - -// Set the scanner error and return false. -func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { - parser.error = yaml_SCANNER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = parser.mark - return false -} - -func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { - context := "while parsing a tag" - if directive { - context = "while parsing a %TAG directive" - } - return yaml_parser_set_scanner_error(parser, context, context_mark, problem) -} - -func trace(args ...interface{}) func() { - pargs := append([]interface{}{"+++"}, args...) - fmt.Println(pargs...) - pargs = append([]interface{}{"---"}, args...) - return func() { fmt.Println(pargs...) } -} - -// Ensure that the tokens queue contains at least one token which can be -// returned to the Parser. -func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { - // While we need more tokens to fetch, do it. - for { - // [Go] The comment parsing logic requires a lookahead of two tokens - // so that foot comments may be parsed in time of associating them - // with the tokens that are parsed before them, and also for line - // comments to be transformed into head comments in some edge cases. - if parser.tokens_head < len(parser.tokens)-2 { - // If a potential simple key is at the head position, we need to fetch - // the next token to disambiguate it. - head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] - if !ok { - break - } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { - return false - } else if !valid { - break - } - } - // Fetch the next token. - if !yaml_parser_fetch_next_token(parser) { - return false - } - } - - parser.token_available = true - return true -} - -// The dispatcher for token fetchers. -func yaml_parser_fetch_next_token(parser *yaml_parser_t) (ok bool) { - // Ensure that the buffer is initialized. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we just started scanning. Fetch STREAM-START then. - if !parser.stream_start_produced { - return yaml_parser_fetch_stream_start(parser) - } - - scan_mark := parser.mark - - // Eat whitespaces and comments until we reach the next token. - if !yaml_parser_scan_to_next_token(parser) { - return false - } - - // [Go] While unrolling indents, transform the head comments of prior - // indentation levels observed after scan_start into foot comments at - // the respective indexes. - - // Check the indentation level against the current column. - if !yaml_parser_unroll_indent(parser, parser.mark.column, scan_mark) { - return false - } - - // Ensure that the buffer contains at least 4 characters. 4 is the length - // of the longest indicators ('--- ' and '... '). - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - // Is it the end of the stream? - if is_z(parser.buffer, parser.buffer_pos) { - return yaml_parser_fetch_stream_end(parser) - } - - // Is it a directive? - if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { - return yaml_parser_fetch_directive(parser) - } - - buf := parser.buffer - pos := parser.buffer_pos - - // Is it the document start indicator? - if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) - } - - // Is it the document end indicator? - if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) - } - - comment_mark := parser.mark - if len(parser.tokens) > 0 && (parser.flow_level == 0 && buf[pos] == ':' || parser.flow_level > 0 && buf[pos] == ',') { - // Associate any following comments with the prior token. - comment_mark = parser.tokens[len(parser.tokens)-1].start_mark - } - defer func() { - if !ok { - return - } - if len(parser.tokens) > 0 && parser.tokens[len(parser.tokens)-1].typ == yaml_BLOCK_ENTRY_TOKEN { - // Sequence indicators alone have no line comments. It becomes - // a head comment for whatever follows. - return - } - if !yaml_parser_scan_line_comment(parser, comment_mark) { - ok = false - return - } - }() - - // Is it the flow sequence start indicator? - if buf[pos] == '[' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) - } - - // Is it the flow mapping start indicator? - if parser.buffer[parser.buffer_pos] == '{' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) - } - - // Is it the flow sequence end indicator? - if parser.buffer[parser.buffer_pos] == ']' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_SEQUENCE_END_TOKEN) - } - - // Is it the flow mapping end indicator? - if parser.buffer[parser.buffer_pos] == '}' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_MAPPING_END_TOKEN) - } - - // Is it the flow entry indicator? - if parser.buffer[parser.buffer_pos] == ',' { - return yaml_parser_fetch_flow_entry(parser) - } - - // Is it the block entry indicator? - if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { - return yaml_parser_fetch_block_entry(parser) - } - - // Is it the key indicator? - if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_key(parser) - } - - // Is it the value indicator? - if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_value(parser) - } - - // Is it an alias? - if parser.buffer[parser.buffer_pos] == '*' { - return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) - } - - // Is it an anchor? - if parser.buffer[parser.buffer_pos] == '&' { - return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) - } - - // Is it a tag? - if parser.buffer[parser.buffer_pos] == '!' { - return yaml_parser_fetch_tag(parser) - } - - // Is it a literal scalar? - if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, true) - } - - // Is it a folded scalar? - if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, false) - } - - // Is it a single-quoted scalar? - if parser.buffer[parser.buffer_pos] == '\'' { - return yaml_parser_fetch_flow_scalar(parser, true) - } - - // Is it a double-quoted scalar? - if parser.buffer[parser.buffer_pos] == '"' { - return yaml_parser_fetch_flow_scalar(parser, false) - } - - // Is it a plain scalar? - // - // A plain scalar may start with any non-blank characters except - // - // '-', '?', ':', ',', '[', ']', '{', '}', - // '#', '&', '*', '!', '|', '>', '\'', '\"', - // '%', '@', '`'. - // - // In the block context (and, for the '-' indicator, in the flow context - // too), it may also start with the characters - // - // '-', '?', ':' - // - // if it is followed by a non-space character. - // - // The last rule is more restrictive than the specification requires. - // [Go] TODO Make this logic more reasonable. - //switch parser.buffer[parser.buffer_pos] { - //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': - //} - if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || - parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || - parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || - (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level == 0 && - (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && - !is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_plain_scalar(parser) - } - - // If we don't determine the token type so far, it is an error. - return yaml_parser_set_scanner_error(parser, - "while scanning for the next token", parser.mark, - "found character that cannot start any token") -} - -func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { - if !simple_key.possible { - return false, true - } - - // The 1.2 specification says: - // - // "If the ? indicator is omitted, parsing needs to see past the - // implicit key to recognize it as such. To limit the amount of - // lookahead required, the “:” indicator must appear at most 1024 - // Unicode characters beyond the start of the key. In addition, the key - // is restricted to a single line." - // - if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { - // Check if the potential simple key to be removed is required. - if simple_key.required { - return false, yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false - return false, true - } - return true, true -} - -// Check if a simple key may start at the current position and add it if -// needed. -func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { - // A simple key is required at the current position if the scanner is in - // the block context and the current column coincides with the indentation - // level. - - required := parser.flow_level == 0 && parser.indent == parser.mark.column - - // - // If the current position may start a simple key, save it. - // - if parser.simple_key_allowed { - simple_key := yaml_simple_key_t{ - possible: true, - required: required, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, - } - - if !yaml_parser_remove_simple_key(parser) { - return false - } - parser.simple_keys[len(parser.simple_keys)-1] = simple_key - parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 - } - return true -} - -// Remove a potential simple key at the current flow level. -func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { - i := len(parser.simple_keys) - 1 - if parser.simple_keys[i].possible { - // If the key is required, it is an error. - if parser.simple_keys[i].required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", parser.simple_keys[i].mark, - "could not find expected ':'") - } - // Remove the key from the stack. - parser.simple_keys[i].possible = false - delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) - } - return true -} - -// max_flow_level limits the flow_level -const max_flow_level = 10000 - -// Increase the flow level and resize the simple key list if needed. -func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { - // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ - possible: false, - required: false, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - mark: parser.mark, - }) - - // Increase the flow level. - parser.flow_level++ - if parser.flow_level > max_flow_level { - return yaml_parser_set_scanner_error(parser, - "while increasing flow level", parser.simple_keys[len(parser.simple_keys)-1].mark, - fmt.Sprintf("exceeded max depth of %d", max_flow_level)) - } - return true -} - -// Decrease the flow level. -func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { - if parser.flow_level > 0 { - parser.flow_level-- - last := len(parser.simple_keys) - 1 - delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) - parser.simple_keys = parser.simple_keys[:last] - } - return true -} - -// max_indents limits the indents stack size -const max_indents = 10000 - -// Push the current indentation level to the stack and set the new level -// the current column is greater than the indentation level. In this case, -// append or insert the specified token into the token queue. -func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - if parser.indent < column { - // Push the current indentation level to the stack and set the new - // indentation level. - parser.indents = append(parser.indents, parser.indent) - parser.indent = column - if len(parser.indents) > max_indents { - return yaml_parser_set_scanner_error(parser, - "while increasing indent level", parser.simple_keys[len(parser.simple_keys)-1].mark, - fmt.Sprintf("exceeded max depth of %d", max_indents)) - } - - // Create a token and insert it into the queue. - token := yaml_token_t{ - typ: typ, - start_mark: mark, - end_mark: mark, - } - if number > -1 { - number -= parser.tokens_parsed - } - yaml_insert_token(parser, number, &token) - } - return true -} - -// Pop indentation levels from the indents stack until the current level -// becomes less or equal to the column. For each indentation level, append -// the BLOCK-END token. -func yaml_parser_unroll_indent(parser *yaml_parser_t, column int, scan_mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - block_mark := scan_mark - block_mark.index-- - - // Loop through the indentation levels in the stack. - for parser.indent > column { - - // [Go] Reposition the end token before potential following - // foot comments of parent blocks. For that, search - // backwards for recent comments that were at the same - // indent as the block that is ending now. - stop_index := block_mark.index - for i := len(parser.comments) - 1; i >= 0; i-- { - comment := &parser.comments[i] - - if comment.end_mark.index < stop_index { - // Don't go back beyond the start of the comment/whitespace scan, unless column < 0. - // If requested indent column is < 0, then the document is over and everything else - // is a foot anyway. - break - } - if comment.start_mark.column == parser.indent+1 { - // This is a good match. But maybe there's a former comment - // at that same indent level, so keep searching. - block_mark = comment.start_mark - } - - // While the end of the former comment matches with - // the start of the following one, we know there's - // nothing in between and scanning is still safe. - stop_index = comment.scan_mark.index - } - - // Create a token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, - start_mark: block_mark, - end_mark: block_mark, - } - yaml_insert_token(parser, -1, &token) - - // Pop the indentation level. - parser.indent = parser.indents[len(parser.indents)-1] - parser.indents = parser.indents[:len(parser.indents)-1] - } - return true -} - -// Initialize the scanner and produce the STREAM-START token. -func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - - // Set the initial indentation. - parser.indent = -1 - - // Initialize the simple key stack. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - parser.simple_keys_by_tok = make(map[int]int) - - // A simple key is allowed at the beginning of the stream. - parser.simple_key_allowed = true - - // We have started. - parser.stream_start_produced = true - - // Create the STREAM-START token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the STREAM-END token and shut down the scanner. -func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - - // Force new line. - if parser.mark.column != 0 { - parser.mark.column = 0 - parser.mark.line++ - } - - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1, parser.mark) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the STREAM-END token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. -func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1, parser.mark) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. - token := yaml_token_t{} - if !yaml_parser_scan_directive(parser, &token) { - return false - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the DOCUMENT-START or DOCUMENT-END token. -func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1, parser.mark) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Consume the token. - start_mark := parser.mark - - skip(parser) - skip(parser) - skip(parser) - - end_mark := parser.mark - - // Create the DOCUMENT-START or DOCUMENT-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. -func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { - - // The indicators '[' and '{' may start a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // Increase the flow level. - if !yaml_parser_increase_flow_level(parser) { - return false - } - - // A simple key may follow the indicators '[' and '{'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. -func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset any potential simple key on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Decrease the flow level. - if !yaml_parser_decrease_flow_level(parser) { - return false - } - - // No simple keys after the indicators ']' and '}'. - parser.simple_key_allowed = false - - // Consume the token. - - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-ENTRY token. -func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after ','. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the BLOCK-ENTRY token. -func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { - // Check if the scanner is in the block context. - if parser.flow_level == 0 { - // Check if we are allowed to start a new entry. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "block sequence entries are not allowed in this context") - } - // Add the BLOCK-SEQUENCE-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { - return false - } - } else { - // It is an error for the '-' indicator to occur in the flow context, - // but we let the Parser detect and report about it because the Parser - // is able to point to the context. - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '-'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the BLOCK-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the KEY token. -func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - - // In the block context, additional checks are required. - if parser.flow_level == 0 { - // Check if we are allowed to start a new key (not nessesary simple). - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping keys are not allowed in this context") - } - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '?' in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the KEY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the VALUE token. -func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] - - // Have we found a simple key? - if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { - return false - - } else if valid { - - // Create the KEY token and insert it into the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: simple_key.mark, - end_mark: simple_key.mark, - } - yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) - - // In the block context, we may need to add the BLOCK-MAPPING-START token. - if !yaml_parser_roll_indent(parser, simple_key.mark.column, - simple_key.token_number, - yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { - return false - } - - // Remove the simple key. - simple_key.possible = false - delete(parser.simple_keys_by_tok, simple_key.token_number) - - // A simple key cannot follow another simple key. - parser.simple_key_allowed = false - - } else { - // The ':' indicator follows a complex key. - - // In the block context, extra checks are required. - if parser.flow_level == 0 { - - // Check if we are allowed to start a complex value. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping values are not allowed in this context") - } - - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Simple keys after ':' are allowed in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - } - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the VALUE token and append it to the queue. - token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the ALIAS or ANCHOR token. -func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // An anchor or an alias could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow an anchor or an alias. - parser.simple_key_allowed = false - - // Create the ALIAS or ANCHOR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_anchor(parser, &token, typ) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the TAG token. -func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { - // A tag could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a tag. - parser.simple_key_allowed = false - - // Create the TAG token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_tag(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. -func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { - // Remove any potential simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // A simple key may follow a block scalar. - parser.simple_key_allowed = true - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_block_scalar(parser, &token, literal) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. -func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_flow_scalar(parser, &token, single) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,plain) token. -func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_plain_scalar(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Eat whitespaces and comments until the next token is found. -func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - - scan_mark := parser.mark - - // Until the next token is not found. - for { - // Allow the BOM mark to start a line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { - skip(parser) - } - - // Eat whitespaces. - // Tabs are allowed: - // - in the flow context - // - in the block context, but not at the beginning of the line or - // after '-', '?', or ':' (complex value). - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if we just had a line comment under a sequence entry that - // looks more like a header to the following content. Similar to this: - // - // - # The comment - // - Some data - // - // If so, transform the line comment to a head comment and reposition. - if len(parser.comments) > 0 && len(parser.tokens) > 1 { - tokenA := parser.tokens[len(parser.tokens)-2] - tokenB := parser.tokens[len(parser.tokens)-1] - comment := &parser.comments[len(parser.comments)-1] - if tokenA.typ == yaml_BLOCK_SEQUENCE_START_TOKEN && tokenB.typ == yaml_BLOCK_ENTRY_TOKEN && len(comment.line) > 0 && !is_break(parser.buffer, parser.buffer_pos) { - // If it was in the prior line, reposition so it becomes a - // header of the follow up token. Otherwise, keep it in place - // so it becomes a header of the former. - comment.head = comment.line - comment.line = nil - if comment.start_mark.line == parser.mark.line-1 { - comment.token_mark = parser.mark - } - } - } - - // Eat a comment until a line break. - if parser.buffer[parser.buffer_pos] == '#' { - if !yaml_parser_scan_comments(parser, scan_mark) { - return false - } - } - - // If it is a line break, eat it. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - - // In the block context, a new line may start a simple key. - if parser.flow_level == 0 { - parser.simple_key_allowed = true - } - } else { - break // We have found a token. - } - } - - return true -} - -// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { - // Eat '%'. - start_mark := parser.mark - skip(parser) - - // Scan the directive name. - var name []byte - if !yaml_parser_scan_directive_name(parser, start_mark, &name) { - return false - } - - // Is it a YAML directive? - if bytes.Equal(name, []byte("YAML")) { - // Scan the VERSION directive value. - var major, minor int8 - if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { - return false - } - end_mark := parser.mark - - // Create a VERSION-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, - } - - // Is it a TAG directive? - } else if bytes.Equal(name, []byte("TAG")) { - // Scan the TAG directive value. - var handle, prefix []byte - if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { - return false - } - end_mark := parser.mark - - // Create a TAG-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, - } - - // Unknown directive. - } else { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unknown directive name") - return false - } - - // Eat the rest of the line including any comments. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - if parser.buffer[parser.buffer_pos] == '#' { - // [Go] Discard this inline comment for the time being. - //if !yaml_parser_scan_line_comment(parser, start_mark) { - // return false - //} - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - return true -} - -// Scan the directive name. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ -// -func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { - // Consume the directive name. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - var s []byte - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the name is empty. - if len(s) == 0 { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "could not find expected directive name") - return false - } - - // Check for an blank character after the name. - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unexpected non-alphabetical character") - return false - } - *name = s - return true -} - -// Scan the value of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^ -func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the major version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { - return false - } - - // Eat '.'. - if parser.buffer[parser.buffer_pos] != '.' { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected digit or '.' character") - } - - skip(parser) - - // Consume the minor version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { - return false - } - return true -} - -const max_number_length = 2 - -// Scan the version number of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ -func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - - // Repeat while the next character is digit. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var value, length int8 - for is_digit(parser.buffer, parser.buffer_pos) { - // Check if the number is too long. - length++ - if length > max_number_length { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "found extremely long version number") - } - value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the number was present. - if length == 0 { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected version number") - } - *number = value - return true -} - -// Scan the value of a TAG-DIRECTIVE token. -// -// Scope: -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { - var handle_value, prefix_value []byte - - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a handle. - if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { - return false - } - - // Expect a whitespace. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blank(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace") - return false - } - - // Eat whitespaces. - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a prefix. - if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { - return false - } - - // Expect a whitespace or line break. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace or line break") - return false - } - - *handle = handle_value - *prefix = prefix_value - return true -} - -func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { - var s []byte - - // Eat the indicator character. - start_mark := parser.mark - skip(parser) - - // Consume the value. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - end_mark := parser.mark - - /* - * Check if length of the anchor is greater than 0 and it is followed by - * a whitespace character or one of the indicators: - * - * '?', ':', ',', ']', '}', '%', '@', '`'. - */ - - if len(s) == 0 || - !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || - parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '`') { - context := "while scanning an alias" - if typ == yaml_ANCHOR_TOKEN { - context = "while scanning an anchor" - } - yaml_parser_set_scanner_error(parser, context, start_mark, - "did not find expected alphabetic or numeric character") - return false - } - - // Create a token. - *token = yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - value: s, - } - - return true -} - -/* - * Scan a TAG token. - */ - -func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { - var handle, suffix []byte - - start_mark := parser.mark - - // Check if the tag is in the canonical form. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - if parser.buffer[parser.buffer_pos+1] == '<' { - // Keep the handle as '' - - // Eat '!<' - skip(parser) - skip(parser) - - // Consume the tag value. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - - // Check for '>' and eat it. - if parser.buffer[parser.buffer_pos] != '>' { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find the expected '>'") - return false - } - - skip(parser) - } else { - // The tag has either the '!suffix' or the '!handle!suffix' form. - - // First, try to scan a handle. - if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { - return false - } - - // Check if it is, indeed, handle. - if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { - // Scan the suffix now. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - } else { - // It wasn't a handle after all. Scan the rest of the tag. - if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { - return false - } - - // Set the handle to '!'. - handle = []byte{'!'} - - // A special case: the '!' tag. Set the handle to '' and the - // suffix to '!'. - if len(suffix) == 0 { - handle, suffix = suffix, handle - } - } - } - - // Check the character which ends the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find expected whitespace or line break") - return false - } - - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, - } - return true -} - -// Scan a tag handle. -func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { - // Check the initial '!' character. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] != '!' { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - - var s []byte - - // Copy the '!' character. - s = read(parser, s) - - // Copy all subsequent alphabetical and numerical characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the trailing character is '!' and copy it. - if parser.buffer[parser.buffer_pos] == '!' { - s = read(parser, s) - } else { - // It's either the '!' tag or not really a tag handle. If it's a %TAG - // directive, it's an error. If it's a tag token, it must be a part of URI. - if directive && string(s) != "!" { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - } - - *handle = s - return true -} - -// Scan a tag. -func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 - var s []byte - hasTag := len(head) > 0 - - // Copy the head if needed. - // - // Note that we don't copy the leading '!' character. - if len(head) > 1 { - s = append(s, head[1:]...) - } - - // Scan the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // The set of characters that may appear in URI is as follows: - // - // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', - // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', - // '%'. - // [Go] TODO Convert this into more reasonable logic. - for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || - parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || - parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || - parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || - parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || - parser.buffer[parser.buffer_pos] == '%' { - // Check if it is a URI-escape sequence. - if parser.buffer[parser.buffer_pos] == '%' { - if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { - return false - } - } else { - s = read(parser, s) - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - hasTag = true - } - - if !hasTag { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected tag URI") - return false - } - *uri = s - return true -} - -// Decode an URI-escape sequence corresponding to a single UTF-8 character. -func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - - // Decode the required number of characters. - w := 1024 - for w > 0 { - // Check for a URI-escaped octet. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - - if !(parser.buffer[parser.buffer_pos] == '%' && - is_hex(parser.buffer, parser.buffer_pos+1) && - is_hex(parser.buffer, parser.buffer_pos+2)) { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find URI escaped octet") - } - - // Get the octet. - octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) - - // If it is the leading octet, determine the length of the UTF-8 sequence. - if w == 1024 { - w = width(octet) - if w == 0 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect leading UTF-8 octet") - } - } else { - // Check if the trailing octet is correct. - if octet&0xC0 != 0x80 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect trailing UTF-8 octet") - } - } - - // Copy the octet and move the pointers. - *s = append(*s, octet) - skip(parser) - skip(parser) - skip(parser) - w-- - } - return true -} - -// Scan a block scalar. -func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { - // Eat the indicator '|' or '>'. - start_mark := parser.mark - skip(parser) - - // Scan the additional block scalar indicators. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check for a chomping indicator. - var chomping, increment int - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - // Set the chomping method and eat the indicator. - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - - // Check for an indentation indicator. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_digit(parser.buffer, parser.buffer_pos) { - // Check that the indentation is greater than 0. - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - - // Get the indentation level and eat the indicator. - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - } - - } else if is_digit(parser.buffer, parser.buffer_pos) { - // Do the same as above, but in the opposite order. - - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - } - } - - // Eat whitespaces and comments to the end of the line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.buffer[parser.buffer_pos] == '#' { - if !yaml_parser_scan_line_comment(parser, start_mark) { - return false - } - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - end_mark := parser.mark - - // Set the indentation level if it was specified. - var indent int - if increment > 0 { - if parser.indent >= 0 { - indent = parser.indent + increment - } else { - indent = increment - } - } - - // Scan the leading line breaks and determine the indentation level if needed. - var s, leading_break, trailing_breaks []byte - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - - // Scan the block scalar content. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var leading_blank, trailing_blank bool - for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { - // We are at the beginning of a non-empty line. - - // Is it a trailing whitespace? - trailing_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Check if we need to fold the leading line break. - if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { - // Do we need to join the lines by space? - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } - } else { - s = append(s, leading_break...) - } - leading_break = leading_break[:0] - - // Append the remaining line breaks. - s = append(s, trailing_breaks...) - trailing_breaks = trailing_breaks[:0] - - // Is it a leading whitespace? - leading_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Consume the current line. - for !is_breakz(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - leading_break = read_line(parser, leading_break) - - // Eat the following indentation spaces and line breaks. - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - } - - // Chomp the tail. - if chomping != -1 { - s = append(s, leading_break...) - } - if chomping == 1 { - s = append(s, trailing_breaks...) - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, - } - if !literal { - token.style = yaml_FOLDED_SCALAR_STYLE - } - return true -} - -// Scan indentation spaces and line breaks for a block scalar. Determine the -// indentation level if needed. -func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { - *end_mark = parser.mark - - // Eat the indentation spaces and line breaks. - max_indent := 0 - for { - // Eat the indentation spaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.mark.column > max_indent { - max_indent = parser.mark.column - } - - // Check for a tab character messing the indentation. - if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { - return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found a tab character where an indentation space is expected") - } - - // Have we found a non-empty line? - if !is_break(parser.buffer, parser.buffer_pos) { - break - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - // [Go] Should really be returning breaks instead. - *breaks = read_line(parser, *breaks) - *end_mark = parser.mark - } - - // Determine the indentation level if needed. - if *indent == 0 { - *indent = max_indent - if *indent < parser.indent+1 { - *indent = parser.indent + 1 - } - if *indent < 1 { - *indent = 1 - } - } - return true -} - -// Scan a quoted scalar. -func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { - // Eat the left quote. - start_mark := parser.mark - skip(parser) - - // Consume the content of the quoted scalar. - var s, leading_break, trailing_breaks, whitespaces []byte - for { - // Check that there are no document indicators at the beginning of the line. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected document indicator") - return false - } - - // Check for EOF. - if is_z(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected end of stream") - return false - } - - // Consume non-blank characters. - leading_blanks := false - for !is_blankz(parser.buffer, parser.buffer_pos) { - if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { - // Is is an escaped single quote. - s = append(s, '\'') - skip(parser) - skip(parser) - - } else if single && parser.buffer[parser.buffer_pos] == '\'' { - // It is a right single quote. - break - } else if !single && parser.buffer[parser.buffer_pos] == '"' { - // It is a right double quote. - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { - // It is an escaped line break. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - skip(parser) - skip_line(parser) - leading_blanks = true - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' { - // It is an escape sequence. - code_length := 0 - - // Check the escape character. - switch parser.buffer[parser.buffer_pos+1] { - case '0': - s = append(s, 0) - case 'a': - s = append(s, '\x07') - case 'b': - s = append(s, '\x08') - case 't', '\t': - s = append(s, '\x09') - case 'n': - s = append(s, '\x0A') - case 'v': - s = append(s, '\x0B') - case 'f': - s = append(s, '\x0C') - case 'r': - s = append(s, '\x0D') - case 'e': - s = append(s, '\x1B') - case ' ': - s = append(s, '\x20') - case '"': - s = append(s, '"') - case '\'': - s = append(s, '\'') - case '\\': - s = append(s, '\\') - case 'N': // NEL (#x85) - s = append(s, '\xC2') - s = append(s, '\x85') - case '_': // #xA0 - s = append(s, '\xC2') - s = append(s, '\xA0') - case 'L': // LS (#x2028) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA8') - case 'P': // PS (#x2029) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA9') - case 'x': - code_length = 2 - case 'u': - code_length = 4 - case 'U': - code_length = 8 - default: - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found unknown escape character") - return false - } - - skip(parser) - skip(parser) - - // Consume an arbitrary escape code. - if code_length > 0 { - var value int - - // Scan the character value. - if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { - return false - } - for k := 0; k < code_length; k++ { - if !is_hex(parser.buffer, parser.buffer_pos+k) { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "did not find expected hexdecimal number") - return false - } - value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) - } - - // Check the value and write the character. - if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found invalid Unicode character escape code") - return false - } - if value <= 0x7F { - s = append(s, byte(value)) - } else if value <= 0x7FF { - s = append(s, byte(0xC0+(value>>6))) - s = append(s, byte(0x80+(value&0x3F))) - } else if value <= 0xFFFF { - s = append(s, byte(0xE0+(value>>12))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } else { - s = append(s, byte(0xF0+(value>>18))) - s = append(s, byte(0x80+((value>>12)&0x3F))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } - - // Advance the pointer. - for k := 0; k < code_length; k++ { - skip(parser) - } - } - } else { - // It is a non-escaped non-blank character. - s = read(parser, s) - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we are at the end of the scalar. - if single { - if parser.buffer[parser.buffer_pos] == '\'' { - break - } - } else { - if parser.buffer[parser.buffer_pos] == '"' { - break - } - } - - // Consume blank characters. - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Join the whitespaces or fold line breaks. - if leading_blanks { - // Do we need to fold line breaks? - if len(leading_break) > 0 && leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Eat the right quote. - skip(parser) - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, - } - if !single { - token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - return true -} - -// Scan a plain scalar. -func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - - var s, leading_break, trailing_breaks, whitespaces []byte - var leading_blanks bool - var indent = parser.indent + 1 - - start_mark := parser.mark - end_mark := parser.mark - - // Consume the content of the plain scalar. - for { - // Check for a document indicator. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - break - } - - // Check for a comment. - if parser.buffer[parser.buffer_pos] == '#' { - break - } - - // Consume non-blank characters. - for !is_blankz(parser.buffer, parser.buffer_pos) { - - // Check for indicators that may end a plain scalar. - if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level > 0 && - (parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}')) { - break - } - - // Check if we need to join whitespaces and breaks. - if leading_blanks || len(whitespaces) > 0 { - if leading_blanks { - // Do we need to fold line breaks? - if leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - leading_blanks = false - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Copy the character. - s = read(parser, s) - - end_mark = parser.mark - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - // Is it the end? - if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { - break - } - - // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - - // Check for tab characters that abuse indentation. - if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found a tab character that violates indentation") - return false - } - - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check indentation level. - if parser.flow_level == 0 && parser.mark.column < indent { - break - } - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, - } - - // Note that we change the 'simple_key_allowed' flag. - if leading_blanks { - parser.simple_key_allowed = true - } - return true -} - -func yaml_parser_scan_line_comment(parser *yaml_parser_t, token_mark yaml_mark_t) bool { - if parser.newlines > 0 { - return true - } - - var start_mark yaml_mark_t - var text []byte - - for peek := 0; peek < 512; peek++ { - if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { - break - } - if is_blank(parser.buffer, parser.buffer_pos+peek) { - continue - } - if parser.buffer[parser.buffer_pos+peek] == '#' { - seen := parser.mark.index+peek - for { - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_breakz(parser.buffer, parser.buffer_pos) { - if parser.mark.index >= seen { - break - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } else if parser.mark.index >= seen { - if len(text) == 0 { - start_mark = parser.mark - } - text = read(parser, text) - } else { - skip(parser) - } - } - } - break - } - if len(text) > 0 { - parser.comments = append(parser.comments, yaml_comment_t{ - token_mark: token_mark, - start_mark: start_mark, - line: text, - }) - } - return true -} - -func yaml_parser_scan_comments(parser *yaml_parser_t, scan_mark yaml_mark_t) bool { - token := parser.tokens[len(parser.tokens)-1] - - if token.typ == yaml_FLOW_ENTRY_TOKEN && len(parser.tokens) > 1 { - token = parser.tokens[len(parser.tokens)-2] - } - - var token_mark = token.start_mark - var start_mark yaml_mark_t - var next_indent = parser.indent - if next_indent < 0 { - next_indent = 0 - } - - var recent_empty = false - var first_empty = parser.newlines <= 1 - - var line = parser.mark.line - var column = parser.mark.column - - var text []byte - - // The foot line is the place where a comment must start to - // still be considered as a foot of the prior content. - // If there's some content in the currently parsed line, then - // the foot is the line below it. - var foot_line = -1 - if scan_mark.line > 0 { - foot_line = parser.mark.line-parser.newlines+1 - if parser.newlines == 0 && parser.mark.column > 1 { - foot_line++ - } - } - - var peek = 0 - for ; peek < 512; peek++ { - if parser.unread < peek+1 && !yaml_parser_update_buffer(parser, peek+1) { - break - } - column++ - if is_blank(parser.buffer, parser.buffer_pos+peek) { - continue - } - c := parser.buffer[parser.buffer_pos+peek] - var close_flow = parser.flow_level > 0 && (c == ']' || c == '}') - if close_flow || is_breakz(parser.buffer, parser.buffer_pos+peek) { - // Got line break or terminator. - if close_flow || !recent_empty { - if close_flow || first_empty && (start_mark.line == foot_line && token.typ != yaml_VALUE_TOKEN || start_mark.column-1 < next_indent) { - // This is the first empty line and there were no empty lines before, - // so this initial part of the comment is a foot of the prior token - // instead of being a head for the following one. Split it up. - // Alternatively, this might also be the last comment inside a flow - // scope, so it must be a footer. - if len(text) > 0 { - if start_mark.column-1 < next_indent { - // If dedented it's unrelated to the prior token. - token_mark = start_mark - } - parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, - token_mark: token_mark, - start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, - foot: text, - }) - scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} - token_mark = scan_mark - text = nil - } - } else { - if len(text) > 0 && parser.buffer[parser.buffer_pos+peek] != 0 { - text = append(text, '\n') - } - } - } - if !is_break(parser.buffer, parser.buffer_pos+peek) { - break - } - first_empty = false - recent_empty = true - column = 0 - line++ - continue - } - - if len(text) > 0 && (close_flow || column-1 < next_indent && column != start_mark.column) { - // The comment at the different indentation is a foot of the - // preceding data rather than a head of the upcoming one. - parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, - token_mark: token_mark, - start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek, line, column}, - foot: text, - }) - scan_mark = yaml_mark_t{parser.mark.index + peek, line, column} - token_mark = scan_mark - text = nil - } - - if parser.buffer[parser.buffer_pos+peek] != '#' { - break - } - - if len(text) == 0 { - start_mark = yaml_mark_t{parser.mark.index + peek, line, column} - } else { - text = append(text, '\n') - } - - recent_empty = false - - // Consume until after the consumed comment line. - seen := parser.mark.index+peek - for { - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_breakz(parser.buffer, parser.buffer_pos) { - if parser.mark.index >= seen { - break - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } else if parser.mark.index >= seen { - text = read(parser, text) - } else { - skip(parser) - } - } - - peek = 0 - column = 0 - line = parser.mark.line - next_indent = parser.indent - if next_indent < 0 { - next_indent = 0 - } - } - - if len(text) > 0 { - parser.comments = append(parser.comments, yaml_comment_t{ - scan_mark: scan_mark, - token_mark: start_mark, - start_mark: start_mark, - end_mark: yaml_mark_t{parser.mark.index + peek - 1, line, column}, - head: text, - }) - } - return true -} diff --git a/vendor/gopkg.in/yaml.v3/sorter.go b/vendor/gopkg.in/yaml.v3/sorter.go deleted file mode 100644 index 9210ece..0000000 --- a/vendor/gopkg.in/yaml.v3/sorter.go +++ /dev/null @@ -1,134 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// 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 yaml - -import ( - "reflect" - "unicode" -) - -type keyList []reflect.Value - -func (l keyList) Len() int { return len(l) } -func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } -func (l keyList) Less(i, j int) bool { - a := l[i] - b := l[j] - ak := a.Kind() - bk := b.Kind() - for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { - a = a.Elem() - ak = a.Kind() - } - for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { - b = b.Elem() - bk = b.Kind() - } - af, aok := keyFloat(a) - bf, bok := keyFloat(b) - if aok && bok { - if af != bf { - return af < bf - } - if ak != bk { - return ak < bk - } - return numLess(a, b) - } - if ak != reflect.String || bk != reflect.String { - return ak < bk - } - ar, br := []rune(a.String()), []rune(b.String()) - digits := false - for i := 0; i < len(ar) && i < len(br); i++ { - if ar[i] == br[i] { - digits = unicode.IsDigit(ar[i]) - continue - } - al := unicode.IsLetter(ar[i]) - bl := unicode.IsLetter(br[i]) - if al && bl { - return ar[i] < br[i] - } - if al || bl { - if digits { - return al - } else { - return bl - } - } - var ai, bi int - var an, bn int64 - if ar[i] == '0' || br[i] == '0' { - for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- { - if ar[j] != '0' { - an = 1 - bn = 1 - break - } - } - } - for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { - an = an*10 + int64(ar[ai]-'0') - } - for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { - bn = bn*10 + int64(br[bi]-'0') - } - if an != bn { - return an < bn - } - if ai != bi { - return ai < bi - } - return ar[i] < br[i] - } - return len(ar) < len(br) -} - -// keyFloat returns a float value for v if it is a number/bool -// and whether it is a number/bool or not. -func keyFloat(v reflect.Value) (f float64, ok bool) { - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return float64(v.Int()), true - case reflect.Float32, reflect.Float64: - return v.Float(), true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return float64(v.Uint()), true - case reflect.Bool: - if v.Bool() { - return 1, true - } - return 0, true - } - return 0, false -} - -// numLess returns whether a < b. -// a and b must necessarily have the same kind. -func numLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return a.Int() < b.Int() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Bool: - return !a.Bool() && b.Bool() - } - panic("not a number") -} diff --git a/vendor/gopkg.in/yaml.v3/writerc.go b/vendor/gopkg.in/yaml.v3/writerc.go deleted file mode 100644 index b8a116b..0000000 --- a/vendor/gopkg.in/yaml.v3/writerc.go +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -// Set the writer error and return false. -func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_WRITER_ERROR - emitter.problem = problem - return false -} - -// Flush the output buffer. -func yaml_emitter_flush(emitter *yaml_emitter_t) bool { - if emitter.write_handler == nil { - panic("write handler not set") - } - - // Check if the buffer is empty. - if emitter.buffer_pos == 0 { - return true - } - - if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - return true -} diff --git a/vendor/gopkg.in/yaml.v3/yaml.go b/vendor/gopkg.in/yaml.v3/yaml.go deleted file mode 100644 index 8cec6da..0000000 --- a/vendor/gopkg.in/yaml.v3/yaml.go +++ /dev/null @@ -1,698 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// -// 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 yaml implements YAML support for the Go language. -// -// Source code and other details for the project are available at GitHub: -// -// https://github.com/go-yaml/yaml -// -package yaml - -import ( - "errors" - "fmt" - "io" - "reflect" - "strings" - "sync" - "unicode/utf8" -) - -// The Unmarshaler interface may be implemented by types to customize their -// behavior when being unmarshaled from a YAML document. -type Unmarshaler interface { - UnmarshalYAML(value *Node) error -} - -type obsoleteUnmarshaler interface { - UnmarshalYAML(unmarshal func(interface{}) error) error -} - -// The Marshaler interface may be implemented by types to customize their -// behavior when being marshaled into a YAML document. The returned value -// is marshaled in place of the original value implementing Marshaler. -// -// If an error is returned by MarshalYAML, the marshaling procedure stops -// and returns with the provided error. -type Marshaler interface { - MarshalYAML() (interface{}, error) -} - -// Unmarshal decodes the first document found within the in byte slice -// and assigns decoded values into the out value. -// -// Maps and pointers (to a struct, string, int, etc) are accepted as out -// values. If an internal pointer within a struct is not initialized, -// the yaml package will initialize it if necessary for unmarshalling -// the provided data. The out parameter must not be nil. -// -// The type of the decoded values should be compatible with the respective -// values in out. If one or more values cannot be decoded due to a type -// mismatches, decoding continues partially until the end of the YAML -// content, and a *yaml.TypeError is returned with details for all -// missed values. -// -// Struct fields are only unmarshalled if they are exported (have an -// upper case first letter), and are unmarshalled using the field name -// lowercased as the default key. Custom keys may be defined via the -// "yaml" name in the field tag: the content preceding the first comma -// is used as the key, and the following comma-separated options are -// used to tweak the marshalling process (see Marshal). -// Conflicting names result in a runtime error. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// var t T -// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) -// -// See the documentation of Marshal for the format of tags and a list of -// supported tag options. -// -func Unmarshal(in []byte, out interface{}) (err error) { - return unmarshal(in, out, false) -} - -// A Decoder reads and decodes YAML values from an input stream. -type Decoder struct { - parser *parser - knownFields bool -} - -// NewDecoder returns a new decoder that reads from r. -// -// The decoder introduces its own buffering and may read -// data from r beyond the YAML values requested. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{ - parser: newParserFromReader(r), - } -} - -// KnownFields ensures that the keys in decoded mappings to -// exist as fields in the struct being decoded into. -func (dec *Decoder) KnownFields(enable bool) { - dec.knownFields = enable -} - -// Decode reads the next YAML-encoded value from its input -// and stores it in the value pointed to by v. -// -// See the documentation for Unmarshal for details about the -// conversion of YAML into a Go value. -func (dec *Decoder) Decode(v interface{}) (err error) { - d := newDecoder() - d.knownFields = dec.knownFields - defer handleErr(&err) - node := dec.parser.parse() - if node == nil { - return io.EOF - } - out := reflect.ValueOf(v) - if out.Kind() == reflect.Ptr && !out.IsNil() { - out = out.Elem() - } - d.unmarshal(node, out) - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -// Decode decodes the node and stores its data into the value pointed to by v. -// -// See the documentation for Unmarshal for details about the -// conversion of YAML into a Go value. -func (n *Node) Decode(v interface{}) (err error) { - d := newDecoder() - defer handleErr(&err) - out := reflect.ValueOf(v) - if out.Kind() == reflect.Ptr && !out.IsNil() { - out = out.Elem() - } - d.unmarshal(n, out) - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -func unmarshal(in []byte, out interface{}, strict bool) (err error) { - defer handleErr(&err) - d := newDecoder() - p := newParser(in) - defer p.destroy() - node := p.parse() - if node != nil { - v := reflect.ValueOf(out) - if v.Kind() == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - d.unmarshal(node, v) - } - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -// Marshal serializes the value provided into a YAML document. The structure -// of the generated document will reflect the structure of the value itself. -// Maps and pointers (to struct, string, int, etc) are accepted as the in value. -// -// Struct fields are only marshalled if they are exported (have an upper case -// first letter), and are marshalled using the field name lowercased as the -// default key. Custom keys may be defined via the "yaml" name in the field -// tag: the content preceding the first comma is used as the key, and the -// following comma-separated options are used to tweak the marshalling process. -// Conflicting names result in a runtime error. -// -// The field tag format accepted is: -// -// `(...) yaml:"[][,[,]]" (...)` -// -// The following flags are currently supported: -// -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// Zero valued structs will be omitted if all their public -// fields are zero, unless they implement an IsZero -// method (see the IsZeroer interface type), in which -// case the field will be excluded if IsZero returns true. -// -// flow Marshal using a flow style (useful for structs, -// sequences and maps). -// -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the yaml keys of other struct fields. -// -// In addition, if the key is "-", the field is ignored. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" -// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" -// -func Marshal(in interface{}) (out []byte, err error) { - defer handleErr(&err) - e := newEncoder() - defer e.destroy() - e.marshalDoc("", reflect.ValueOf(in)) - e.finish() - out = e.out - return -} - -// An Encoder writes YAML values to an output stream. -type Encoder struct { - encoder *encoder -} - -// NewEncoder returns a new encoder that writes to w. -// The Encoder should be closed after use to flush all data -// to w. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - encoder: newEncoderWithWriter(w), - } -} - -// Encode writes the YAML encoding of v to the stream. -// If multiple items are encoded to the stream, the -// second and subsequent document will be preceded -// with a "---" document separator, but the first will not. -// -// See the documentation for Marshal for details about the conversion of Go -// values to YAML. -func (e *Encoder) Encode(v interface{}) (err error) { - defer handleErr(&err) - e.encoder.marshalDoc("", reflect.ValueOf(v)) - return nil -} - -// Encode encodes value v and stores its representation in n. -// -// See the documentation for Marshal for details about the -// conversion of Go values into YAML. -func (n *Node) Encode(v interface{}) (err error) { - defer handleErr(&err) - e := newEncoder() - defer e.destroy() - e.marshalDoc("", reflect.ValueOf(v)) - e.finish() - p := newParser(e.out) - p.textless = true - defer p.destroy() - doc := p.parse() - *n = *doc.Content[0] - return nil -} - -// SetIndent changes the used indentation used when encoding. -func (e *Encoder) SetIndent(spaces int) { - if spaces < 0 { - panic("yaml: cannot indent to a negative number of spaces") - } - e.encoder.indent = spaces -} - -// Close closes the encoder by writing any remaining data. -// It does not write a stream terminating string "...". -func (e *Encoder) Close() (err error) { - defer handleErr(&err) - e.encoder.finish() - return nil -} - -func handleErr(err *error) { - if v := recover(); v != nil { - if e, ok := v.(yamlError); ok { - *err = e.err - } else { - panic(v) - } - } -} - -type yamlError struct { - err error -} - -func fail(err error) { - panic(yamlError{err}) -} - -func failf(format string, args ...interface{}) { - panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) -} - -// A TypeError is returned by Unmarshal when one or more fields in -// the YAML document cannot be properly decoded into the requested -// types. When this error is returned, the value is still -// unmarshaled partially. -type TypeError struct { - Errors []string -} - -func (e *TypeError) Error() string { - return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) -} - -type Kind uint32 - -const ( - DocumentNode Kind = 1 << iota - SequenceNode - MappingNode - ScalarNode - AliasNode -) - -type Style uint32 - -const ( - TaggedStyle Style = 1 << iota - DoubleQuotedStyle - SingleQuotedStyle - LiteralStyle - FoldedStyle - FlowStyle -) - -// Node represents an element in the YAML document hierarchy. While documents -// are typically encoded and decoded into higher level types, such as structs -// and maps, Node is an intermediate representation that allows detailed -// control over the content being decoded or encoded. -// -// It's worth noting that although Node offers access into details such as -// line numbers, colums, and comments, the content when re-encoded will not -// have its original textual representation preserved. An effort is made to -// render the data plesantly, and to preserve comments near the data they -// describe, though. -// -// Values that make use of the Node type interact with the yaml package in the -// same way any other type would do, by encoding and decoding yaml data -// directly or indirectly into them. -// -// For example: -// -// var person struct { -// Name string -// Address yaml.Node -// } -// err := yaml.Unmarshal(data, &person) -// -// Or by itself: -// -// var person Node -// err := yaml.Unmarshal(data, &person) -// -type Node struct { - // Kind defines whether the node is a document, a mapping, a sequence, - // a scalar value, or an alias to another node. The specific data type of - // scalar nodes may be obtained via the ShortTag and LongTag methods. - Kind Kind - - // Style allows customizing the apperance of the node in the tree. - Style Style - - // Tag holds the YAML tag defining the data type for the value. - // When decoding, this field will always be set to the resolved tag, - // even when it wasn't explicitly provided in the YAML content. - // When encoding, if this field is unset the value type will be - // implied from the node properties, and if it is set, it will only - // be serialized into the representation if TaggedStyle is used or - // the implicit tag diverges from the provided one. - Tag string - - // Value holds the unescaped and unquoted represenation of the value. - Value string - - // Anchor holds the anchor name for this node, which allows aliases to point to it. - Anchor string - - // Alias holds the node that this alias points to. Only valid when Kind is AliasNode. - Alias *Node - - // Content holds contained nodes for documents, mappings, and sequences. - Content []*Node - - // HeadComment holds any comments in the lines preceding the node and - // not separated by an empty line. - HeadComment string - - // LineComment holds any comments at the end of the line where the node is in. - LineComment string - - // FootComment holds any comments following the node and before empty lines. - FootComment string - - // Line and Column hold the node position in the decoded YAML text. - // These fields are not respected when encoding the node. - Line int - Column int -} - -// IsZero returns whether the node has all of its fields unset. -func (n *Node) IsZero() bool { - return n.Kind == 0 && n.Style == 0 && n.Tag == "" && n.Value == "" && n.Anchor == "" && n.Alias == nil && n.Content == nil && - n.HeadComment == "" && n.LineComment == "" && n.FootComment == "" && n.Line == 0 && n.Column == 0 -} - - -// LongTag returns the long form of the tag that indicates the data type for -// the node. If the Tag field isn't explicitly defined, one will be computed -// based on the node properties. -func (n *Node) LongTag() string { - return longTag(n.ShortTag()) -} - -// ShortTag returns the short form of the YAML tag that indicates data type for -// the node. If the Tag field isn't explicitly defined, one will be computed -// based on the node properties. -func (n *Node) ShortTag() string { - if n.indicatedString() { - return strTag - } - if n.Tag == "" || n.Tag == "!" { - switch n.Kind { - case MappingNode: - return mapTag - case SequenceNode: - return seqTag - case AliasNode: - if n.Alias != nil { - return n.Alias.ShortTag() - } - case ScalarNode: - tag, _ := resolve("", n.Value) - return tag - case 0: - // Special case to make the zero value convenient. - if n.IsZero() { - return nullTag - } - } - return "" - } - return shortTag(n.Tag) -} - -func (n *Node) indicatedString() bool { - return n.Kind == ScalarNode && - (shortTag(n.Tag) == strTag || - (n.Tag == "" || n.Tag == "!") && n.Style&(SingleQuotedStyle|DoubleQuotedStyle|LiteralStyle|FoldedStyle) != 0) -} - -// SetString is a convenience function that sets the node to a string value -// and defines its style in a pleasant way depending on its content. -func (n *Node) SetString(s string) { - n.Kind = ScalarNode - if utf8.ValidString(s) { - n.Value = s - n.Tag = strTag - } else { - n.Value = encodeBase64(s) - n.Tag = binaryTag - } - if strings.Contains(n.Value, "\n") { - n.Style = LiteralStyle - } -} - -// -------------------------------------------------------------------------- -// Maintain a mapping of keys to structure field indexes - -// The code in this section was copied from mgo/bson. - -// structInfo holds details for the serialization of fields of -// a given struct. -type structInfo struct { - FieldsMap map[string]fieldInfo - FieldsList []fieldInfo - - // InlineMap is the number of the field in the struct that - // contains an ,inline map, or -1 if there's none. - InlineMap int - - // InlineUnmarshalers holds indexes to inlined fields that - // contain unmarshaler values. - InlineUnmarshalers [][]int -} - -type fieldInfo struct { - Key string - Num int - OmitEmpty bool - Flow bool - // Id holds the unique field identifier, so we can cheaply - // check for field duplicates without maintaining an extra map. - Id int - - // Inline holds the field index if the field is part of an inlined struct. - Inline []int -} - -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex -var unmarshalerType reflect.Type - -func init() { - var v Unmarshaler - unmarshalerType = reflect.ValueOf(&v).Elem().Type() -} - -func getStructInfo(st reflect.Type) (*structInfo, error) { - fieldMapMutex.RLock() - sinfo, found := structMap[st] - fieldMapMutex.RUnlock() - if found { - return sinfo, nil - } - - n := st.NumField() - fieldsMap := make(map[string]fieldInfo) - fieldsList := make([]fieldInfo, 0, n) - inlineMap := -1 - inlineUnmarshalers := [][]int(nil) - for i := 0; i != n; i++ { - field := st.Field(i) - if field.PkgPath != "" && !field.Anonymous { - continue // Private field - } - - info := fieldInfo{Num: i} - - tag := field.Tag.Get("yaml") - if tag == "" && strings.Index(string(field.Tag), ":") < 0 { - tag = string(field.Tag) - } - if tag == "-" { - continue - } - - inline := false - fields := strings.Split(tag, ",") - if len(fields) > 1 { - for _, flag := range fields[1:] { - switch flag { - case "omitempty": - info.OmitEmpty = true - case "flow": - info.Flow = true - case "inline": - inline = true - default: - return nil, errors.New(fmt.Sprintf("unsupported flag %q in tag %q of type %s", flag, tag, st)) - } - } - tag = fields[0] - } - - if inline { - switch field.Type.Kind() { - case reflect.Map: - if inlineMap >= 0 { - return nil, errors.New("multiple ,inline maps in struct " + st.String()) - } - if field.Type.Key() != reflect.TypeOf("") { - return nil, errors.New("option ,inline needs a map with string keys in struct " + st.String()) - } - inlineMap = info.Num - case reflect.Struct, reflect.Ptr: - ftype := field.Type - for ftype.Kind() == reflect.Ptr { - ftype = ftype.Elem() - } - if ftype.Kind() != reflect.Struct { - return nil, errors.New("option ,inline may only be used on a struct or map field") - } - if reflect.PtrTo(ftype).Implements(unmarshalerType) { - inlineUnmarshalers = append(inlineUnmarshalers, []int{i}) - } else { - sinfo, err := getStructInfo(ftype) - if err != nil { - return nil, err - } - for _, index := range sinfo.InlineUnmarshalers { - inlineUnmarshalers = append(inlineUnmarshalers, append([]int{i}, index...)) - } - for _, finfo := range sinfo.FieldsList { - if _, found := fieldsMap[finfo.Key]; found { - msg := "duplicated key '" + finfo.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - if finfo.Inline == nil { - finfo.Inline = []int{i, finfo.Num} - } else { - finfo.Inline = append([]int{i}, finfo.Inline...) - } - finfo.Id = len(fieldsList) - fieldsMap[finfo.Key] = finfo - fieldsList = append(fieldsList, finfo) - } - } - default: - return nil, errors.New("option ,inline may only be used on a struct or map field") - } - continue - } - - if tag != "" { - info.Key = tag - } else { - info.Key = strings.ToLower(field.Name) - } - - if _, found = fieldsMap[info.Key]; found { - msg := "duplicated key '" + info.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - - info.Id = len(fieldsList) - fieldsList = append(fieldsList, info) - fieldsMap[info.Key] = info - } - - sinfo = &structInfo{ - FieldsMap: fieldsMap, - FieldsList: fieldsList, - InlineMap: inlineMap, - InlineUnmarshalers: inlineUnmarshalers, - } - - fieldMapMutex.Lock() - structMap[st] = sinfo - fieldMapMutex.Unlock() - return sinfo, nil -} - -// IsZeroer is used to check whether an object is zero to -// determine whether it should be omitted when marshaling -// with the omitempty flag. One notable implementation -// is time.Time. -type IsZeroer interface { - IsZero() bool -} - -func isZero(v reflect.Value) bool { - kind := v.Kind() - if z, ok := v.Interface().(IsZeroer); ok { - if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { - return true - } - return z.IsZero() - } - switch kind { - case reflect.String: - return len(v.String()) == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - case reflect.Slice: - return v.Len() == 0 - case reflect.Map: - return v.Len() == 0 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Struct: - vt := v.Type() - for i := v.NumField() - 1; i >= 0; i-- { - if vt.Field(i).PkgPath != "" { - continue // Private field - } - if !isZero(v.Field(i)) { - return false - } - } - return true - } - return false -} diff --git a/vendor/gopkg.in/yaml.v3/yamlh.go b/vendor/gopkg.in/yaml.v3/yamlh.go deleted file mode 100644 index 7c6d007..0000000 --- a/vendor/gopkg.in/yaml.v3/yamlh.go +++ /dev/null @@ -1,807 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -import ( - "fmt" - "io" -) - -// The version directive data. -type yaml_version_directive_t struct { - major int8 // The major version number. - minor int8 // The minor version number. -} - -// The tag directive data. -type yaml_tag_directive_t struct { - handle []byte // The tag handle. - prefix []byte // The tag prefix. -} - -type yaml_encoding_t int - -// The stream encoding. -const ( - // Let the parser choose the encoding. - yaml_ANY_ENCODING yaml_encoding_t = iota - - yaml_UTF8_ENCODING // The default UTF-8 encoding. - yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. - yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. -) - -type yaml_break_t int - -// Line break types. -const ( - // Let the parser choose the break type. - yaml_ANY_BREAK yaml_break_t = iota - - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). - yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). -) - -type yaml_error_type_t int - -// Many bad things could happen with the parser and emitter. -const ( - // No error is produced. - yaml_NO_ERROR yaml_error_type_t = iota - - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. - yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. -) - -// The pointer position. -type yaml_mark_t struct { - index int // The position index. - line int // The position line. - column int // The position column. -} - -// Node Styles - -type yaml_style_t int8 - -type yaml_scalar_style_t yaml_style_t - -// Scalar styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = 0 - - yaml_PLAIN_SCALAR_STYLE yaml_scalar_style_t = 1 << iota // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. -) - -type yaml_sequence_style_t yaml_style_t - -// Sequence styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota - - yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. -) - -type yaml_mapping_style_t yaml_style_t - -// Mapping styles. -const ( - // Let the emitter choose the style. - yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota - - yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. -) - -// Tokens - -type yaml_token_type_t int - -// Token types. -const ( - // An empty token. - yaml_NO_TOKEN yaml_token_type_t = iota - - yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. - - yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. - - yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. - - yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. - - yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - - yaml_ALIAS_TOKEN // An ALIAS token. - yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. - yaml_SCALAR_TOKEN // A SCALAR token. -) - -func (tt yaml_token_type_t) String() string { - switch tt { - case yaml_NO_TOKEN: - return "yaml_NO_TOKEN" - case yaml_STREAM_START_TOKEN: - return "yaml_STREAM_START_TOKEN" - case yaml_STREAM_END_TOKEN: - return "yaml_STREAM_END_TOKEN" - case yaml_VERSION_DIRECTIVE_TOKEN: - return "yaml_VERSION_DIRECTIVE_TOKEN" - case yaml_TAG_DIRECTIVE_TOKEN: - return "yaml_TAG_DIRECTIVE_TOKEN" - case yaml_DOCUMENT_START_TOKEN: - return "yaml_DOCUMENT_START_TOKEN" - case yaml_DOCUMENT_END_TOKEN: - return "yaml_DOCUMENT_END_TOKEN" - case yaml_BLOCK_SEQUENCE_START_TOKEN: - return "yaml_BLOCK_SEQUENCE_START_TOKEN" - case yaml_BLOCK_MAPPING_START_TOKEN: - return "yaml_BLOCK_MAPPING_START_TOKEN" - case yaml_BLOCK_END_TOKEN: - return "yaml_BLOCK_END_TOKEN" - case yaml_FLOW_SEQUENCE_START_TOKEN: - return "yaml_FLOW_SEQUENCE_START_TOKEN" - case yaml_FLOW_SEQUENCE_END_TOKEN: - return "yaml_FLOW_SEQUENCE_END_TOKEN" - case yaml_FLOW_MAPPING_START_TOKEN: - return "yaml_FLOW_MAPPING_START_TOKEN" - case yaml_FLOW_MAPPING_END_TOKEN: - return "yaml_FLOW_MAPPING_END_TOKEN" - case yaml_BLOCK_ENTRY_TOKEN: - return "yaml_BLOCK_ENTRY_TOKEN" - case yaml_FLOW_ENTRY_TOKEN: - return "yaml_FLOW_ENTRY_TOKEN" - case yaml_KEY_TOKEN: - return "yaml_KEY_TOKEN" - case yaml_VALUE_TOKEN: - return "yaml_VALUE_TOKEN" - case yaml_ALIAS_TOKEN: - return "yaml_ALIAS_TOKEN" - case yaml_ANCHOR_TOKEN: - return "yaml_ANCHOR_TOKEN" - case yaml_TAG_TOKEN: - return "yaml_TAG_TOKEN" - case yaml_SCALAR_TOKEN: - return "yaml_SCALAR_TOKEN" - } - return "" -} - -// The token structure. -type yaml_token_t struct { - // The token type. - typ yaml_token_type_t - - // The start/end of the token. - start_mark, end_mark yaml_mark_t - - // The stream encoding (for yaml_STREAM_START_TOKEN). - encoding yaml_encoding_t - - // The alias/anchor/scalar value or tag/tag directive handle - // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). - value []byte - - // The tag suffix (for yaml_TAG_TOKEN). - suffix []byte - - // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). - prefix []byte - - // The scalar style (for yaml_SCALAR_TOKEN). - style yaml_scalar_style_t - - // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). - major, minor int8 -} - -// Events - -type yaml_event_type_t int8 - -// Event types. -const ( - // An empty event. - yaml_NO_EVENT yaml_event_type_t = iota - - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. - yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. - yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. - yaml_TAIL_COMMENT_EVENT -) - -var eventStrings = []string{ - yaml_NO_EVENT: "none", - yaml_STREAM_START_EVENT: "stream start", - yaml_STREAM_END_EVENT: "stream end", - yaml_DOCUMENT_START_EVENT: "document start", - yaml_DOCUMENT_END_EVENT: "document end", - yaml_ALIAS_EVENT: "alias", - yaml_SCALAR_EVENT: "scalar", - yaml_SEQUENCE_START_EVENT: "sequence start", - yaml_SEQUENCE_END_EVENT: "sequence end", - yaml_MAPPING_START_EVENT: "mapping start", - yaml_MAPPING_END_EVENT: "mapping end", - yaml_TAIL_COMMENT_EVENT: "tail comment", -} - -func (e yaml_event_type_t) String() string { - if e < 0 || int(e) >= len(eventStrings) { - return fmt.Sprintf("unknown event %d", e) - } - return eventStrings[e] -} - -// The event structure. -type yaml_event_t struct { - - // The event type. - typ yaml_event_type_t - - // The start and end of the event. - start_mark, end_mark yaml_mark_t - - // The document encoding (for yaml_STREAM_START_EVENT). - encoding yaml_encoding_t - - // The version directive (for yaml_DOCUMENT_START_EVENT). - version_directive *yaml_version_directive_t - - // The list of tag directives (for yaml_DOCUMENT_START_EVENT). - tag_directives []yaml_tag_directive_t - - // The comments - head_comment []byte - line_comment []byte - foot_comment []byte - tail_comment []byte - - // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). - anchor []byte - - // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - tag []byte - - // The scalar value (for yaml_SCALAR_EVENT). - value []byte - - // Is the document start/end indicator implicit, or the tag optional? - // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). - implicit bool - - // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). - quoted_implicit bool - - // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - style yaml_style_t -} - -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } -func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } - -// Nodes - -const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. - yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. - - yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. - yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. - - // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. - yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. -) - -type yaml_node_type_t int - -// Node types. -const ( - // An empty node. - yaml_NO_NODE yaml_node_type_t = iota - - yaml_SCALAR_NODE // A scalar node. - yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. -) - -// An element of a sequence node. -type yaml_node_item_t int - -// An element of a mapping node. -type yaml_node_pair_t struct { - key int // The key of the element. - value int // The value of the element. -} - -// The node structure. -type yaml_node_t struct { - typ yaml_node_type_t // The node type. - tag []byte // The node tag. - - // The node data. - - // The scalar parameters (for yaml_SCALAR_NODE). - scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. - } - - // The sequence parameters (for YAML_SEQUENCE_NODE). - sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. - } - - // The mapping parameters (for yaml_MAPPING_NODE). - mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. - } - - start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. - -} - -// The document structure. -type yaml_document_t struct { - - // The document nodes. - nodes []yaml_node_t - - // The version directive. - version_directive *yaml_version_directive_t - - // The list of tag directives. - tag_directives_data []yaml_tag_directive_t - tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. - - start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? - - // The start/end of the document. - start_mark, end_mark yaml_mark_t -} - -// The prototype of a read handler. -// -// The read handler is called when the parser needs to read more bytes from the -// source. The handler should write not more than size bytes to the buffer. -// The number of written bytes should be set to the size_read variable. -// -// [in,out] data A pointer to an application data specified by -// yaml_parser_set_input(). -// [out] buffer The buffer to write the data from the source. -// [in] size The size of the buffer. -// [out] size_read The actual number of bytes read from the source. -// -// On success, the handler should return 1. If the handler failed, -// the returned value should be 0. On EOF, the handler should set the -// size_read to 0 and return 1. -type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) - -// This structure holds information about a potential simple key. -type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. -} - -// The states of the parser. -type yaml_parser_state_t int - -const ( - yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. - yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. -) - -func (ps yaml_parser_state_t) String() string { - switch ps { - case yaml_PARSE_STREAM_START_STATE: - return "yaml_PARSE_STREAM_START_STATE" - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_START_STATE: - return "yaml_PARSE_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return "yaml_PARSE_DOCUMENT_CONTENT_STATE" - case yaml_PARSE_DOCUMENT_END_STATE: - return "yaml_PARSE_DOCUMENT_END_STATE" - case yaml_PARSE_BLOCK_NODE_STATE: - return "yaml_PARSE_BLOCK_NODE_STATE" - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" - case yaml_PARSE_FLOW_NODE_STATE: - return "yaml_PARSE_FLOW_NODE_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" - case yaml_PARSE_END_STATE: - return "yaml_PARSE_END_STATE" - } - return "" -} - -// This structure holds aliases data. -type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. -} - -// The parser structure. -// -// All members are internal. Manage the structure using the -// yaml_parser_ family of functions. -type yaml_parser_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - - problem string // Error description. - - // The byte about which the problem occurred. - problem_offset int - problem_value int - problem_mark yaml_mark_t - - // The error context. - context string - context_mark yaml_mark_t - - // Reader stuff - - read_handler yaml_read_handler_t // Read handler. - - input_reader io.Reader // File input data. - input []byte // String input data. - input_pos int - - eof bool // EOF flag - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - unread int // The number of unread characters in the buffer. - - newlines int // The number of line breaks since last non-break/non-blank character - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The input encoding. - - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. - - // Comments - - head_comment []byte // The current head comments - line_comment []byte // The current line comments - foot_comment []byte // The current foot comments - tail_comment []byte // Foot comment that happens at the end of a block. - stem_comment []byte // Comment in item preceding a nested structure (list inside list item, etc) - - comments []yaml_comment_t // The folded comments for all parsed tokens - comments_head int - - // Scanner stuff - - stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? - - flow_level int // The number of unclosed '[' and '{' indicators. - - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. - - indent int // The current indentation level. - indents []int // The indentation levels stack. - - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number - - // Parser stuff - - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. - tag_directives []yaml_tag_directive_t // The list of TAG directives. - - // Dumper stuff - - aliases []yaml_alias_data_t // The alias data. - - document *yaml_document_t // The currently parsed document. -} - -type yaml_comment_t struct { - - scan_mark yaml_mark_t // Position where scanning for comments started - token_mark yaml_mark_t // Position after which tokens will be associated with this comment - start_mark yaml_mark_t // Position of '#' comment mark - end_mark yaml_mark_t // Position where comment terminated - - head []byte - line []byte - foot []byte -} - -// Emitter Definitions - -// The prototype of a write handler. -// -// The write handler is called when the emitter needs to flush the accumulated -// characters to the output. The handler should write @a size bytes of the -// @a buffer to the output. -// -// @param[in,out] data A pointer to an application data specified by -// yaml_emitter_set_output(). -// @param[in] buffer The buffer with bytes to be written. -// @param[in] size The size of the buffer. -// -// @returns On success, the handler should return @c 1. If the handler failed, -// the returned value should be @c 0. -// -type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error - -type yaml_emitter_state_t int - -// The emitter states. -const ( - // Expect STREAM-START. - yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_TRAIL_ITEM_STATE // Expect the next item of a flow sequence, with the comma already written out - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_TRAIL_KEY_STATE // Expect the next key of a flow mapping, with the comma already written out - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. -) - -// The emitter structure. -// -// All members are internal. Manage the structure using the @c yaml_emitter_ -// family of functions. -type yaml_emitter_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - problem string // Error description. - - // Writer stuff - - write_handler yaml_write_handler_t // Write handler. - - output_buffer *[]byte // String output data. - output_writer io.Writer // File output data. - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The stream encoding. - - // Emitter stuff - - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. - - state yaml_emitter_state_t // The current emitter state. - states []yaml_emitter_state_t // The stack of states. - - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. - - indents []int // The stack of indentation levels. - - tag_directives []yaml_tag_directive_t // The list of tag directives. - - indent int // The current indentation level. - - flow_level int // The current flow level. - - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? - simple_key_context bool // Is it a simple mapping key context? - - line int // The current line. - column int // The current column. - whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? - open_ended bool // If an explicit document end is required? - - space_above bool // Is there's an empty line above? - foot_indent int // The indent used to write the foot comment above, or -1 if none. - - // Anchor analysis. - anchor_data struct { - anchor []byte // The anchor value. - alias bool // Is it an alias? - } - - // Tag analysis. - tag_data struct { - handle []byte // The tag handle. - suffix []byte // The tag suffix. - } - - // Scalar analysis. - scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. - } - - // Comments - head_comment []byte - line_comment []byte - foot_comment []byte - tail_comment []byte - - key_line_comment []byte - - // Dumper stuff - - opened bool // If the stream was already opened? - closed bool // If the stream was already closed? - - // The information associated with the document nodes. - anchors *struct { - references int // The number of references. - anchor int // The anchor id. - serialized bool // If the node has been emitted? - } - - last_anchor_id int // The last assigned anchor id. - - document *yaml_document_t // The currently emitted document. -} diff --git a/vendor/gopkg.in/yaml.v3/yamlprivateh.go b/vendor/gopkg.in/yaml.v3/yamlprivateh.go deleted file mode 100644 index e88f9c5..0000000 --- a/vendor/gopkg.in/yaml.v3/yamlprivateh.go +++ /dev/null @@ -1,198 +0,0 @@ -// -// Copyright (c) 2011-2019 Canonical Ltd -// Copyright (c) 2006-2010 Kirill Simonov -// -// 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. - -package yaml - -const ( - // The size of the input raw buffer. - input_raw_buffer_size = 512 - - // The size of the input buffer. - // It should be possible to decode the whole raw buffer. - input_buffer_size = input_raw_buffer_size * 3 - - // The size of the output buffer. - output_buffer_size = 128 - - // The size of the output raw buffer. - // It should be possible to encode the whole output buffer. - output_raw_buffer_size = (output_buffer_size*2 + 2) - - // The size of other stacks and queues. - initial_stack_size = 16 - initial_queue_size = 16 - initial_string_size = 16 -) - -// Check if the character at the specified position is an alphabetical -// character, a digit, '_', or '-'. -func is_alpha(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' -} - -// Check if the character at the specified position is a digit. -func is_digit(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' -} - -// Get the value of a digit. -func as_digit(b []byte, i int) int { - return int(b[i]) - '0' -} - -// Check if the character at the specified position is a hex-digit. -func is_hex(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' -} - -// Get the value of a hex-digit. -func as_hex(b []byte, i int) int { - bi := b[i] - if bi >= 'A' && bi <= 'F' { - return int(bi) - 'A' + 10 - } - if bi >= 'a' && bi <= 'f' { - return int(bi) - 'a' + 10 - } - return int(bi) - '0' -} - -// Check if the character is ASCII. -func is_ascii(b []byte, i int) bool { - return b[i] <= 0x7F -} - -// Check if the character at the start of the buffer can be printed unescaped. -func is_printable(b []byte, i int) bool { - return ((b[i] == 0x0A) || // . == #x0A - (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E - (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF - (b[i] > 0xC2 && b[i] < 0xED) || - (b[i] == 0xED && b[i+1] < 0xA0) || - (b[i] == 0xEE) || - (b[i] == 0xEF && // #xE000 <= . <= #xFFFD - !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF - !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) -} - -// Check if the character at the specified position is NUL. -func is_z(b []byte, i int) bool { - return b[i] == 0x00 -} - -// Check if the beginning of the buffer is a BOM. -func is_bom(b []byte, i int) bool { - return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF -} - -// Check if the character at the specified position is space. -func is_space(b []byte, i int) bool { - return b[i] == ' ' -} - -// Check if the character at the specified position is tab. -func is_tab(b []byte, i int) bool { - return b[i] == '\t' -} - -// Check if the character at the specified position is blank (space or tab). -func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) - return b[i] == ' ' || b[i] == '\t' -} - -// Check if the character at the specified position is a line break. -func is_break(b []byte, i int) bool { - return (b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) -} - -func is_crlf(b []byte, i int) bool { - return b[i] == '\r' && b[i+1] == '\n' -} - -// Check if the character is a line break or NUL. -func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) - return ( - // is_break: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - // is_z: - b[i] == 0) -} - -// Check if the character is a line break, space, or NUL. -func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) - return ( - // is_space: - b[i] == ' ' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Check if the character is a line break, space, tab, or NUL. -func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) - return ( - // is_blank: - b[i] == ' ' || b[i] == '\t' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Determine the width of the character. -func width(b byte) int { - // Don't replace these by a switch without first - // confirming that it is being inlined. - if b&0x80 == 0x00 { - return 1 - } - if b&0xE0 == 0xC0 { - return 2 - } - if b&0xF0 == 0xE0 { - return 3 - } - if b&0xF8 == 0xF0 { - return 4 - } - return 0 - -} diff --git a/vendor/modules.txt b/vendor/modules.txt deleted file mode 100644 index 0303278..0000000 --- a/vendor/modules.txt +++ /dev/null @@ -1,90 +0,0 @@ -# github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d -## explicit; go 1.13 -github.com/asaskevich/govalidator -# github.com/davecgh/go-spew v1.1.1 -## explicit -github.com/davecgh/go-spew/spew -# github.com/go-playground/locales v0.14.0 -## explicit; go 1.13 -github.com/go-playground/locales -github.com/go-playground/locales/currency -# github.com/go-playground/universal-translator v0.18.0 -## explicit; go 1.13 -github.com/go-playground/universal-translator -# github.com/go-playground/validator/v10 v10.11.1 -## explicit; go 1.13 -github.com/go-playground/validator/v10 -# github.com/inconshreveable/mousetrap v1.1.0 -## explicit; go 1.18 -github.com/inconshreveable/mousetrap -# github.com/leodido/go-urn v1.2.1 -## explicit; go 1.13 -github.com/leodido/go-urn -# github.com/pmezard/go-difflib v1.0.0 -## explicit -github.com/pmezard/go-difflib/difflib -# github.com/rsteube/carapace v0.30.0 => github.com/reeflective/carapace v0.25.2-0.20230416191807-fc9b8c3aa6f6 -## explicit; go 1.15 -github.com/rsteube/carapace -github.com/rsteube/carapace/internal/cache -github.com/rsteube/carapace/internal/common -github.com/rsteube/carapace/internal/config -github.com/rsteube/carapace/internal/export -github.com/rsteube/carapace/internal/man -github.com/rsteube/carapace/internal/pflagfork -github.com/rsteube/carapace/internal/shell -github.com/rsteube/carapace/internal/shell/bash -github.com/rsteube/carapace/internal/shell/bash_ble -github.com/rsteube/carapace/internal/shell/elvish -github.com/rsteube/carapace/internal/shell/export -github.com/rsteube/carapace/internal/shell/fish -github.com/rsteube/carapace/internal/shell/ion -github.com/rsteube/carapace/internal/shell/nushell -github.com/rsteube/carapace/internal/shell/oil -github.com/rsteube/carapace/internal/shell/powershell -github.com/rsteube/carapace/internal/shell/spec -github.com/rsteube/carapace/internal/shell/tcsh -github.com/rsteube/carapace/internal/shell/xonsh -github.com/rsteube/carapace/internal/shell/zsh -github.com/rsteube/carapace/internal/uid -github.com/rsteube/carapace/pkg/cache -github.com/rsteube/carapace/pkg/ps -github.com/rsteube/carapace/pkg/style -github.com/rsteube/carapace/pkg/xdg -github.com/rsteube/carapace/third_party/github.com/acarl005/stripansi -github.com/rsteube/carapace/third_party/github.com/drone/envsubst -github.com/rsteube/carapace/third_party/github.com/drone/envsubst/parse -github.com/rsteube/carapace/third_party/github.com/drone/envsubst/path -github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/cli/lscolors -github.com/rsteube/carapace/third_party/github.com/elves/elvish/pkg/ui -github.com/rsteube/carapace/third_party/github.com/mitchellh/go-ps -github.com/rsteube/carapace/third_party/golang.org/x/sys/execabs -# github.com/rsteube/carapace-bin v0.19.0 -## explicit; go 1.19 -github.com/rsteube/carapace-bin/pkg/actions/net -github.com/rsteube/carapace-bin/pkg/actions/number -# github.com/spf13/cobra v1.7.0 -## explicit; go 1.15 -github.com/spf13/cobra -# github.com/spf13/pflag v1.0.5 -## explicit; go 1.12 -github.com/spf13/pflag -# github.com/stretchr/testify v1.8.0 -## explicit; go 1.13 -github.com/stretchr/testify/assert -github.com/stretchr/testify/require -# golang.org/x/crypto v0.3.0 -## explicit; go 1.17 -golang.org/x/crypto/sha3 -# golang.org/x/sys v0.2.0 -## explicit; go 1.17 -golang.org/x/sys/cpu -# golang.org/x/text v0.4.0 -## explicit; go 1.17 -golang.org/x/text/internal/language -golang.org/x/text/internal/language/compact -golang.org/x/text/internal/tag -golang.org/x/text/language -# gopkg.in/yaml.v3 v3.0.1 -## explicit -gopkg.in/yaml.v3