diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..442087c --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +version: 2 +updates: + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ade399f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,33 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + branches: [master] + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Build + run: go build ./... + + - name: Lint + uses: golangci/golangci-lint-action@v7 + with: + version: v2.11 + + - name: Check module tidiness + run: | + go mod tidy + git diff --exit-code go.mod go.sum diff --git a/.gitignore b/.gitignore index 6c50c96..f5d42d0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ build/ +vendor/ .idea/ .vscode/ .DS_Store diff --git a/go.mod b/go.mod index f593a68..5f50e38 100644 --- a/go.mod +++ b/go.mod @@ -6,7 +6,7 @@ toolchain go1.23.4 require ( github.com/alecthomas/kong v1.11.0 - github.com/anduril/lattice-sdk-go/v2 v2.2.0 + github.com/anduril/lattice-sdk-go/v4 v4.5.0 ) require ( diff --git a/go.sum b/go.sum index 5f79dfb..ad74332 100644 --- a/go.sum +++ b/go.sum @@ -4,8 +4,8 @@ github.com/alecthomas/kong v1.11.0 h1:y++1gI7jf8O7G7l4LZo5ASFhrhJvzc+WgF/arranEm github.com/alecthomas/kong v1.11.0/go.mod h1:p2vqieVMeTAnaC83txKtXe8FLke2X07aruPWXyMPQrU= github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc= github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= -github.com/anduril/lattice-sdk-go/v2 v2.2.0 h1:7qEveGHtCoKd81of9PjPkNMLMCVMXMiJKwSVvavQIrY= -github.com/anduril/lattice-sdk-go/v2 v2.2.0/go.mod h1:LZXFUrBP6Zuq+IhNpqN1tiaMuC2WayvxlGVO+ApesKo= +github.com/anduril/lattice-sdk-go/v4 v4.5.0 h1:miiQk94+fRa5ZqokWy4uZL533/4qDGxbMOXYS262E4k= +github.com/anduril/lattice-sdk-go/v4 v4.5.0/go.mod h1:bGvU1erf9umZBBtdWyJn2mGtHPCx5g4mub97naVrOmM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= diff --git a/internal/cli/cli.go b/internal/cli/cli.go index fbca0e6..cdde387 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -12,9 +12,9 @@ import ( "time" "github.com/alecthomas/kong" - api "github.com/anduril/lattice-sdk-go/v2" - client "github.com/anduril/lattice-sdk-go/v2/client" - option "github.com/anduril/lattice-sdk-go/v2/option" + api "github.com/anduril/lattice-sdk-go/v4" + client "github.com/anduril/lattice-sdk-go/v4/client" + option "github.com/anduril/lattice-sdk-go/v4/option" ) type cli struct { @@ -36,7 +36,7 @@ func (d *deleteCmd) Run(kongCtx *kong.Context) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - if err := objectStoreClient.Objects.DeleteObject(ctx, d.Path); err != nil { + if err := objectStoreClient.Objects.DeleteObject(ctx, &api.DeleteObjectRequest{ObjectPath: d.Path}); err != nil { return fmt.Errorf("unable to delete path %q: %w", d.Path, err) } fmt.Printf("deleted path %q\n", d.Path) @@ -77,7 +77,7 @@ func (u *uploadCmd) Run(kongCtx *kong.Context) error { if err != nil { return fmt.Errorf("unable to open file %q: %w", u.InputPath, err) } - defer fileReader.Close() + defer func() { _ = fileReader.Close() }() fileBytes, err := io.ReadAll(fileReader) if err != nil { @@ -107,7 +107,7 @@ func (o *objectMetadataCmd) Run(kongCtx *kong.Context) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - header, err := objectStoreClient.Objects.WithRawResponse.GetObjectMetadata(ctx, o.Path) + header, err := objectStoreClient.Objects.WithRawResponse.GetObjectMetadata(ctx, &api.GetObjectMetadataRequest{ObjectPath: o.Path}) if err != nil { return fmt.Errorf("unable to get object metadata for path %q, err=%w", o.Path, err) } @@ -132,8 +132,7 @@ func (o *getCmd) Run(kongCtx *kong.Context) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - request := &api.GetObjectRequest{} - objectReader, err := objectStoreClient.Objects.GetObject(ctx, o.ObjectStorePath, request) + objectReader, err := objectStoreClient.Objects.GetObject(ctx, &api.GetObjectRequest{ObjectPath: o.ObjectStorePath}) if err != nil { return fmt.Errorf("unable to get file %q from object store: %w", o.ObjectStorePath, err) } @@ -142,7 +141,7 @@ func (o *getCmd) Run(kongCtx *kong.Context) error { if err != nil { return fmt.Errorf("unable to create writer for %q: %w", o.OutputPath, err) } - defer outputWriter.Close() + defer func() { _ = outputWriter.Close() }() bytesCopied, err := io.Copy(outputWriter, objectReader) if err != nil { diff --git a/vendor/github.com/alecthomas/kong/.gitignore b/vendor/github.com/alecthomas/kong/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/github.com/alecthomas/kong/.golangci.yml b/vendor/github.com/alecthomas/kong/.golangci.yml deleted file mode 100644 index 1eb0b92..0000000 --- a/vendor/github.com/alecthomas/kong/.golangci.yml +++ /dev/null @@ -1,85 +0,0 @@ -run: - tests: true - -output: - print-issued-lines: false - -linters: - enable-all: true - disable: - - lll - - gochecknoglobals - - wsl - - funlen - - gocognit - - goprintffuncname - - paralleltest - - nlreturn - - testpackage - - wrapcheck - - forbidigo - - gci - - godot - - gofumpt - - cyclop - - errorlint - - nestif - - tagliatelle - - thelper - - godox - - goconst - - varnamelen - - ireturn - - exhaustruct - - nonamedreturns - - nilnil - - depguard # nothing to guard against yet - - tagalign # hurts readability of kong tags - - tenv # deprecated since v1.64, but not removed yet - - mnd - - perfsprint - - err113 - - copyloopvar - - intrange - - nakedret - - recvcheck # value receivers are intentionally used for copies - -linters-settings: - govet: - # These govet checks are disabled by default, but they're useful. - enable: - - niliness - - sortslice - - unusedwrite - dupl: - threshold: 100 - gocyclo: - min-complexity: 20 - exhaustive: - default-signifies-exhaustive: true - -issues: - max-per-linter: 0 - max-same: 0 - exclude-use-default: false - exclude: - - '^(G104|G204):' - # Very commonly not checked. - - 'Error return value of .(.*\.Help|.*\.MarkFlagRequired|(os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked' - - 'exported method (.*\.MarshalJSON|.*\.UnmarshalJSON) should have comment or be unexported' - - 'composite literal uses unkeyed fields' - - 'bad syntax for struct tag key' - - 'bad syntax for struct tag pair' - - 'result .* \(error\) is always nil' - - 'Error return value of `fmt.Fprintln` is not checked' - - exclude-rules: - # Don't warn on unused parameters. - # Parameter names are useful for documentation. - # Replacing them with '_' hides useful information. - - linters: [revive] - text: 'unused-parameter: parameter \S+ seems to be unused, consider removing or renaming it as _' - - # Duplicate words are okay in tests. - - linters: [dupword] - path: _test\.go diff --git a/vendor/github.com/alecthomas/kong/COPYING b/vendor/github.com/alecthomas/kong/COPYING deleted file mode 100644 index 22707ac..0000000 --- a/vendor/github.com/alecthomas/kong/COPYING +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2018 Alec Thomas - -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/alecthomas/kong/README.md b/vendor/github.com/alecthomas/kong/README.md deleted file mode 100644 index a976332..0000000 --- a/vendor/github.com/alecthomas/kong/README.md +++ /dev/null @@ -1,775 +0,0 @@ - -

- -# Kong is a command-line parser for Go - -[![](https://godoc.org/github.com/alecthomas/kong?status.svg)](http://godoc.org/github.com/alecthomas/kong) [![CircleCI](https://img.shields.io/circleci/project/github/alecthomas/kong.svg)](https://circleci.com/gh/alecthomas/kong) [![Go Report Card](https://goreportcard.com/badge/github.com/alecthomas/kong)](https://goreportcard.com/report/github.com/alecthomas/kong) [![Slack chat](https://img.shields.io/static/v1?logo=slack&style=flat&label=slack&color=green&message=gophers)](https://gophers.slack.com/messages/CN9DS8YF3) - -- [Version 1.0.0 Release](#version-100-release) -- [Introduction](#introduction) -- [Help](#help) - - [Help as a user of a Kong application](#help-as-a-user-of-a-kong-application) - - [Defining help in Kong](#defining-help-in-kong) -- [Command handling](#command-handling) - - [Switch on the command string](#switch-on-the-command-string) - - [Attach a `Run(...) error` method to each command](#attach-a-run-error-method-to-each-command) -- [Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply()](#hooks-beforereset-beforeresolve-beforeapply-afterapply) -- [The Bind() option](#the-bind-option) -- [Flags](#flags) -- [Commands and sub-commands](#commands-and-sub-commands) -- [Branching positional arguments](#branching-positional-arguments) -- [Positional arguments](#positional-arguments) -- [Slices](#slices) -- [Maps](#maps) -- [Pointers](#pointers) -- [Nested data structure](#nested-data-structure) -- [Custom named decoders](#custom-named-decoders) -- [Supported field types](#supported-field-types) -- [Custom decoders (mappers)](#custom-decoders-mappers) -- [Supported tags](#supported-tags) -- [Plugins](#plugins) -- [Dynamic Commands](#dynamic-commands) -- [Variable interpolation](#variable-interpolation) -- [Validation](#validation) -- [Modifying Kong's behaviour](#modifying-kongs-behaviour) - - [`Name(help)` and `Description(help)` - set the application name description](#namehelp-and-descriptionhelp---set-the-application-name-description) - - [`Configuration(loader, paths...)` - load defaults from configuration files](#configurationloader-paths---load-defaults-from-configuration-files) - - [`Resolver(...)` - support for default values from external sources](#resolver---support-for-default-values-from-external-sources) - - [`*Mapper(...)` - customising how the command-line is mapped to Go values](#mapper---customising-how-the-command-line-is-mapped-to-go-values) - - [`ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help](#configurehelphelpoptions-and-helphelpfunc---customising-help) - - [Injecting values into `Run()` methods](#injecting-values-into-run-methods) - - [Other options](#other-options) - -## Version 1.0.0 Release - -Kong has been stable for a long time, so it seemed appropriate to cut a 1.0 release. - -There is one breaking change, [#436](https://github.com/alecthomas/kong/pull/436), which should effect relatively few users. - -## Introduction - -Kong aims to support arbitrarily complex command-line structures with as little developer effort as possible. - -To achieve that, command-lines are expressed as Go types, with the structure and tags directing how the command line is mapped onto the struct. - -For example, the following command-line: - - shell rm [-f] [-r] ... - shell ls [ ...] - -Can be represented by the following command-line structure: - -```go -package main - -import "github.com/alecthomas/kong" - -var CLI struct { - Rm struct { - Force bool `help:"Force removal."` - Recursive bool `help:"Recursively remove files."` - - Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"` - } `cmd:"" help:"Remove files."` - - Ls struct { - Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"` - } `cmd:"" help:"List paths."` -} - -func main() { - ctx := kong.Parse(&CLI) - switch ctx.Command() { - case "rm ": - case "ls": - default: - panic(ctx.Command()) - } -} -``` - -## Help - -### Help as a user of a Kong application - -Every Kong application includes a `--help` flag that will display auto-generated help. - -eg. - - $ shell --help - usage: shell - - A shell-like example app. - - Flags: - --help Show context-sensitive help. - --debug Debug mode. - - Commands: - rm ... - Remove files. - - ls [ ...] - List paths. - -If a command is provided, the help will show full detail on the command including all available flags. - -eg. - - $ shell --help rm - usage: shell rm ... - - Remove files. - - Arguments: - ... Paths to remove. - - Flags: - --debug Debug mode. - - -f, --force Force removal. - -r, --recursive Recursively remove files. - -### Defining help in Kong - -Help is automatically generated from the command-line structure itself, -including `help:""` and other tags. [Variables](#variable-interpolation) will -also be interpolated into the help string. - -Finally, any command, or argument type implementing the interface -`Help() string` will have this function called to retrieve more detail to -augment the help tag. This allows for much more descriptive text than can -fit in Go tags. [See \_examples/shell/help](./_examples/shell/help) - -#### Showing the _command_'s detailed help - -A command's additional help text is _not_ shown from top-level help, but can be displayed within contextual help: - -**Top level help** - -```bash - $ go run ./_examples/shell/help --help -Usage: help - -An app demonstrating HelpProviders - -Flags: - -h, --help Show context-sensitive help. - --flag Regular flag help - -Commands: - echo Regular command help -``` - -**Contextual** - -```bash - $ go run ./_examples/shell/help echo --help -Usage: help echo - -Regular command help - -🚀 additional command help - -Arguments: - Regular argument help - -Flags: - -h, --help Show context-sensitive help. - --flag Regular flag help -``` - -#### Showing an _argument_'s detailed help - -Custom help will only be shown for _positional arguments with named fields_ ([see the README section on positional arguments for more details on what that means](#branching-positional-arguments)) - -**Contextual argument help** - -```bash - $ go run ./_examples/shell/help msg --help -Usage: help echo - -Regular argument help - -📣 additional argument help - -Flags: - -h, --help Show context-sensitive help. - --flag Regular flag help -``` - -## Command handling - -There are two ways to handle commands in Kong. - -### Switch on the command string - -When you call `kong.Parse()` it will return a unique string representation of the command. Each command branch in the hierarchy will be a bare word and each branching argument or required positional argument will be the name surrounded by angle brackets. Here's an example: - -There's an example of this pattern [here](https://github.com/alecthomas/kong/blob/master/_examples/shell/commandstring/main.go). - -eg. - -```go -package main - -import "github.com/alecthomas/kong" - -var CLI struct { - Rm struct { - Force bool `help:"Force removal."` - Recursive bool `help:"Recursively remove files."` - - Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"` - } `cmd:"" help:"Remove files."` - - Ls struct { - Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"` - } `cmd:"" help:"List paths."` -} - -func main() { - ctx := kong.Parse(&CLI) - switch ctx.Command() { - case "rm ": - case "ls": - default: - panic(ctx.Command()) - } -} -``` - -This has the advantage that it is convenient, but the downside that if you modify your CLI structure, the strings may change. This can be fragile. - -### Attach a `Run(...) error` method to each command - -A more robust approach is to break each command out into their own structs: - -1. Break leaf commands out into separate structs. -2. Attach a `Run(...) error` method to all leaf commands. -3. Call `kong.Kong.Parse()` to obtain a `kong.Context`. -4. Call `kong.Context.Run(bindings...)` to call the selected parsed command. - -Once a command node is selected by Kong it will search from that node back to the root. Each -encountered command node with a `Run(...) error` will be called in reverse order. This allows -sub-trees to be re-used fairly conveniently. - -In addition to values bound with the `kong.Bind(...)` option, any values -passed through to `kong.Context.Run(...)` are also bindable to the target's -`Run()` arguments. - -Finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`. - -There's a full example emulating part of the Docker CLI [here](https://github.com/alecthomas/kong/tree/master/_examples/docker). - -eg. - -```go -type Context struct { - Debug bool -} - -type RmCmd struct { - Force bool `help:"Force removal."` - Recursive bool `help:"Recursively remove files."` - - Paths []string `arg:"" name:"path" help:"Paths to remove." type:"path"` -} - -func (r *RmCmd) Run(ctx *Context) error { - fmt.Println("rm", r.Paths) - return nil -} - -type LsCmd struct { - Paths []string `arg:"" optional:"" name:"path" help:"Paths to list." type:"path"` -} - -func (l *LsCmd) Run(ctx *Context) error { - fmt.Println("ls", l.Paths) - return nil -} - -var cli struct { - Debug bool `help:"Enable debug mode."` - - Rm RmCmd `cmd:"" help:"Remove files."` - Ls LsCmd `cmd:"" help:"List paths."` -} - -func main() { - ctx := kong.Parse(&cli) - // Call the Run() method of the selected parsed command. - err := ctx.Run(&Context{Debug: cli.Debug}) - ctx.FatalIfErrorf(err) -} - -``` - -## Hooks: BeforeReset(), BeforeResolve(), BeforeApply(), AfterApply() - -If a node in the CLI, or any of its embedded fields, implements a `BeforeReset(...) error`, `BeforeResolve -(...) error`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those will be called as Kong -resets, resolves, validates, and assigns values to the node. - -| Hook | Description | -| --------------- | ----------------------------------------------------------------------------------------------------------- | -| `BeforeReset` | Invoked before values are reset to their defaults (as defined by the grammar) or to zero values | -| `BeforeResolve` | Invoked before resolvers are applied to a node | -| `BeforeApply` | Invoked before the traced command line arguments are applied to the grammar | -| `AfterApply` | Invoked after command line arguments are applied to the grammar **and validated**` | - -The `--help` flag is implemented with a `BeforeReset` hook. - -eg. - -```go -// A flag with a hook that, if triggered, will set the debug loggers output to stdout. -type debugFlag bool - -func (d debugFlag) BeforeApply(logger *log.Logger) error { - logger.SetOutput(os.Stdout) - return nil -} - -var cli struct { - Debug debugFlag `help:"Enable debug logging."` -} - -func main() { - // Debug logger going to discard. - logger := log.New(io.Discard, "", log.LstdFlags) - - ctx := kong.Parse(&cli, kong.Bind(logger)) - - // ... -} -``` - -It's also possible to register these hooks with the functional options -`kong.WithBeforeReset`, `kong.WithBeforeResolve`, `kong.WithBeforeApply`, and -`kong.WithAfterApply`. - -## The Bind() option - -Arguments to hooks are provided via the `Run(...)` method or `Bind(...)` option. `*Kong`, `*Context`, `*Path` and parent commands are also bound and finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`. - -eg: - -```go -type CLI struct { - Debug bool `help:"Enable debug mode."` - - Rm RmCmd `cmd:"" help:"Remove files."` - Ls LsCmd `cmd:"" help:"List paths."` -} - -type AuthorName string - -// ... -func (l *LsCmd) Run(cli *CLI) error { -// use cli.Debug here !! - return nil -} - -func (r *RmCmD) Run(author AuthorName) error{ -// use binded author here - return nil -} - -func main() { - var cli CLI - - ctx := kong.Parse(&cli, Bind(AuthorName("penguin"))) - err := ctx.Run() -``` - -## Flags - -Any [mapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) field in the command structure _not_ tagged with `cmd` or `arg` will be a flag. Flags are optional by default. - -eg. The command-line `app [--flag="foo"]` can be represented by the following. - -```go -type CLI struct { - Flag string -} -``` - -## Commands and sub-commands - -Sub-commands are specified by tagging a struct field with `cmd`. Kong supports arbitrarily nested commands. - -eg. The following struct represents the CLI structure `command [--flag="str"] sub-command`. - -```go -type CLI struct { - Command struct { - Flag string - - SubCommand struct { - } `cmd` - } `cmd` -} -``` - -If a sub-command is tagged with `default:"1"` it will be selected if there are no further arguments. If a sub-command is tagged with `default:"withargs"` it will be selected even if there are further arguments or flags and those arguments or flags are valid for the sub-command. This allows the user to omit the sub-command name on the CLI if its arguments/flags are not ambiguous with the sibling commands or flags. - -## Branching positional arguments - -In addition to sub-commands, structs can also be configured as branching positional arguments. - -This is achieved by tagging an [unmapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) nested struct field with `arg`, then including a positional argument field inside that struct _with the same name_. For example, the following command structure: - - app rename to - -Can be represented with the following: - -```go -var CLI struct { - Rename struct { - Name struct { - Name string `arg` // <-- NOTE: identical name to enclosing struct field. - To struct { - Name struct { - Name string `arg` - } `arg` - } `cmd` - } `arg` - } `cmd` -} -``` - -This looks a little verbose in this contrived example, but typically this will not be the case. - -## Positional arguments - -If a field is tagged with `arg:""` it will be treated as the final positional -value to be parsed on the command line. By default positional arguments are -required, but specifying `optional:""` will alter this. - -If a positional argument is a slice, all remaining arguments will be appended -to that slice. - -## Slices - -Slice values are treated specially. First the input is split on the `sep:""` tag (defaults to `,`), then each element is parsed by the slice element type and appended to the slice. If the same value is encountered multiple times, elements continue to be appended. - -To represent the following command-line: - - cmd ls ... - -You would use the following: - -```go -var CLI struct { - Ls struct { - Files []string `arg:"" type:"existingfile"` - } `cmd` -} -``` - -## Maps - -Maps are similar to slices except that only one key/value pair can be assigned per value, and the `sep` tag denotes the assignment character and defaults to `=`. - -To represent the following command-line: - - cmd config set = = ... - -You would use the following: - -```go -var CLI struct { - Config struct { - Set struct { - Config map[string]float64 `arg:"" type:"file:"` - } `cmd` - } `cmd` -} -``` - -For flags, multiple key+value pairs should be separated by `mapsep:"rune"` tag (defaults to `;`) eg. `--set="key1=value1;key2=value2"`. - -## Pointers - -Pointers work like the underlying type, except that you can differentiate between the presence of the zero value and no value being supplied. - -For example: - -```go -var CLI struct { - Foo *int -} -``` - -Would produce a nil value for `Foo` if no `--foo` argument is supplied, but would have a pointer to the value 0 if the argument `--foo=0` was supplied. - -## Nested data structure - -Kong support a nested data structure as well with `embed:""`. You can combine `embed:""` with `prefix:""`: - -```go -var CLI struct { - Logging struct { - Level string `enum:"debug,info,warn,error" default:"info"` - Type string `enum:"json,console" default:"console"` - } `embed:"" prefix:"logging."` -} -``` - -This configures Kong to accept flags `--logging.level` and `--logging.type`. - -## Custom named decoders - -Kong includes a number of builtin custom type mappers. These can be used by -specifying the tag `type:""`. They are registered with the option -function `NamedMapper(name, mapper)`. - -| Name | Description | -| -------------- | ---------------------------------------------------------------------------------------------------------------------- | -| `path` | A path. ~ expansion is applied. `-` is accepted for stdout, and will be passed unaltered. | -| `existingfile` | An existing file. ~ expansion is applied. `-` is accepted for stdin, and will be passed unaltered. | -| `existingdir` | An existing directory. ~ expansion is applied. | -| `counter` | Increment a numeric field. Useful for `-vvv`. Can accept `-s`, `--long` or `--long=N`. | -| `filecontent` | Read the file at path into the field. ~ expansion is applied. `-` is accepted for stdin, and will be passed unaltered. | - -Slices and maps treat type tags specially. For slices, the `type:""` tag -specifies the element type. For maps, the tag has the format -`tag:"[]:[]"` where either may be omitted. - -## Supported field types - -## Custom decoders (mappers) - -Any field implementing `encoding.TextUnmarshaler` or `json.Unmarshaler` will use those interfaces -for decoding values. Kong also includes builtin support for many common Go types: - -| Type | Description | -| --------------- | ----------------------------------------------------------------------------------------------------------- | -| `time.Duration` | Populated using `time.ParseDuration()`. | -| `time.Time` | Populated using `time.Parse()`. Format defaults to RFC3339 but can be overridden with the `format:"X"` tag. | -| `*os.File` | Path to a file that will be opened, or `-` for `os.Stdin`. File must be closed by the user. | -| `*url.URL` | Populated with `url.Parse()`. | - -For more fine-grained control, if a field implements the -[MapperValue](https://godoc.org/github.com/alecthomas/kong#MapperValue) -interface it will be used to decode arguments into the field. - -## Supported tags - -Tags can be in two forms: - -1. Standard Go syntax, eg. `kong:"required,name='foo'"`. -2. Bare tags, eg. `required:"" name:"foo"` - -Both can coexist with standard Tag parsing. - -| Tag | Description | -| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `cmd:""` | If present, struct is a command. | -| `arg:""` | If present, field is an argument. Required by default. | -| `env:"X,Y,..."` | Specify envars to use for default value. The envs are resolved in the declared order. The first value found is used. | -| `name:"X"` | Long name, for overriding field name. | -| `help:"X"` | Help text. | -| `type:"X"` | Specify [named types](#custom-named-decoders) to use. | -| `placeholder:"X"` | Placeholder input, if flag. e.g. `` `placeholder:""` `` will show `--flag-name=` when displaying help. | -| `default:"X"` | Default value. | -| `default:"1"` | On a command, make it the default. | -| `default:"withargs"` | On a command, make it the default and allow args/flags from that command | -| `short:"X"` | Short name, if flag. | -| `aliases:"X,Y"` | One or more aliases (for cmd or flag). | -| `required:""` | If present, flag/arg is required. | -| `optional:""` | If present, flag/arg is optional. | -| `hidden:""` | If present, command or flag is hidden. | -| `negatable:""` | If present on a `bool` field, supports prefixing a flag with `--no-` to invert the default value | -| `negatable:"X"` | If present on a `bool` field, supports `--X` to invert the default value | -| `format:"X"` | Format for parsing input, if supported. | -| `sep:"X"` | Separator for sequences (defaults to ","). May be `none` to disable splitting. | -| `mapsep:"X"` | Separator for maps (defaults to ";"). May be `none` to disable splitting. | -| `enum:"X,Y,..."` | Set of valid values allowed for this flag. An enum field must be `required` or have a valid `default`. | -| `group:"X"` | Logical group for a flag or command. | -| `xor:"X,Y,..."` | Exclusive OR groups for flags. Only one flag in the group can be used which is restricted within the same command. When combined with `required`, at least one of the `xor` group will be required. | -| `and:"X,Y,..."` | AND groups for flags. All flags in the group must be used in the same command. When combined with `required`, all flags in the group will be required. | -| `prefix:"X"` | Prefix for all sub-flags. | -| `envprefix:"X"` | Envar prefix for all sub-flags. | -| `xorprefix:"X"` | Prefix for all sub-flags in XOR/AND groups. | -| `set:"K=V"` | Set a variable for expansion by child elements. Multiples can occur. | -| `embed:""` | If present, this field's children will be embedded in the parent. Useful for composition. | -| `passthrough:""`[^1] | If present on a positional argument, it stops flag parsing when encountered, as if `--` was processed before. Useful for external command wrappers, like `exec`. On a command it requires that the command contains only one argument of type `[]string` which is then filled with everything following the command, unparsed. | -| `-` | Ignore the field. Useful for adding non-CLI fields to a configuration struct. e.g `` `kong:"-"` `` | - -[^1]: `` can be `partial` or `all` (the default). `all` will pass through all arguments including flags, including -flags. `partial` will validate flags until the first positional argument is encountered, then pass through all remaining -positional arguments. - -## Plugins - -Kong CLI's can be extended by embedding the `kong.Plugin` type and populating it with pointers to Kong annotated structs. For example: - -```go -var pluginOne struct { - PluginOneFlag string -} -var pluginTwo struct { - PluginTwoFlag string -} -var cli struct { - BaseFlag string - kong.Plugins -} -cli.Plugins = kong.Plugins{&pluginOne, &pluginTwo} -``` - -Additionally if an interface type is embedded, it can also be populated with a Kong annotated struct. - -## Dynamic Commands - -While plugins give complete control over extending command-line interfaces, Kong -also supports dynamically adding commands via `kong.DynamicCommand()`. - -## Variable interpolation - -Kong supports limited variable interpolation into help strings, placeholder strings, -enum lists and default values. - -Variables are in the form: - - ${} - ${=} - -Variables are set with the `Vars{"key": "value", ...}` option. Undefined -variable references in the grammar without a default will result in an error at -construction time. - -Variables can also be set via the `set:"K=V"` tag. In this case, those variables will be available for that -node and all children. This is useful for composition by allowing the same struct to be reused. - -When interpolating into flag or argument help strings, some extra variables -are defined from the value itself: - - ${default} - ${enum} - -For flags with associated environment variables, the variable `${env}` can be -interpolated into the help string. In the absence of this variable in the -help string, Kong will append `($$${env})` to the help string. - -eg. - -```go -type cli struct { - Config string `type:"path" default:"${config_file}"` -} - -func main() { - kong.Parse(&cli, - kong.Vars{ - "config_file": "~/.app.conf", - }) -} -``` - -## Validation - -Kong does validation on the structure of a command-line, but also supports -extensible validation. Any node in the tree may implement either of the following interfaces: - -```go -type Validatable interface { - Validate() error - } -``` - -```go -type Validatable interface { - Validate(kctx *kong.Context) error - } -``` - -If one of these nodes is in the active command-line it will be called during -normal validation. - -## Modifying Kong's behaviour - -Each Kong parser can be configured via functional options passed to `New(cli any, options...Option)`. - -The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option). - -### `Name(help)` and `Description(help)` - set the application name description - -Set the application name and/or description. - -The name of the application will default to the binary name, but can be overridden with `Name(name)`. - -As with all help in Kong, text will be wrapped to the terminal. - -### `Configuration(loader, paths...)` - load defaults from configuration files - -This option provides Kong with support for loading defaults from a set of configuration files. Each file is opened, if possible, and the loader called to create a resolver for that file. - -eg. - -```go -kong.Parse(&cli, kong.Configuration(kong.JSON, "/etc/myapp.json", "~/.myapp.json")) -``` - -[See the tests](https://github.com/alecthomas/kong/blob/master/resolver_test.go#L206) for an example of how the JSON file is structured. - -#### List of Configuration Loaders - -- [YAML](https://github.com/alecthomas/kong-yaml) -- [HCL](https://github.com/alecthomas/kong-hcl) -- [TOML](https://github.com/alecthomas/kong-toml) -- [JSON](https://github.com/alecthomas/kong) - -### `Resolver(...)` - support for default values from external sources - -Resolvers are Kong's extension point for providing default values from external sources. As an example, support for environment variables via the `env` tag is provided by a resolver. There's also a builtin resolver for JSON configuration files. - -Example resolvers can be found in [resolver.go](https://github.com/alecthomas/kong/blob/master/resolver.go). - -### `*Mapper(...)` - customising how the command-line is mapped to Go values - -Command-line arguments are mapped to Go values via the Mapper interface: - -```go -// A Mapper represents how a field is mapped from command-line values to Go. -// -// Mappers can be associated with concrete fields via pointer, reflect.Type, reflect.Kind, or via a "type" tag. -// -// Additionally, if a type implements the MapperValue interface, it will be used. -type Mapper interface { - // Decode ctx.Value with ctx.Scanner into target. - Decode(ctx *DecodeContext, target reflect.Value) error -} -``` - -All builtin Go types (as well as a bunch of useful stdlib types like `time.Time`) have mappers registered by default. Mappers for custom types can be added using `kong.??Mapper(...)` options. Mappers are applied to fields in four ways: - -1. `NamedMapper(string, Mapper)` and using the tag key `type:""`. -2. `KindMapper(reflect.Kind, Mapper)`. -3. `TypeMapper(reflect.Type, Mapper)`. -4. `ValueMapper(any, Mapper)`, passing in a pointer to a field of the grammar. - -### `ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help - -The default help output is usually sufficient, but if not there are two solutions. - -1. Use `ConfigureHelp(HelpOptions)` to configure how help is formatted (see [HelpOptions](https://godoc.org/github.com/alecthomas/kong#HelpOptions) for details). -2. Custom help can be wired into Kong via the `Help(HelpFunc)` option. The `HelpFunc` is passed a `Context`, which contains the parsed context for the current command-line. See the implementation of `DefaultHelpPrinter` for an example. -3. Use `ValueFormatter(HelpValueFormatter)` if you want to just customize the help text that is accompanied by flags and arguments. -4. Use `Groups([]Group)` if you want to customize group titles or add a header. - -### Injecting values into `Run()` methods - -There are several ways to inject values into `Run()` methods: - -1. Use `Bind()` to bind values directly. -2. Use `BindTo()` to bind values to an interface type. -3. Use `BindToProvider()` to bind values to a function that provides the value. -4. Implement `Provide() error` methods on the command structure. - -### Other options - -The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option). diff --git a/vendor/github.com/alecthomas/kong/build.go b/vendor/github.com/alecthomas/kong/build.go deleted file mode 100644 index 63afcd4..0000000 --- a/vendor/github.com/alecthomas/kong/build.go +++ /dev/null @@ -1,411 +0,0 @@ -package kong - -import ( - "fmt" - "reflect" - "strings" -) - -// Plugins are dynamically embedded command-line structures. -// -// Each element in the Plugins list *must* be a pointer to a structure. -type Plugins []any - -func build(k *Kong, ast any) (app *Application, err error) { - v := reflect.ValueOf(ast) - iv := reflect.Indirect(v) - if v.Kind() != reflect.Ptr || iv.Kind() != reflect.Struct { - return nil, fmt.Errorf("expected a pointer to a struct but got %T", ast) - } - - app = &Application{} - extraFlags := k.extraFlags() - seenFlags := map[string]bool{} - for _, flag := range extraFlags { - seenFlags[flag.Name] = true - } - - node, err := buildNode(k, iv, ApplicationNode, newEmptyTag(), seenFlags) - if err != nil { - return nil, err - } - if len(node.Positional) > 0 && len(node.Children) > 0 { - return nil, fmt.Errorf("can't mix positional arguments and branching arguments on %T", ast) - } - app.Node = node - app.Node.Flags = append(extraFlags, app.Node.Flags...) - app.Tag = newEmptyTag() - app.Tag.Vars = k.vars - return app, nil -} - -func dashedString(s string) string { - return strings.Join(camelCase(s), "-") -} - -type flattenedField struct { - field reflect.StructField - value reflect.Value - tag *Tag -} - -func flattenedFields(v reflect.Value, ptag *Tag) (out []flattenedField, err error) { - v = reflect.Indirect(v) - if v.Kind() != reflect.Struct { - return out, nil - } - ignored := map[string]bool{} - for i := 0; i < v.NumField(); i++ { - ft := v.Type().Field(i) - fv := v.Field(i) - tag, err := parseTag(v, ft) - if err != nil { - return nil, err - } - if tag.Ignored || ignored[ft.Name] { - ignored[ft.Name] = true - continue - } - // Assign group if it's not already set. - if tag.Group == "" { - tag.Group = ptag.Group - } - // Accumulate prefixes. - tag.Prefix = ptag.Prefix + tag.Prefix - tag.EnvPrefix = ptag.EnvPrefix + tag.EnvPrefix - tag.XorPrefix = ptag.XorPrefix + tag.XorPrefix - // Combine parent vars. - tag.Vars = ptag.Vars.CloneWith(tag.Vars) - // Command and embedded structs can be pointers, so we hydrate them now. - if (tag.Cmd || tag.Embed) && ft.Type.Kind() == reflect.Ptr { - fv = reflect.New(ft.Type.Elem()).Elem() - v.FieldByIndex(ft.Index).Set(fv.Addr()) - } - if !ft.Anonymous && !tag.Embed { - if fv.CanSet() { - field := flattenedField{field: ft, value: fv, tag: tag} - out = append(out, field) - } - continue - } - - // Embedded type. - if fv.Kind() == reflect.Interface { - fv = fv.Elem() - } else if fv.Type() == reflect.TypeOf(Plugins{}) { - for i := 0; i < fv.Len(); i++ { - fields, ferr := flattenedFields(fv.Index(i).Elem(), tag) - if ferr != nil { - return nil, ferr - } - out = append(out, fields...) - } - continue - } - sub, err := flattenedFields(fv, tag) - if err != nil { - return nil, err - } - out = append(out, sub...) - } - out = removeIgnored(out, ignored) - return out, nil -} - -func removeIgnored(fields []flattenedField, ignored map[string]bool) []flattenedField { - j := 0 - for i := 0; i < len(fields); i++ { - if ignored[fields[i].field.Name] { - continue - } - if i != j { - fields[j] = fields[i] - } - j++ - } - if j != len(fields) { - fields = fields[:j] - } - return fields -} - -// Build a Node in the Kong data model. -// -// "v" is the value to create the node from, "typ" is the output Node type. -func buildNode(k *Kong, v reflect.Value, typ NodeType, tag *Tag, seenFlags map[string]bool) (*Node, error) { //nolint:gocyclo - node := &Node{ - Type: typ, - Target: v, - Tag: tag, - } - fields, err := flattenedFields(v, tag) - if err != nil { - return nil, err - } - -MAIN: - for _, field := range fields { - for _, r := range k.ignoreFields { - if r.MatchString(v.Type().Name() + "." + field.field.Name) { - continue MAIN - } - } - - ft := field.field - fv := field.value - - tag := field.tag - name := tag.Name - if name == "" { - name = tag.Prefix + k.flagNamer(ft.Name) - } else { - name = tag.Prefix + name - } - - if len(tag.Envs) != 0 { - for i := range tag.Envs { - tag.Envs[i] = tag.EnvPrefix + tag.Envs[i] - } - } - - if len(tag.Xor) != 0 { - for i := range tag.Xor { - tag.Xor[i] = tag.XorPrefix + tag.Xor[i] - } - } - - if len(tag.And) != 0 { - for i := range tag.And { - tag.And[i] = tag.XorPrefix + tag.And[i] - } - } - - // Nested structs are either commands or args, unless they implement the Mapper interface. - if field.value.Kind() == reflect.Struct && (tag.Cmd || tag.Arg) && k.registry.ForValue(fv) == nil { - typ := CommandNode - if tag.Arg { - typ = ArgumentNode - } - err = buildChild(k, node, typ, v, ft, fv, tag, name, seenFlags) - } else { - err = buildField(k, node, v, ft, fv, tag, name, seenFlags) - } - if err != nil { - return nil, err - } - } - - // Validate if there are no duplicate names - if err := checkDuplicateNames(node, v); err != nil { - return nil, err - } - - // "Unsee" flags. - for _, flag := range node.Flags { - delete(seenFlags, "--"+flag.Name) - if flag.Short != 0 { - delete(seenFlags, "-"+string(flag.Short)) - } - if negFlag := negatableFlagName(flag.Name, flag.Tag.Negatable); negFlag != "" { - delete(seenFlags, negFlag) - } - for _, aflag := range flag.Aliases { - delete(seenFlags, "--"+aflag) - } - } - - if err := validatePositionalArguments(node); err != nil { - return nil, err - } - - return node, nil -} - -func validatePositionalArguments(node *Node) error { - var last *Value - for i, curr := range node.Positional { - if last != nil { - // Scan through argument positionals to ensure optional is never before a required. - if !last.Required && curr.Required { - return fmt.Errorf("%s: required %q cannot come after optional %q", node.FullPath(), curr.Name, last.Name) - } - - // Cumulative argument needs to be last. - if last.IsCumulative() { - return fmt.Errorf("%s: argument %q cannot come after cumulative %q", node.FullPath(), curr.Name, last.Name) - } - } - - last = curr - curr.Position = i - } - - return nil -} - -func buildChild(k *Kong, node *Node, typ NodeType, v reflect.Value, ft reflect.StructField, fv reflect.Value, tag *Tag, name string, seenFlags map[string]bool) error { - child, err := buildNode(k, fv, typ, newEmptyTag(), seenFlags) - if err != nil { - return err - } - child.Name = name - child.Tag = tag - child.Parent = node - child.Help = tag.Help - child.Hidden = tag.Hidden - child.Group = buildGroupForKey(k, tag.Group) - child.Aliases = tag.Aliases - - if provider, ok := fv.Addr().Interface().(HelpProvider); ok { - child.Detail = provider.Help() - } - - // A branching argument. This is a bit hairy, as we let buildNode() do the parsing, then check that - // a positional argument is provided to the child, and move it to the branching argument field. - if tag.Arg { - if len(child.Positional) == 0 { - return failField(v, ft, "positional branch must have at least one child positional argument named %q", name) - } - if child.Positional[0].Name != name { - return failField(v, ft, "first field in positional branch must have the same name as the parent field (%s).", child.Name) - } - - child.Argument = child.Positional[0] - child.Positional = child.Positional[1:] - if child.Help == "" { - child.Help = child.Argument.Help - } - } else { - if tag.HasDefault { - if node.DefaultCmd != nil { - return failField(v, ft, "can't have more than one default command under %s", node.Summary()) - } - if tag.Default != "withargs" && (len(child.Children) > 0 || len(child.Positional) > 0) { - return failField(v, ft, "default command %s must not have subcommands or arguments", child.Summary()) - } - node.DefaultCmd = child - } - if tag.Passthrough { - if len(child.Children) > 0 || len(child.Flags) > 0 { - return failField(v, ft, "passthrough command %s must not have subcommands or flags", child.Summary()) - } - if len(child.Positional) != 1 { - return failField(v, ft, "passthrough command %s must contain exactly one positional argument", child.Summary()) - } - if !checkPassthroughArg(child.Positional[0].Target) { - return failField(v, ft, "passthrough command %s must contain exactly one positional argument of []string type", child.Summary()) - } - child.Passthrough = true - } - } - node.Children = append(node.Children, child) - - if len(child.Positional) > 0 && len(child.Children) > 0 { - return failField(v, ft, "can't mix positional arguments and branching arguments") - } - - return nil -} - -func buildField(k *Kong, node *Node, v reflect.Value, ft reflect.StructField, fv reflect.Value, tag *Tag, name string, seenFlags map[string]bool) error { - mapper := k.registry.ForNamedValue(tag.Type, fv) - if mapper == nil { - return failField(v, ft, "unsupported field type %s, perhaps missing a cmd:\"\" tag?", ft.Type) - } - - value := &Value{ - Name: name, - Help: tag.Help, - OrigHelp: tag.Help, - HasDefault: tag.HasDefault, - Default: tag.Default, - DefaultValue: reflect.New(fv.Type()).Elem(), - Mapper: mapper, - Tag: tag, - Target: fv, - Enum: tag.Enum, - Passthrough: tag.Passthrough, - PassthroughMode: tag.PassthroughMode, - - // Flags are optional by default, and args are required by default. - Required: (!tag.Arg && tag.Required) || (tag.Arg && !tag.Optional), - Format: tag.Format, - } - - if tag.Arg { - node.Positional = append(node.Positional, value) - } else { - if seenFlags["--"+value.Name] { - return failField(v, ft, "duplicate flag --%s", value.Name) - } - seenFlags["--"+value.Name] = true - for _, alias := range tag.Aliases { - aliasFlag := "--" + alias - if seenFlags[aliasFlag] { - return failField(v, ft, "duplicate flag %s", aliasFlag) - } - seenFlags[aliasFlag] = true - } - if tag.Short != 0 { - if seenFlags["-"+string(tag.Short)] { - return failField(v, ft, "duplicate short flag -%c", tag.Short) - } - seenFlags["-"+string(tag.Short)] = true - } - if tag.Negatable != "" { - negFlag := negatableFlagName(value.Name, tag.Negatable) - if seenFlags[negFlag] { - return failField(v, ft, "duplicate negation flag %s", negFlag) - } - seenFlags[negFlag] = true - } - flag := &Flag{ - Value: value, - Aliases: tag.Aliases, - Short: tag.Short, - PlaceHolder: tag.PlaceHolder, - Envs: tag.Envs, - Group: buildGroupForKey(k, tag.Group), - Xor: tag.Xor, - And: tag.And, - Hidden: tag.Hidden, - } - value.Flag = flag - node.Flags = append(node.Flags, flag) - } - return nil -} - -func buildGroupForKey(k *Kong, key string) *Group { - if key == "" { - return nil - } - for _, group := range k.groups { - if group.Key == key { - return &group - } - } - - // No group provided with kong.ExplicitGroups. We create one ad-hoc for this key. - return &Group{ - Key: key, - Title: key, - } -} - -func checkDuplicateNames(node *Node, v reflect.Value) error { - seenNames := make(map[string]struct{}) - for _, node := range node.Children { - if _, ok := seenNames[node.Name]; ok { - name := v.Type().Name() - if name == "" { - name = "" - } - return fmt.Errorf("duplicate command name %q in command %q", node.Name, name) - } - - seenNames[node.Name] = struct{}{} - } - - return nil -} diff --git a/vendor/github.com/alecthomas/kong/callbacks.go b/vendor/github.com/alecthomas/kong/callbacks.go deleted file mode 100644 index 6096a26..0000000 --- a/vendor/github.com/alecthomas/kong/callbacks.go +++ /dev/null @@ -1,231 +0,0 @@ -package kong - -import ( - "fmt" - "reflect" - "strings" -) - -// binding is a single binding registered with Kong. -type binding struct { - // fn is a function that returns a value of the target type. - fn reflect.Value - - // val is a value of the target type. - // Must be set if done and singleton are true. - val reflect.Value - - // singleton indicates whether the binding is a singleton. - // If true, the binding will be resolved once and cached. - singleton bool - - // done indicates whether a singleton binding has been resolved. - // If singleton is false, this field is ignored. - done bool -} - -// newValueBinding builds a binding with an already resolved value. -func newValueBinding(v reflect.Value) *binding { - return &binding{val: v, done: true, singleton: true} -} - -// newFunctionBinding builds a binding with a function -// that will return a value of the target type. -// -// The function signature must be func(...) (T, error) or func(...) T -// where parameters are recursively resolved. -func newFunctionBinding(f reflect.Value, singleton bool) *binding { - return &binding{fn: f, singleton: singleton} -} - -// Get returns the pre-resolved value for the binding, -// or false if the binding is not resolved. -func (b *binding) Get() (v reflect.Value, ok bool) { - return b.val, b.done -} - -// Set sets the value of the binding to the given value, -// marking it as resolved. -// -// If the binding is not a singleton, this method does nothing. -func (b *binding) Set(v reflect.Value) { - if b.singleton { - b.val = v - b.done = true - } -} - -// A map of type to function that returns a value of that type. -// -// The function should have the signature func(...) (T, error). Arguments are recursively resolved. -type bindings map[reflect.Type]*binding - -func (b bindings) String() string { - out := []string{} - for k := range b { - out = append(out, k.String()) - } - return "bindings{" + strings.Join(out, ", ") + "}" -} - -func (b bindings) add(values ...any) bindings { - for _, v := range values { - val := reflect.ValueOf(v) - b[val.Type()] = newValueBinding(val) - } - return b -} - -func (b bindings) addTo(impl, iface any) { - val := reflect.ValueOf(impl) - b[reflect.TypeOf(iface).Elem()] = newValueBinding(val) -} - -func (b bindings) addProvider(provider any, singleton bool) error { - pv := reflect.ValueOf(provider) - t := pv.Type() - if t.Kind() != reflect.Func { - return fmt.Errorf("%T must be a function", provider) - } - - if t.NumOut() == 0 { - return fmt.Errorf("%T must be a function with the signature func(...)(T, error) or func(...) T", provider) - } - if t.NumOut() == 2 { - if t.Out(1) != reflect.TypeOf((*error)(nil)).Elem() { - return fmt.Errorf("missing error; %T must be a function with the signature func(...)(T, error) or func(...) T", provider) - } - } - rt := pv.Type().Out(0) - b[rt] = newFunctionBinding(pv, singleton) - return nil -} - -// Clone and add values. -func (b bindings) clone() bindings { - out := make(bindings, len(b)) - for k, v := range b { - out[k] = v - } - return out -} - -func (b bindings) merge(other bindings) bindings { - for k, v := range other { - b[k] = v - } - return b -} - -func getMethod(value reflect.Value, name string) reflect.Value { - method := value.MethodByName(name) - if !method.IsValid() { - if value.CanAddr() { - method = value.Addr().MethodByName(name) - } - } - return method -} - -// getMethods gets all methods with the given name from the given value -// and any embedded fields. -// -// Returns a slice of bound methods that can be called directly. -func getMethods(value reflect.Value, name string) (methods []reflect.Value) { - if value.Kind() == reflect.Ptr { - value = value.Elem() - } - if !value.IsValid() { - return - } - - if method := getMethod(value, name); method.IsValid() { - methods = append(methods, method) - } - - if value.Kind() != reflect.Struct { - return - } - // If the current value is a struct, also consider embedded fields. - // Two kinds of embedded fields are considered if they're exported: - // - // - standard Go embedded fields - // - fields tagged with `embed:""` - t := value.Type() - for i := 0; i < value.NumField(); i++ { - fieldValue := value.Field(i) - field := t.Field(i) - - if !field.IsExported() { - continue - } - - // Consider a field embedded if it's actually embedded - // or if it's tagged with `embed:""`. - _, isEmbedded := field.Tag.Lookup("embed") - isEmbedded = isEmbedded || field.Anonymous - if isEmbedded { - methods = append(methods, getMethods(fieldValue, name)...) - } - } - return -} - -func callFunction(f reflect.Value, bindings bindings) error { - if f.Kind() != reflect.Func { - return fmt.Errorf("expected function, got %s", f.Type()) - } - t := f.Type() - if t.NumOut() != 1 || !t.Out(0).Implements(callbackReturnSignature) { - return fmt.Errorf("return value of %s must implement \"error\"", t) - } - out, err := callAnyFunction(f, bindings) - if err != nil { - return err - } - ferr := out[0] - if ferrv := reflect.ValueOf(ferr); !ferrv.IsValid() || ((ferrv.Kind() == reflect.Interface || ferrv.Kind() == reflect.Pointer) && ferrv.IsNil()) { - return nil - } - return ferr.(error) //nolint:forcetypeassert -} - -func callAnyFunction(f reflect.Value, bindings bindings) (out []any, err error) { - if f.Kind() != reflect.Func { - return nil, fmt.Errorf("expected function, got %s", f.Type()) - } - in := []reflect.Value{} - t := f.Type() - for i := 0; i < t.NumIn(); i++ { - pt := t.In(i) - binding, ok := bindings[pt] - if !ok { - return nil, fmt.Errorf("couldn't find binding of type %s for parameter %d of %s(), use kong.Bind(%s)", pt, i, t, pt) - } - - // Don't need to call the function if the value is already resolved. - if val, ok := binding.Get(); ok { - in = append(in, val) - continue - } - - // Recursively resolve binding functions. - argv, err := callAnyFunction(binding.fn, bindings) - if err != nil { - return nil, fmt.Errorf("%s: %w", pt, err) - } - if ferrv := reflect.ValueOf(argv[len(argv)-1]); ferrv.IsValid() && ferrv.Type().Implements(callbackReturnSignature) && !ferrv.IsNil() { - return nil, ferrv.Interface().(error) //nolint:forcetypeassert - } - - val := reflect.ValueOf(argv[0]) - binding.Set(val) - in = append(in, val) - } - outv := f.Call(in) - out = make([]any, len(outv)) - for i, v := range outv { - out[i] = v.Interface() - } - return out, nil -} diff --git a/vendor/github.com/alecthomas/kong/camelcase.go b/vendor/github.com/alecthomas/kong/camelcase.go deleted file mode 100644 index a955b16..0000000 --- a/vendor/github.com/alecthomas/kong/camelcase.go +++ /dev/null @@ -1,90 +0,0 @@ -package kong - -// NOTE: This code is from https://github.com/fatih/camelcase. MIT license. - -import ( - "unicode" - "unicode/utf8" -) - -// 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" => ["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 -// 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 camelCase(src string) (entries []string) { - // don't split invalid utf8 - if !utf8.ValidString(src) { - return []string{src} - } - entries = []string{} - var runes [][]rune - lastClass := 0 - // split into fields based on class of unicode character - for _, r := range src { - var class int - switch { - case unicode.IsLower(r): - class = 1 - case unicode.IsUpper(r): - class = 2 - case unicode.IsDigit(r): - class = 3 - default: - class = 4 - } - if class == lastClass { - 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 entries -} diff --git a/vendor/github.com/alecthomas/kong/context.go b/vendor/github.com/alecthomas/kong/context.go deleted file mode 100644 index 6a4989f..0000000 --- a/vendor/github.com/alecthomas/kong/context.go +++ /dev/null @@ -1,1183 +0,0 @@ -package kong - -import ( - "errors" - "fmt" - "os" - "reflect" - "sort" - "strconv" - "strings" -) - -// Path records the nodes and parsed values from the current command-line. -type Path struct { - Parent *Node - - // One of these will be non-nil. - App *Application - Positional *Positional - Flag *Flag - Argument *Argument - Command *Command - - // Flags added by this node. - Flags []*Flag - - // True if this Path element was created as the result of a resolver. - Resolved bool - - // Remaining tokens after this node - remainder []Token -} - -// Node returns the Node associated with this Path, or nil if Path is a non-Node. -func (p *Path) Node() *Node { - switch { - case p.App != nil: - return p.App.Node - - case p.Argument != nil: - return p.Argument - - case p.Command != nil: - return p.Command - } - return nil -} - -// Visitable returns the Visitable for this path element. -func (p *Path) Visitable() Visitable { - switch { - case p.App != nil: - return p.App - - case p.Argument != nil: - return p.Argument - - case p.Command != nil: - return p.Command - - case p.Flag != nil: - return p.Flag - - case p.Positional != nil: - return p.Positional - } - return nil -} - -// Remainder returns the remaining unparsed args after this Path element. -func (p *Path) Remainder() []string { - args := []string{} - for _, token := range p.remainder { - args = append(args, token.String()) - } - return args -} - -// Context contains the current parse context. -type Context struct { - *Kong - // A trace through parsed nodes. - Path []*Path - // Original command-line arguments. - Args []string - // Error that occurred during trace, if any. - Error error - - values map[*Value]reflect.Value // Temporary values during tracing. - bindings bindings - resolvers []Resolver // Extra context-specific resolvers. - scan *Scanner -} - -// Trace path of "args" through the grammar tree. -// -// The returned Context will include a Path of all commands, arguments, positionals and flags. -// -// This just constructs a new trace. To fully apply the trace you must call Reset(), Resolve(), -// Validate() and Apply(). -func Trace(k *Kong, args []string) (*Context, error) { - s := Scan(args...).AllowHyphenPrefixedParameters(k.allowHyphenated) - c := &Context{ - Kong: k, - Args: args, - Path: []*Path{ - {App: k.Model, Flags: k.Model.Flags, remainder: s.PeekAll()}, - }, - values: map[*Value]reflect.Value{}, - scan: s, - bindings: bindings{}, - } - c.Error = c.trace(c.Model.Node) - return c, nil -} - -// Bind adds bindings to the Context. -func (c *Context) Bind(args ...any) { - c.bindings.add(args...) -} - -// BindTo adds a binding to the Context. -// -// This will typically have to be called like so: -// -// BindTo(impl, (*MyInterface)(nil)) -func (c *Context) BindTo(impl, iface any) { - c.bindings.addTo(impl, iface) -} - -// BindToProvider allows binding of provider functions. -// -// This is useful when the Run() function of different commands require different values that may -// not all be initialisable from the main() function. -// -// "provider" must be a function with the signature func(...) (T, error) or func(...) T, -// where ... will be recursively injected with bound values. -func (c *Context) BindToProvider(provider any) error { - return c.bindings.addProvider(provider, false /* singleton */) -} - -// BindSingletonProvider allows binding of provider functions. -// The provider will be called once and the result cached. -// -// "provider" must be a function with the signature func(...) (T, error) or func(...) T, -// where ... will be recursively injected with bound values. -func (c *Context) BindSingletonProvider(provider any) error { - return c.bindings.addProvider(provider, true /* singleton */) -} - -// Value returns the value for a particular path element. -func (c *Context) Value(path *Path) reflect.Value { - switch { - case path.Positional != nil: - return c.values[path.Positional] - case path.Flag != nil: - return c.values[path.Flag.Value] - case path.Argument != nil: - return c.values[path.Argument.Argument] - } - panic("can only retrieve value for flag, argument or positional") -} - -// Selected command or argument. -func (c *Context) Selected() *Node { - var selected *Node - for _, path := range c.Path { - switch { - case path.Command != nil: - selected = path.Command - case path.Argument != nil: - selected = path.Argument - } - } - return selected -} - -// Empty returns true if there were no arguments provided. -func (c *Context) Empty() bool { - for _, path := range c.Path { - if !path.Resolved && path.App == nil { - return false - } - } - return true -} - -// Validate the current context. -func (c *Context) Validate() error { //nolint: gocyclo - err := Visit(c.Model, func(node Visitable, next Next) error { - switch node := node.(type) { - case *Value: - ok := atLeastOneEnvSet(node.Tag.Envs) - if node.Enum != "" && (!node.Required || node.HasDefault || (len(node.Tag.Envs) != 0 && ok)) { - if err := checkEnum(node, node.Target); err != nil { - return err - } - } - - case *Flag: - ok := atLeastOneEnvSet(node.Tag.Envs) - if node.Enum != "" && (!node.Required || node.HasDefault || (len(node.Tag.Envs) != 0 && ok)) { - if err := checkEnum(node.Value, node.Target); err != nil { - return err - } - } - } - return next(nil) - }) - if err != nil { - return err - } - for _, el := range c.Path { - var ( - value reflect.Value - desc string - ) - switch node := el.Visitable().(type) { - case *Value: - value = node.Target - desc = node.ShortSummary() - - case *Flag: - value = node.Target - desc = node.ShortSummary() - - case *Application: - value = node.Target - desc = "" - - case *Node: - value = node.Target - desc = node.Path() - } - if validate := isValidatable(value); validate != nil { - if err := validate.Validate(c); err != nil { - if desc != "" { - return fmt.Errorf("%s: %w", desc, err) - } - return err - } - } - } - for _, resolver := range c.combineResolvers() { - if err := resolver.Validate(c.Model); err != nil { - return err - } - } - for _, path := range c.Path { - var value *Value - switch { - case path.Flag != nil: - value = path.Flag.Value - - case path.Positional != nil: - value = path.Positional - } - if value != nil && value.Tag.Enum != "" { - if err := checkEnum(value, value.Target); err != nil { - return err - } - } - if err := checkMissingFlags(path.Flags); err != nil { - return err - } - } - // Check the terminal node. - node := c.Selected() - if node == nil { - node = c.Model.Node - } - - // Find deepest positional argument so we can check if all required positionals have been provided. - positionals := 0 - for _, path := range c.Path { - if path.Positional != nil { - positionals = path.Positional.Position + 1 - } - } - - if err := checkMissingChildren(node); err != nil { - return err - } - if err := checkMissingPositionals(positionals, node.Positional); err != nil { - return err - } - if err := checkXorDuplicatedAndAndMissing(c.Path); err != nil { - return err - } - - if node.Type == ArgumentNode { - value := node.Argument - if value.Required && !value.Set { - return fmt.Errorf("%s is required", node.Summary()) - } - } - return nil -} - -// Flags returns the accumulated available flags. -func (c *Context) Flags() (flags []*Flag) { - for _, trace := range c.Path { - flags = append(flags, trace.Flags...) - } - return -} - -// Command returns the full command path. -func (c *Context) Command() string { - command := []string{} - for _, trace := range c.Path { - switch { - case trace.Positional != nil: - command = append(command, "<"+trace.Positional.Name+">") - - case trace.Argument != nil: - command = append(command, "<"+trace.Argument.Name+">") - - case trace.Command != nil: - command = append(command, trace.Command.Name) - } - } - return strings.Join(command, " ") -} - -// AddResolver adds a context-specific resolver. -// -// This is most useful in the BeforeResolve() hook. -func (c *Context) AddResolver(resolver Resolver) { - c.resolvers = append(c.resolvers, resolver) -} - -// FlagValue returns the set value of a flag if it was encountered and exists, or its default value. -func (c *Context) FlagValue(flag *Flag) any { - for _, trace := range c.Path { - if trace.Flag == flag { - v, ok := c.values[trace.Flag.Value] - if !ok { - break - } - return v.Interface() - } - } - if flag.Target.IsValid() { - return flag.Target.Interface() - } - return flag.DefaultValue.Interface() -} - -// Reset recursively resets values to defaults (as specified in the grammar) or the zero value. -func (c *Context) Reset() error { - return Visit(c.Model.Node, func(node Visitable, next Next) error { - if value, ok := node.(*Value); ok { - return next(value.Reset()) - } - return next(nil) - }) -} - -func (c *Context) endParsing() { - args := []string{} - for { - token := c.scan.Pop() - if token.Type == EOLToken { - break - } - args = append(args, token.String()) - } - // Note: tokens must be pushed in reverse order. - for i := range args { - c.scan.PushTyped(args[len(args)-1-i], PositionalArgumentToken) - } -} - -//nolint:maintidx -func (c *Context) trace(node *Node) (err error) { //nolint: gocyclo - positional := 0 - node.Active = true - - flags := []*Flag{} - flagNode := node - if node.DefaultCmd != nil && node.DefaultCmd.Tag.Default == "withargs" { - // Add flags of the default command if the current node has one - // and that default command allows args / flags without explicitly - // naming the command on the CLI. - flagNode = node.DefaultCmd - } - for _, group := range flagNode.AllFlags(false) { - flags = append(flags, group...) - } - - if node.Passthrough { - c.endParsing() - } - - for !c.scan.Peek().IsEOL() { - token := c.scan.Peek() - switch token.Type { - case UntypedToken: - switch v := token.Value.(type) { - case string: - - switch { - case v == "-": - fallthrough - default: //nolint - c.scan.Pop() - c.scan.PushTyped(token.Value, PositionalArgumentToken) - - // Indicates end of parsing. All remaining arguments are treated as positional arguments only. - case v == "--": - c.endParsing() - - // Pop the -- token unless the next positional argument accepts passthrough arguments. - if !(positional < len(node.Positional) && node.Positional[positional].Passthrough) { - c.scan.Pop() - } - - // Long flag. - case strings.HasPrefix(v, "--"): - c.scan.Pop() - // Parse it and push the tokens. - parts := strings.SplitN(v[2:], "=", 2) - if len(parts) > 1 { - c.scan.PushTyped(parts[1], FlagValueToken) - } - c.scan.PushTyped(parts[0], FlagToken) - - // Short flag. - case strings.HasPrefix(v, "-"): - c.scan.Pop() - // Note: tokens must be pushed in reverse order. - if tail := v[2:]; tail != "" { - c.scan.PushTyped(tail, ShortFlagTailToken) - } - c.scan.PushTyped(v[1:2], ShortFlagToken) - } - default: - c.scan.Pop() - c.scan.PushTyped(token.Value, PositionalArgumentToken) - } - - case ShortFlagTailToken: - c.scan.Pop() - // Note: tokens must be pushed in reverse order. - if tail := token.String()[1:]; tail != "" { - c.scan.PushTyped(tail, ShortFlagTailToken) - } - c.scan.PushTyped(token.String()[0:1], ShortFlagToken) - - case FlagToken: - if err := c.parseFlag(flags, token.String()); err != nil { - if isUnknownFlagError(err) && positional < len(node.Positional) && node.Positional[positional].PassthroughMode == PassThroughModeAll { - c.scan.Pop() - c.scan.PushTyped(token.String(), PositionalArgumentToken) - } else { - return err - } - } - - case ShortFlagToken: - if err := c.parseFlag(flags, token.String()); err != nil { - if isUnknownFlagError(err) && positional < len(node.Positional) && node.Positional[positional].PassthroughMode == PassThroughModeAll { - c.scan.Pop() - c.scan.PushTyped(token.String(), PositionalArgumentToken) - } else { - return err - } - } - - case FlagValueToken: - return fmt.Errorf("unexpected flag argument %q", token.Value) - - case PositionalArgumentToken: - candidates := []string{} - - // Ensure we've consumed all positional arguments. - if positional < len(node.Positional) { - arg := node.Positional[positional] - - if arg.Passthrough { - c.endParsing() - } - - arg.Active = true - err := arg.Parse(c.scan, c.getValue(arg)) - if err != nil { - return err - } - c.Path = append(c.Path, &Path{ - Parent: node, - Positional: arg, - remainder: c.scan.PeekAll(), - }) - positional++ - break - } - - // Assign token value to a branch name if tagged as an alias - // An alias will be ignored in the case of an existing command - cmds := make(map[string]bool) - for _, branch := range node.Children { - if branch.Type == CommandNode { - cmds[branch.Name] = true - } - } - for _, branch := range node.Children { - for _, a := range branch.Aliases { - _, ok := cmds[a] - if token.Value == a && !ok { - token.Value = branch.Name - break - } - } - } - - // After positional arguments have been consumed, check commands next... - for _, branch := range node.Children { - if branch.Type == CommandNode && !branch.Hidden { - candidates = append(candidates, branch.Name) - } - if branch.Type == CommandNode && branch.Name == token.Value { - c.scan.Pop() - c.Path = append(c.Path, &Path{ - Parent: node, - Command: branch, - Flags: branch.Flags, - remainder: c.scan.PeekAll(), - }) - return c.trace(branch) - } - } - - // Finally, check arguments. - for _, branch := range node.Children { - if branch.Type == ArgumentNode { - arg := branch.Argument - if err := arg.Parse(c.scan, c.getValue(arg)); err == nil { - c.Path = append(c.Path, &Path{ - Parent: node, - Argument: branch, - Flags: branch.Flags, - remainder: c.scan.PeekAll(), - }) - return c.trace(branch) - } - } - } - - // If there is a default command that allows args and nothing else - // matches, take the branch of the default command - if node.DefaultCmd != nil && node.DefaultCmd.Tag.Default == "withargs" { - c.Path = append(c.Path, &Path{ - Parent: node, - Command: node.DefaultCmd, - Flags: node.DefaultCmd.Flags, - remainder: c.scan.PeekAll(), - }) - return c.trace(node.DefaultCmd) - } - - return findPotentialCandidates(token.String(), candidates, "unexpected argument %s", token) - default: - return fmt.Errorf("unexpected token %s", token) - } - } - return c.maybeSelectDefault(flags, node) -} - -// IgnoreDefault can be implemented by flags that want to be applied before any default commands. -type IgnoreDefault interface { - IgnoreDefault() -} - -// End of the line, check for a default command, but only if we're not displaying help, -// otherwise we'd only ever display the help for the default command. -func (c *Context) maybeSelectDefault(flags []*Flag, node *Node) error { - for _, flag := range flags { - if _, ok := flag.Target.Interface().(IgnoreDefault); ok && flag.Set { - return nil - } - } - if node.DefaultCmd != nil { - c.Path = append(c.Path, &Path{ - Parent: node.DefaultCmd, - Command: node.DefaultCmd, - Flags: node.DefaultCmd.Flags, - remainder: c.scan.PeekAll(), - }) - } - return nil -} - -// Resolve walks through the traced path, applying resolvers to any unset flags. -func (c *Context) Resolve() error { - resolvers := c.combineResolvers() - if len(resolvers) == 0 { - return nil - } - - inserted := []*Path{} - for _, path := range c.Path { - for _, flag := range path.Flags { - // Flag has already been set on the command-line. - if _, ok := c.values[flag.Value]; ok { - continue - } - - // Pick the last resolved value. - var selected any - for _, resolver := range resolvers { - s, err := resolver.Resolve(c, path, flag) - if err != nil { - return fmt.Errorf("%s: %w", flag.ShortSummary(), err) - } - if s == nil { - continue - } - selected = s - } - - if selected == nil { - continue - } - - scan := Scan().PushTyped(selected, FlagValueToken) - delete(c.values, flag.Value) - err := flag.Parse(scan, c.getValue(flag.Value)) - if err != nil { - return err - } - inserted = append(inserted, &Path{ - Flag: flag, - Resolved: true, - remainder: c.scan.PeekAll(), - }) - } - } - c.Path = append(c.Path, inserted...) - return nil -} - -// Combine application-level resolvers and context resolvers. -func (c *Context) combineResolvers() []Resolver { - resolvers := []Resolver{} - resolvers = append(resolvers, c.Kong.resolvers...) - resolvers = append(resolvers, c.resolvers...) - return resolvers -} - -func (c *Context) getValue(value *Value) reflect.Value { - v, ok := c.values[value] - if !ok { - v = reflect.New(value.Target.Type()).Elem() - switch v.Kind() { - case reflect.Ptr: - v.Set(reflect.New(v.Type().Elem())) - case reflect.Slice: - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - case reflect.Map: - v.Set(reflect.MakeMap(v.Type())) - default: - } - c.values[value] = v - } - return v -} - -// ApplyDefaults if they are not already set. -func (c *Context) ApplyDefaults() error { - return Visit(c.Model.Node, func(node Visitable, next Next) error { - var value *Value - switch node := node.(type) { - case *Flag: - value = node.Value - case *Node: - value = node.Argument - case *Value: - value = node - default: - } - if value != nil { - if err := value.ApplyDefault(); err != nil { - return err - } - } - return next(nil) - }) -} - -// Apply traced context to the target grammar. -func (c *Context) Apply() (string, error) { - path := []string{} - - for _, trace := range c.Path { - var value *Value - switch { - case trace.App != nil: - case trace.Argument != nil: - path = append(path, "<"+trace.Argument.Name+">") - value = trace.Argument.Argument - case trace.Command != nil: - path = append(path, trace.Command.Name) - case trace.Flag != nil: - value = trace.Flag.Value - case trace.Positional != nil: - path = append(path, "<"+trace.Positional.Name+">") - value = trace.Positional - default: - panic("unsupported path ?!") - } - if value != nil { - value.Apply(c.getValue(value)) - } - } - - return strings.Join(path, " "), nil -} - -func flipBoolValue(value reflect.Value) error { - if value.Kind() == reflect.Bool { - value.SetBool(!value.Bool()) - return nil - } - - if value.Kind() == reflect.Ptr { - if !value.IsNil() { - return flipBoolValue(value.Elem()) - } - return nil - } - - return fmt.Errorf("cannot negate a value of %s", value.Type().String()) -} - -func (c *Context) parseFlag(flags []*Flag, match string) (err error) { - candidates := []string{} - - for _, flag := range flags { - long := "--" + flag.Name - matched := long == match - candidates = append(candidates, long) - if flag.Short != 0 { - short := "-" + string(flag.Short) - matched = matched || (short == match) - candidates = append(candidates, short) - } - for _, alias := range flag.Aliases { - alias = "--" + alias - matched = matched || (alias == match) - candidates = append(candidates, alias) - } - - neg := negatableFlagName(flag.Name, flag.Tag.Negatable) - if !matched && match != neg { - continue - } - // Found a matching flag. - c.scan.Pop() - if match == neg && flag.Tag.Negatable != "" { - flag.Negated = true - } - err := flag.Parse(c.scan, c.getValue(flag.Value)) - if err != nil { - var expected *expectedError - if errors.As(err, &expected) && expected.token.InferredType().IsAny(FlagToken, ShortFlagToken) { - return fmt.Errorf("%s; perhaps try %s=%q?", err.Error(), flag.ShortSummary(), expected.token) - } - return err - } - if flag.Negated { - value := c.getValue(flag.Value) - err := flipBoolValue(value) - if err != nil { - return err - } - flag.Value.Apply(value) - } - c.Path = append(c.Path, &Path{ - Flag: flag, - remainder: c.scan.PeekAll(), - }) - return nil - } - return &unknownFlagError{Cause: findPotentialCandidates(match, candidates, "unknown flag %s", match)} -} - -func isUnknownFlagError(err error) bool { - var unknown *unknownFlagError - return errors.As(err, &unknown) -} - -type unknownFlagError struct{ Cause error } - -func (e *unknownFlagError) Unwrap() error { return e.Cause } -func (e *unknownFlagError) Error() string { return e.Cause.Error() } - -// Call an arbitrary function filling arguments with bound values. -func (c *Context) Call(fn any, binds ...any) (out []any, err error) { - fv := reflect.ValueOf(fn) - bindings := c.Kong.bindings.clone().add(binds...).add(c).merge(c.bindings) - return callAnyFunction(fv, bindings) -} - -// RunNode calls the Run() method on an arbitrary node. -// -// This is useful in conjunction with Visit(), for dynamically running commands. -// -// Any passed values will be bindable to arguments of the target Run() method. Additionally, -// all parent nodes in the command structure will be bound. -func (c *Context) RunNode(node *Node, binds ...any) (err error) { - type targetMethod struct { - node *Node - method reflect.Value - binds bindings - } - methodBinds := c.Kong.bindings.clone().add(binds...).add(c).merge(c.bindings) - methods := []targetMethod{} - for i := 0; node != nil; i, node = i+1, node.Parent { - method := getMethod(node.Target, "Run") - methodBinds = methodBinds.clone() - for p := node; p != nil; p = p.Parent { - methodBinds = methodBinds.add(p.Target.Addr().Interface()) - // Try value and pointer to value. - for _, p := range []reflect.Value{p.Target, p.Target.Addr()} { - t := p.Type() - for i := 0; i < p.NumMethod(); i++ { - methodt := t.Method(i) - if strings.HasPrefix(methodt.Name, "Provide") { - method := p.Method(i) - if err := methodBinds.addProvider(method.Interface(), false /* singleton */); err != nil { - return fmt.Errorf("%s.%s: %w", t.Name(), methodt.Name, err) - } - } - } - } - } - if method.IsValid() { - methods = append(methods, targetMethod{node, method, methodBinds}) - } - } - if len(methods) == 0 { - return fmt.Errorf("no Run() method found in hierarchy of %s", c.Selected().Summary()) - } - for _, method := range methods { - if err = callFunction(method.method, method.binds); err != nil { - return err - } - } - return nil -} - -// Run executes the Run() method on the selected command, which must exist. -// -// Any passed values will be bindable to arguments of the target Run() method. Additionally, -// all parent nodes in the command structure will be bound. -func (c *Context) Run(binds ...any) (err error) { - node := c.Selected() - if node == nil { - if len(c.Path) == 0 { - return fmt.Errorf("no command selected") - } - selected := c.Path[0].Node() - if selected.Type == ApplicationNode { - method := getMethod(selected.Target, "Run") - if method.IsValid() { - node = selected - } - } - - if node == nil { - return fmt.Errorf("no command selected") - } - } - runErr := c.RunNode(node, binds...) - err = c.Kong.applyHook(c, "AfterRun") - return errors.Join(runErr, err) -} - -// PrintUsage to Kong's stdout. -// -// If summary is true, a summarised version of the help will be output. -func (c *Context) PrintUsage(summary bool) error { - options := c.helpOptions - options.Summary = summary - return c.help(options, c) -} - -func checkMissingFlags(flags []*Flag) error { - xorGroupSet := map[string]bool{} - xorGroup := map[string][]string{} - andGroupSet := map[string]bool{} - andGroup := map[string][]string{} - missing := []string{} - andGroupRequired := getRequiredAndGroupMap(flags) - for _, flag := range flags { - for _, and := range flag.And { - flag.Required = andGroupRequired[and] - } - if flag.Set { - for _, xor := range flag.Xor { - xorGroupSet[xor] = true - } - for _, and := range flag.And { - andGroupSet[and] = true - } - } - if !flag.Required || flag.Set { - continue - } - if len(flag.Xor) > 0 || len(flag.And) > 0 { - for _, xor := range flag.Xor { - if xorGroupSet[xor] { - continue - } - xorGroup[xor] = append(xorGroup[xor], flag.Summary()) - } - for _, and := range flag.And { - andGroup[and] = append(andGroup[and], flag.Summary()) - } - } else { - missing = append(missing, flag.Summary()) - } - } - for xor, flags := range xorGroup { - if !xorGroupSet[xor] && len(flags) > 1 { - missing = append(missing, strings.Join(flags, " or ")) - } - } - for _, flags := range andGroup { - if len(flags) > 1 { - missing = append(missing, strings.Join(flags, " and ")) - } - } - - if len(missing) == 0 { - return nil - } - - sort.Strings(missing) - - return fmt.Errorf("missing flags: %s", strings.Join(missing, ", ")) -} - -func getRequiredAndGroupMap(flags []*Flag) map[string]bool { - andGroupRequired := map[string]bool{} - for _, flag := range flags { - for _, and := range flag.And { - if flag.Required { - andGroupRequired[and] = true - } - } - } - return andGroupRequired -} - -func checkMissingChildren(node *Node) error { - missing := []string{} - - missingArgs := []string{} - for _, arg := range node.Positional { - if arg.Required && !arg.Set { - missingArgs = append(missingArgs, arg.Summary()) - } - } - if len(missingArgs) > 0 { - missing = append(missing, strconv.Quote(strings.Join(missingArgs, " "))) - } - - for _, child := range node.Children { - if child.Hidden { - continue - } - if child.Argument != nil { - if !child.Argument.Required { - continue - } - missing = append(missing, strconv.Quote(child.Summary())) - } else { - missing = append(missing, strconv.Quote(child.Name)) - } - } - if len(missing) == 0 { - return nil - } - - if len(missing) > 5 { - missing = append(missing[:5], "...") - } - if len(missing) == 1 { - return fmt.Errorf("expected %s", missing[0]) - } - return fmt.Errorf("expected one of %s", strings.Join(missing, ", ")) -} - -// If we're missing any positionals and they're required, return an error. -func checkMissingPositionals(positional int, values []*Value) error { - // All the positionals are in. - if positional >= len(values) { - return nil - } - - // We're low on supplied positionals, but the missing one is optional. - if !values[positional].Required { - return nil - } - - missing := []string{} - for ; positional < len(values); positional++ { - arg := values[positional] - // TODO(aat): Fix hardcoding of these env checks all over the place :\ - if len(arg.Tag.Envs) != 0 { - if atLeastOneEnvSet(arg.Tag.Envs) { - continue - } - } - missing = append(missing, "<"+arg.Name+">") - } - if len(missing) == 0 { - return nil - } - return fmt.Errorf("missing positional arguments %s", strings.Join(missing, " ")) -} - -func checkEnum(value *Value, target reflect.Value) error { - switch target.Kind() { - case reflect.Slice, reflect.Array: - for i := 0; i < target.Len(); i++ { - if err := checkEnum(value, target.Index(i)); err != nil { - return err - } - } - return nil - - case reflect.Map, reflect.Struct: - return errors.New("enum can only be applied to a slice or value") - - case reflect.Ptr: - if target.IsNil() { - return nil - } - return checkEnum(value, target.Elem()) - default: - enumSlice := value.EnumSlice() - v := fmt.Sprintf("%v", target) - enums := []string{} - for _, enum := range enumSlice { - if enum == v { - return nil - } - enums = append(enums, fmt.Sprintf("%q", enum)) - } - return fmt.Errorf("%s must be one of %s but got %q", value.ShortSummary(), strings.Join(enums, ","), fmt.Sprintf("%v", target.Interface())) - } -} - -func checkPassthroughArg(target reflect.Value) bool { - typ := target.Type() - switch typ.Kind() { - case reflect.Slice: - return typ.Elem().Kind() == reflect.String - default: - return false - } -} - -func checkXorDuplicatedAndAndMissing(paths []*Path) error { - errs := []string{} - if err := checkXorDuplicates(paths); err != nil { - errs = append(errs, err.Error()) - } - if err := checkAndMissing(paths); err != nil { - errs = append(errs, err.Error()) - } - if len(errs) > 0 { - return errors.New(strings.Join(errs, ", ")) - } - return nil -} - -func checkXorDuplicates(paths []*Path) error { - for _, path := range paths { - seen := map[string]*Flag{} - for _, flag := range path.Flags { - if !flag.Set { - continue - } - for _, xor := range flag.Xor { - if seen[xor] != nil { - return fmt.Errorf("--%s and --%s can't be used together", seen[xor].Name, flag.Name) - } - seen[xor] = flag - } - } - } - return nil -} - -func checkAndMissing(paths []*Path) error { - for _, path := range paths { - missingMsgs := []string{} - andGroups := map[string][]*Flag{} - for _, flag := range path.Flags { - for _, and := range flag.And { - andGroups[and] = append(andGroups[and], flag) - } - } - for _, flags := range andGroups { - oneSet := false - notSet := []*Flag{} - flagNames := []string{} - for _, flag := range flags { - flagNames = append(flagNames, flag.Name) - if flag.Set { - oneSet = true - } else { - notSet = append(notSet, flag) - } - } - if len(notSet) > 0 && oneSet { - missingMsgs = append(missingMsgs, fmt.Sprintf("--%s must be used together", strings.Join(flagNames, " and --"))) - } - } - if len(missingMsgs) > 0 { - return fmt.Errorf("%s", strings.Join(missingMsgs, ", ")) - } - } - return nil -} - -func findPotentialCandidates(needle string, haystack []string, format string, args ...any) error { - if len(haystack) == 0 { - return fmt.Errorf(format, args...) - } - closestCandidates := []string{} - for _, candidate := range haystack { - if strings.HasPrefix(candidate, needle) || levenshtein(candidate, needle) <= 2 { - closestCandidates = append(closestCandidates, fmt.Sprintf("%q", candidate)) - } - } - prefix := fmt.Sprintf(format, args...) - if len(closestCandidates) == 1 { - return fmt.Errorf("%s, did you mean %s?", prefix, closestCandidates[0]) - } else if len(closestCandidates) > 1 { - return fmt.Errorf("%s, did you mean one of %s?", prefix, strings.Join(closestCandidates, ", ")) - } - return fmt.Errorf("%s", prefix) -} - -type validatable interface{ Validate() error } -type extendedValidatable interface { - Validate(kctx *Context) error -} - -// Proxy a validatable function to the extendedValidatable interface -type validatableFunc func() error - -func (f validatableFunc) Validate(kctx *Context) error { return f() } - -func isValidatable(v reflect.Value) extendedValidatable { - if !v.IsValid() || (v.Kind() == reflect.Ptr || v.Kind() == reflect.Slice || v.Kind() == reflect.Map) && v.IsNil() { - return nil - } - if validate, ok := v.Interface().(validatable); ok { - return validatableFunc(validate.Validate) - } - if validate, ok := v.Interface().(extendedValidatable); ok { - return validate - } - if v.CanAddr() { - return isValidatable(v.Addr()) - } - return nil -} - -func atLeastOneEnvSet(envs []string) bool { - for _, env := range envs { - if _, ok := os.LookupEnv(env); ok { - return true - } - } - return false -} diff --git a/vendor/github.com/alecthomas/kong/defaults.go b/vendor/github.com/alecthomas/kong/defaults.go deleted file mode 100644 index 9489fb3..0000000 --- a/vendor/github.com/alecthomas/kong/defaults.go +++ /dev/null @@ -1,21 +0,0 @@ -package kong - -// ApplyDefaults if they are not already set. -func ApplyDefaults(target any, options ...Option) error { - app, err := New(target, options...) - if err != nil { - return err - } - ctx, err := Trace(app, nil) - if err != nil { - return err - } - err = ctx.Resolve() - if err != nil { - return err - } - if err = ctx.ApplyDefaults(); err != nil { - return err - } - return ctx.Validate() -} diff --git a/vendor/github.com/alecthomas/kong/doc.go b/vendor/github.com/alecthomas/kong/doc.go deleted file mode 100644 index 7e53da7..0000000 --- a/vendor/github.com/alecthomas/kong/doc.go +++ /dev/null @@ -1,32 +0,0 @@ -// Package kong aims to support arbitrarily complex command-line structures with as little developer effort as possible. -// -// Here's an example: -// -// shell rm [-f] [-r] ... -// shell ls [ ...] -// -// This can be represented by the following command-line structure: -// -// package main -// -// import "github.com/alecthomas/kong" -// -// var CLI struct { -// Rm struct { -// Force bool `short:"f" help:"Force removal."` -// Recursive bool `short:"r" help:"Recursively remove files."` -// -// Paths []string `arg help:"Paths to remove." type:"path"` -// } `cmd help:"Remove files."` -// -// Ls struct { -// Paths []string `arg optional help:"Paths to list." type:"path"` -// } `cmd help:"List paths."` -// } -// -// func main() { -// kong.Parse(&CLI) -// } -// -// See https://github.com/alecthomas/kong for details. -package kong diff --git a/vendor/github.com/alecthomas/kong/error.go b/vendor/github.com/alecthomas/kong/error.go deleted file mode 100644 index e79a15d..0000000 --- a/vendor/github.com/alecthomas/kong/error.go +++ /dev/null @@ -1,21 +0,0 @@ -package kong - -// ParseError is the error type returned by Kong.Parse(). -// -// It contains the parse Context that triggered the error. -type ParseError struct { - error - Context *Context - exitCode int -} - -// Unwrap returns the original cause of the error. -func (p *ParseError) Unwrap() error { return p.error } - -// ExitCode returns the status that Kong should exit with if it fails with a ParseError. -func (p *ParseError) ExitCode() int { - if p.exitCode == 0 { - return exitNotOk - } - return p.exitCode -} diff --git a/vendor/github.com/alecthomas/kong/exit.go b/vendor/github.com/alecthomas/kong/exit.go deleted file mode 100644 index 4925f48..0000000 --- a/vendor/github.com/alecthomas/kong/exit.go +++ /dev/null @@ -1,32 +0,0 @@ -package kong - -import "errors" - -const ( - exitOk = 0 - exitNotOk = 1 - - // Semantic exit codes from https://github.com/square/exit?tab=readme-ov-file#about - exitUsageError = 80 -) - -// ExitCoder is an interface that may be implemented by an error value to -// provide an integer exit code. The method ExitCode should return an integer -// that is intended to be used as the exit code for the application. -type ExitCoder interface { - ExitCode() int -} - -// exitCodeFromError returns the exit code for the given error. -// If err implements the exitCoder interface, the ExitCode method is called. -// Otherwise, exitCodeFromError returns 0 if err is nil, and 1 if it is not. -func exitCodeFromError(err error) int { - var e ExitCoder - if errors.As(err, &e) { - return e.ExitCode() - } else if err == nil { - return exitOk - } - - return exitNotOk -} diff --git a/vendor/github.com/alecthomas/kong/global.go b/vendor/github.com/alecthomas/kong/global.go deleted file mode 100644 index babe1e1..0000000 --- a/vendor/github.com/alecthomas/kong/global.go +++ /dev/null @@ -1,16 +0,0 @@ -package kong - -import ( - "os" -) - -// Parse constructs a new parser and parses the default command-line. -func Parse(cli any, options ...Option) *Context { - parser, err := New(cli, options...) - if err != nil { - panic(err) - } - ctx, err := parser.Parse(os.Args[1:]) - parser.FatalIfErrorf(err) - return ctx -} diff --git a/vendor/github.com/alecthomas/kong/guesswidth.go b/vendor/github.com/alecthomas/kong/guesswidth.go deleted file mode 100644 index dfdc3f5..0000000 --- a/vendor/github.com/alecthomas/kong/guesswidth.go +++ /dev/null @@ -1,10 +0,0 @@ -//go:build appengine || (!linux && !freebsd && !darwin && !dragonfly && !netbsd && !openbsd) -// +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd - -package kong - -import "io" - -func guessWidth(w io.Writer) int { - return 80 -} diff --git a/vendor/github.com/alecthomas/kong/guesswidth_unix.go b/vendor/github.com/alecthomas/kong/guesswidth_unix.go deleted file mode 100644 index 0170055..0000000 --- a/vendor/github.com/alecthomas/kong/guesswidth_unix.go +++ /dev/null @@ -1,42 +0,0 @@ -//go:build (!appengine && linux) || freebsd || darwin || dragonfly || netbsd || openbsd -// +build !appengine,linux freebsd darwin dragonfly netbsd openbsd - -package kong - -import ( - "io" - "os" - "strconv" - "syscall" - "unsafe" -) - -func guessWidth(w io.Writer) int { - // check if COLUMNS env is set to comply with - // http://pubs.opengroup.org/onlinepubs/009604499/basedefs/xbd_chap08.html - colsStr := os.Getenv("COLUMNS") - if colsStr != "" { - if cols, err := strconv.Atoi(colsStr); err == nil { - return cols - } - } - - if t, ok := w.(*os.File); ok { - fd := t.Fd() - var dimensions [4]uint16 - - if _, _, err := syscall.Syscall6( - syscall.SYS_IOCTL, - uintptr(fd), //nolint: unconvert - uintptr(syscall.TIOCGWINSZ), - uintptr(unsafe.Pointer(&dimensions)), //nolint: gas - 0, 0, 0, - ); err == 0 { - if dimensions[1] == 0 { - return 80 - } - return int(dimensions[1]) - } - } - return 80 -} diff --git a/vendor/github.com/alecthomas/kong/help.go b/vendor/github.com/alecthomas/kong/help.go deleted file mode 100644 index 8da1555..0000000 --- a/vendor/github.com/alecthomas/kong/help.go +++ /dev/null @@ -1,576 +0,0 @@ -package kong - -import ( - "bytes" - "fmt" - "go/doc" - "io" - "strings" -) - -const ( - defaultIndent = 2 - defaultColumnPadding = 4 -) - -// Help flag. -type helpFlag bool - -func (h helpFlag) IgnoreDefault() {} - -func (h helpFlag) BeforeReset(ctx *Context) error { - options := ctx.Kong.helpOptions - options.Summary = false - err := ctx.Kong.help(options, ctx) - if err != nil { - return err - } - ctx.Kong.Exit(0) - return nil -} - -// HelpOptions for HelpPrinters. -type HelpOptions struct { - // Don't print top-level usage summary. - NoAppSummary bool - - // Write a one-line summary of the context. - Summary bool - - // Write help in a more compact, but still fully-specified, form. - Compact bool - - // Tree writes command chains in a tree structure instead of listing them separately. - Tree bool - - // Place the flags after the commands listing. - FlagsLast bool - - // Indenter modulates the given prefix for the next layer in the tree view. - // The following exported templates can be used: kong.SpaceIndenter, kong.LineIndenter, kong.TreeIndenter - // The kong.SpaceIndenter will be used by default. - Indenter HelpIndenter - - // Don't show the help associated with subcommands - NoExpandSubcommands bool - - // Clamp the help wrap width to a value smaller than the terminal width. - // If this is set to a non-positive number, the terminal width is used; otherwise, - // the min of this value or the terminal width is used. - WrapUpperBound int -} - -// Apply options to Kong as a configuration option. -func (h HelpOptions) Apply(k *Kong) error { - k.helpOptions = h - return nil -} - -// HelpProvider can be implemented by commands/args to provide detailed help. -type HelpProvider interface { - // This string is formatted by go/doc and thus has the same formatting rules. - Help() string -} - -// PlaceHolderProvider can be implemented by mappers to provide custom placeholder text. -type PlaceHolderProvider interface { - PlaceHolder(flag *Flag) string -} - -// HelpIndenter is used to indent new layers in the help tree. -type HelpIndenter func(prefix string) string - -// HelpPrinter is used to print context-sensitive help. -type HelpPrinter func(options HelpOptions, ctx *Context) error - -// HelpValueFormatter is used to format the help text of flags and positional arguments. -type HelpValueFormatter func(value *Value) string - -// DefaultHelpValueFormatter is the default HelpValueFormatter. -func DefaultHelpValueFormatter(value *Value) string { - if len(value.Tag.Envs) == 0 || HasInterpolatedVar(value.OrigHelp, "env") { - return value.Help - } - suffix := "(" + formatEnvs(value.Tag.Envs) + ")" - switch { - case strings.HasSuffix(value.Help, "."): - return value.Help[:len(value.Help)-1] + " " + suffix + "." - case value.Help == "": - return suffix - default: - return value.Help + " " + suffix - } -} - -// DefaultShortHelpPrinter is the default HelpPrinter for short help on error. -func DefaultShortHelpPrinter(options HelpOptions, ctx *Context) error { - w := newHelpWriter(ctx, options) - cmd := ctx.Selected() - app := ctx.Model - if cmd == nil { - w.Printf("Usage: %s%s", app.Name, app.Summary()) - w.Printf(`Run "%s --help" for more information.`, app.Name) - } else { - w.Printf("Usage: %s %s", app.Name, cmd.Summary()) - w.Printf(`Run "%s --help" for more information.`, cmd.FullPath()) - } - return w.Write(ctx.Stdout) -} - -// DefaultHelpPrinter is the default HelpPrinter. -func DefaultHelpPrinter(options HelpOptions, ctx *Context) error { - if ctx.Empty() { - options.Summary = false - } - w := newHelpWriter(ctx, options) - selected := ctx.Selected() - if selected == nil { - printApp(w, ctx.Model) - } else { - printCommand(w, ctx.Model, selected) - } - return w.Write(ctx.Stdout) -} - -func printApp(w *helpWriter, app *Application) { - if !w.NoAppSummary { - w.Printf("Usage: %s%s", app.Name, app.Summary()) - } - printNodeDetail(w, app.Node, true) - cmds := app.Leaves(true) - if len(cmds) > 0 && app.HelpFlag != nil { - w.Print("") - if w.Summary { - w.Printf(`Run "%s --help" for more information.`, app.Name) - } else { - w.Printf(`Run "%s --help" for more information on a command.`, app.Name) - } - } -} - -func printCommand(w *helpWriter, app *Application, cmd *Command) { - if !w.NoAppSummary { - w.Printf("Usage: %s %s", app.Name, cmd.Summary()) - } - printNodeDetail(w, cmd, true) - if w.Summary && app.HelpFlag != nil { - w.Print("") - w.Printf(`Run "%s --help" for more information.`, cmd.FullPath()) - } -} - -func printNodeDetail(w *helpWriter, node *Node, hide bool) { - if node.Help != "" { - w.Print("") - w.Wrap(node.Help) - } - if w.Summary { - return - } - if node.Detail != "" { - w.Print("") - w.Wrap(node.Detail) - } - if len(node.Positional) > 0 { - w.Print("") - w.Print("Arguments:") - writePositionals(w.Indent(), node.Positional) - } - printFlags := func() { - if flags := node.AllFlags(true); len(flags) > 0 { - groupedFlags := collectFlagGroups(flags) - for _, group := range groupedFlags { - w.Print("") - if group.Metadata.Title != "" { - w.Wrap(group.Metadata.Title) - } - if group.Metadata.Description != "" { - w.Indent().Wrap(group.Metadata.Description) - w.Print("") - } - writeFlags(w.Indent(), group.Flags) - } - } - } - if !w.FlagsLast { - printFlags() - } - var cmds []*Node - if w.NoExpandSubcommands { - cmds = node.Children - } else { - cmds = node.Leaves(hide) - } - if len(cmds) > 0 { - iw := w.Indent() - if w.Tree { - w.Print("") - w.Print("Commands:") - writeCommandTree(iw, node) - } else { - groupedCmds := collectCommandGroups(cmds) - for _, group := range groupedCmds { - w.Print("") - if group.Metadata.Title != "" { - w.Wrap(group.Metadata.Title) - } - if group.Metadata.Description != "" { - w.Indent().Wrap(group.Metadata.Description) - w.Print("") - } - - if w.Compact { - writeCompactCommandList(group.Commands, iw) - } else { - writeCommandList(group.Commands, iw) - } - } - } - } - if w.FlagsLast { - printFlags() - } -} - -func writeCommandList(cmds []*Node, iw *helpWriter) { - for i, cmd := range cmds { - if cmd.Hidden { - continue - } - printCommandSummary(iw, cmd) - if i != len(cmds)-1 { - iw.Print("") - } - } -} - -func writeCompactCommandList(cmds []*Node, iw *helpWriter) { - rows := [][2]string{} - for _, cmd := range cmds { - if cmd.Hidden { - continue - } - rows = append(rows, [2]string{cmd.Path(), cmd.Help}) - } - writeTwoColumns(iw, rows) -} - -func writeCommandTree(w *helpWriter, node *Node) { - rows := make([][2]string, 0, len(node.Children)*2) - for i, cmd := range node.Children { - if cmd.Hidden { - continue - } - rows = append(rows, w.CommandTree(cmd, "")...) - if i != len(node.Children)-1 { - rows = append(rows, [2]string{"", ""}) - } - } - writeTwoColumns(w, rows) -} - -type helpFlagGroup struct { - Metadata *Group - Flags [][]*Flag -} - -func collectFlagGroups(flags [][]*Flag) []helpFlagGroup { - // Group keys in order of appearance. - groups := []*Group{} - // Flags grouped by their group key. - flagsByGroup := map[string][][]*Flag{} - - for _, levelFlags := range flags { - levelFlagsByGroup := map[string][]*Flag{} - - for _, flag := range levelFlags { - key := "" - if flag.Group != nil { - key = flag.Group.Key - groupAlreadySeen := false - for _, group := range groups { - if key == group.Key { - groupAlreadySeen = true - break - } - } - if !groupAlreadySeen { - groups = append(groups, flag.Group) - } - } - - levelFlagsByGroup[key] = append(levelFlagsByGroup[key], flag) - } - - for key, flags := range levelFlagsByGroup { - flagsByGroup[key] = append(flagsByGroup[key], flags) - } - } - - out := []helpFlagGroup{} - // Ungrouped flags are always displayed first. - if ungroupedFlags, ok := flagsByGroup[""]; ok { - out = append(out, helpFlagGroup{ - Metadata: &Group{Title: "Flags:"}, - Flags: ungroupedFlags, - }) - } - for _, group := range groups { - out = append(out, helpFlagGroup{Metadata: group, Flags: flagsByGroup[group.Key]}) - } - return out -} - -type helpCommandGroup struct { - Metadata *Group - Commands []*Node -} - -func collectCommandGroups(nodes []*Node) []helpCommandGroup { - // Groups in order of appearance. - groups := []*Group{} - // Nodes grouped by their group key. - nodesByGroup := map[string][]*Node{} - - for _, node := range nodes { - key := "" - if group := node.ClosestGroup(); group != nil { - key = group.Key - if _, ok := nodesByGroup[key]; !ok { - groups = append(groups, group) - } - } - nodesByGroup[key] = append(nodesByGroup[key], node) - } - - out := []helpCommandGroup{} - // Ungrouped nodes are always displayed first. - if ungroupedNodes, ok := nodesByGroup[""]; ok { - out = append(out, helpCommandGroup{ - Metadata: &Group{Title: "Commands:"}, - Commands: ungroupedNodes, - }) - } - for _, group := range groups { - out = append(out, helpCommandGroup{Metadata: group, Commands: nodesByGroup[group.Key]}) - } - return out -} - -func printCommandSummary(w *helpWriter, cmd *Command) { - w.Print(cmd.Summary()) - if cmd.Help != "" { - w.Indent().Wrap(cmd.Help) - } -} - -type helpWriter struct { - indent string - width int - lines *[]string - helpFormatter HelpValueFormatter - HelpOptions -} - -func newHelpWriter(ctx *Context, options HelpOptions) *helpWriter { - lines := []string{} - wrapWidth := guessWidth(ctx.Stdout) - if options.WrapUpperBound > 0 && wrapWidth > options.WrapUpperBound { - wrapWidth = options.WrapUpperBound - } - w := &helpWriter{ - indent: "", - width: wrapWidth, - lines: &lines, - helpFormatter: ctx.Kong.helpFormatter, - HelpOptions: options, - } - return w -} - -func (h *helpWriter) Printf(format string, args ...any) { - h.Print(fmt.Sprintf(format, args...)) -} - -func (h *helpWriter) Print(text string) { - *h.lines = append(*h.lines, strings.TrimRight(h.indent+text, " ")) -} - -// Indent returns a new helpWriter indented by two characters. -func (h *helpWriter) Indent() *helpWriter { - return &helpWriter{indent: h.indent + " ", lines: h.lines, width: h.width - 2, HelpOptions: h.HelpOptions, helpFormatter: h.helpFormatter} -} - -func (h *helpWriter) String() string { - return strings.Join(*h.lines, "\n") -} - -func (h *helpWriter) Write(w io.Writer) error { - for _, line := range *h.lines { - _, err := io.WriteString(w, line+"\n") - if err != nil { - return err - } - } - return nil -} - -func (h *helpWriter) Wrap(text string) { - w := bytes.NewBuffer(nil) - doc.ToText(w, strings.TrimSpace(text), "", " ", h.width) //nolint:staticcheck // cross-package links not possible - for _, line := range strings.Split(strings.TrimSpace(w.String()), "\n") { - h.Print(line) - } -} - -func writePositionals(w *helpWriter, args []*Positional) { - rows := [][2]string{} - for _, arg := range args { - rows = append(rows, [2]string{arg.Summary(), w.helpFormatter(arg)}) - } - writeTwoColumns(w, rows) -} - -func writeFlags(w *helpWriter, groups [][]*Flag) { - rows := [][2]string{} - haveShort := false - for _, group := range groups { - for _, flag := range group { - if flag.Short != 0 { - haveShort = true - break - } - } - } - for i, group := range groups { - if i > 0 { - rows = append(rows, [2]string{"", ""}) - } - for _, flag := range group { - if !flag.Hidden { - rows = append(rows, [2]string{formatFlag(haveShort, flag), w.helpFormatter(flag.Value)}) - } - } - } - writeTwoColumns(w, rows) -} - -func writeTwoColumns(w *helpWriter, rows [][2]string) { - maxLeft := 375 * w.width / 1000 - if maxLeft < 30 { - maxLeft = 30 - } - // Find size of first column. - leftSize := 0 - for _, row := range rows { - if c := len(row[0]); c > leftSize && c < maxLeft { - leftSize = c - } - } - - offsetStr := strings.Repeat(" ", leftSize+defaultColumnPadding) - - for _, row := range rows { - buf := bytes.NewBuffer(nil) - doc.ToText(buf, row[1], "", strings.Repeat(" ", defaultIndent), w.width-leftSize-defaultColumnPadding) //nolint:staticcheck // cross-package links not possible - lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") - - line := fmt.Sprintf("%-*s", leftSize, row[0]) - if len(row[0]) < maxLeft { - line += fmt.Sprintf("%*s%s", defaultColumnPadding, "", lines[0]) - lines = lines[1:] - } - w.Print(line) - for _, line := range lines { - w.Printf("%s%s", offsetStr, line) - } - } -} - -// haveShort will be true if there are short flags present at all in the help. Useful for column alignment. -func formatFlag(haveShort bool, flag *Flag) string { - flagString := "" - name := flag.Name - isBool := flag.IsBool() - isCounter := flag.IsCounter() - - short := "" - if flag.Short != 0 { - short = "-" + string(flag.Short) + ", " - } else if haveShort { - short = " " - } - - if isBool && flag.Tag.Negatable == negatableDefault { - name = "[no-]" + name - } else if isBool && flag.Tag.Negatable != "" { - name += "/" + flag.Tag.Negatable - } - - flagString += fmt.Sprintf("%s--%s", short, name) - - if !isBool && !isCounter { - flagString += fmt.Sprintf("=%s", flag.FormatPlaceHolder()) - } - return flagString -} - -// CommandTree creates a tree with the given node name as root and its children's arguments and sub commands as leaves. -func (h *HelpOptions) CommandTree(node *Node, prefix string) (rows [][2]string) { - var nodeName string - switch node.Type { - default: - nodeName += prefix + node.Name - if len(node.Aliases) != 0 { - nodeName += fmt.Sprintf(" (%s)", strings.Join(node.Aliases, ",")) - } - case ArgumentNode: - nodeName += prefix + "<" + node.Name + ">" - } - rows = append(rows, [2]string{nodeName, node.Help}) - if h.Indenter == nil { - prefix = SpaceIndenter(prefix) - } else { - prefix = h.Indenter(prefix) - } - for _, arg := range node.Positional { - rows = append(rows, [2]string{prefix + arg.Summary(), arg.Help}) - } - for _, subCmd := range node.Children { - if subCmd.Hidden { - continue - } - rows = append(rows, h.CommandTree(subCmd, prefix)...) - } - return -} - -// SpaceIndenter adds a space indent to the given prefix. -func SpaceIndenter(prefix string) string { - return prefix + strings.Repeat(" ", defaultIndent) -} - -// LineIndenter adds line points to every new indent. -func LineIndenter(prefix string) string { - if prefix == "" { - return "- " - } - return strings.Repeat(" ", defaultIndent) + prefix -} - -// TreeIndenter adds line points to every new indent and vertical lines to every layer. -func TreeIndenter(prefix string) string { - if prefix == "" { - return "|- " - } - return "|" + strings.Repeat(" ", defaultIndent) + prefix -} - -func formatEnvs(envs []string) string { - formatted := make([]string, len(envs)) - for i := range envs { - formatted[i] = "$" + envs[i] - } - - return strings.Join(formatted, ", ") -} diff --git a/vendor/github.com/alecthomas/kong/hooks.go b/vendor/github.com/alecthomas/kong/hooks.go deleted file mode 100644 index e95d21b..0000000 --- a/vendor/github.com/alecthomas/kong/hooks.go +++ /dev/null @@ -1,32 +0,0 @@ -package kong - -// BeforeReset is a documentation-only interface describing hooks that run before defaults values are applied. -type BeforeReset interface { - // This is not the correct signature - see README for details. - BeforeReset(args ...any) error -} - -// BeforeResolve is a documentation-only interface describing hooks that run before resolvers are applied. -type BeforeResolve interface { - // This is not the correct signature - see README for details. - BeforeResolve(args ...any) error -} - -// BeforeApply is a documentation-only interface describing hooks that run before values are set. -type BeforeApply interface { - // This is not the correct signature - see README for details. - BeforeApply(args ...any) error -} - -// AfterApply is a documentation-only interface describing hooks that run after values are set. -type AfterApply interface { - // This is not the correct signature - see README for details. - AfterApply(args ...any) error -} - -// AfterRun is a documentation-only interface describing hooks that run after Run() returns. -type AfterRun interface { - // This is not the correct signature - see README for details. - // AfterRun is called after Run() returns. - AfterRun(args ...any) error -} diff --git a/vendor/github.com/alecthomas/kong/interpolate.go b/vendor/github.com/alecthomas/kong/interpolate.go deleted file mode 100644 index e811632..0000000 --- a/vendor/github.com/alecthomas/kong/interpolate.go +++ /dev/null @@ -1,52 +0,0 @@ -package kong - -import ( - "fmt" - "regexp" -) - -var interpolationRegex = regexp.MustCompile(`(\$\$)|((?:\${([[:alpha:]_][[:word:]]*))(?:=([^}]+))?})|(\$)|([^$]+)`) - -// HasInterpolatedVar returns true if the variable "v" is interpolated in "s". -func HasInterpolatedVar(s string, v string) bool { - matches := interpolationRegex.FindAllStringSubmatch(s, -1) - for _, match := range matches { - if name := match[3]; name == v { - return true - } - } - return false -} - -// Interpolate variables from vars into s for substrings in the form ${var} or ${var=default}. -func interpolate(s string, vars Vars, updatedVars map[string]string) (string, error) { - out := "" - matches := interpolationRegex.FindAllStringSubmatch(s, -1) - if len(matches) == 0 { - return s, nil - } - for key, val := range updatedVars { - if vars[key] != val { - vars = vars.CloneWith(updatedVars) - break - } - } - for _, match := range matches { - if dollar := match[1]; dollar != "" { - out += "$" - } else if name := match[3]; name != "" { - value, ok := vars[name] - if !ok { - // No default value. - if match[4] == "" { - return "", fmt.Errorf("undefined variable ${%s}", name) - } - value = match[4] - } - out += value - } else { - out += match[0] - } - } - return out, nil -} diff --git a/vendor/github.com/alecthomas/kong/kong.go b/vendor/github.com/alecthomas/kong/kong.go deleted file mode 100644 index 2334a8a..0000000 --- a/vendor/github.com/alecthomas/kong/kong.go +++ /dev/null @@ -1,500 +0,0 @@ -package kong - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "reflect" - "regexp" - "strings" -) - -var ( - callbackReturnSignature = reflect.TypeOf((*error)(nil)).Elem() -) - -func failField(parent reflect.Value, field reflect.StructField, format string, args ...any) error { - name := parent.Type().Name() - if name == "" { - name = "" - } - return fmt.Errorf("%s.%s: %s", name, field.Name, fmt.Sprintf(format, args...)) -} - -// Must creates a new Parser or panics if there is an error. -func Must(ast any, options ...Option) *Kong { - k, err := New(ast, options...) - if err != nil { - panic(err) - } - return k -} - -type usageOnError int - -const ( - shortUsage usageOnError = iota + 1 - fullUsage -) - -// Kong is the main parser type. -type Kong struct { - // Grammar model. - Model *Application - - // Termination function (defaults to os.Exit) - Exit func(int) - - Stdout io.Writer - Stderr io.Writer - - bindings bindings - loader ConfigurationLoader - resolvers []Resolver - registry *Registry - ignoreFields []*regexp.Regexp - - noDefaultHelp bool - allowHyphenated bool - usageOnError usageOnError - help HelpPrinter - shortHelp HelpPrinter - helpFormatter HelpValueFormatter - helpOptions HelpOptions - helpFlag *Flag - groups []Group - vars Vars - flagNamer func(string) string - - // Set temporarily by Options. These are applied after build(). - postBuildOptions []Option - embedded []embedded - dynamicCommands []*dynamicCommand - - hooks map[string][]reflect.Value -} - -// New creates a new Kong parser on grammar. -// -// See the README (https://github.com/alecthomas/kong) for usage instructions. -func New(grammar any, options ...Option) (*Kong, error) { - k := &Kong{ - Exit: os.Exit, - Stdout: os.Stdout, - Stderr: os.Stderr, - registry: NewRegistry().RegisterDefaults(), - vars: Vars{}, - bindings: bindings{}, - hooks: make(map[string][]reflect.Value), - helpFormatter: DefaultHelpValueFormatter, - ignoreFields: make([]*regexp.Regexp, 0), - flagNamer: func(s string) string { - return strings.ToLower(dashedString(s)) - }, - } - - options = append(options, Bind(k)) - - for _, option := range options { - if err := option.Apply(k); err != nil { - return nil, err - } - } - - if k.help == nil { - k.help = DefaultHelpPrinter - } - - if k.shortHelp == nil { - k.shortHelp = DefaultShortHelpPrinter - } - - model, err := build(k, grammar) - if err != nil { - return k, err - } - model.Name = filepath.Base(os.Args[0]) - k.Model = model - k.Model.HelpFlag = k.helpFlag - - // Embed any embedded structs. - for _, embed := range k.embedded { - tag, err := parseTagString(strings.Join(embed.tags, " ")) - if err != nil { - return nil, err - } - tag.Embed = true - v := reflect.Indirect(reflect.ValueOf(embed.strct)) - node, err := buildNode(k, v, CommandNode, tag, map[string]bool{}) - if err != nil { - return nil, err - } - for _, child := range node.Children { - child.Parent = k.Model.Node - k.Model.Children = append(k.Model.Children, child) - } - k.Model.Flags = append(k.Model.Flags, node.Flags...) - } - - // Synthesise command nodes. - for _, dcmd := range k.dynamicCommands { - tag, terr := parseTagString(strings.Join(dcmd.tags, " ")) - if terr != nil { - return nil, terr - } - tag.Name = dcmd.name - tag.Help = dcmd.help - tag.Group = dcmd.group - tag.Cmd = true - v := reflect.Indirect(reflect.ValueOf(dcmd.cmd)) - err = buildChild(k, k.Model.Node, CommandNode, reflect.Value{}, reflect.StructField{ - Name: dcmd.name, - Type: v.Type(), - }, v, tag, dcmd.name, map[string]bool{}) - if err != nil { - return nil, err - } - } - - for _, option := range k.postBuildOptions { - if err = option.Apply(k); err != nil { - return nil, err - } - } - k.postBuildOptions = nil - - if err = k.interpolate(k.Model.Node); err != nil { - return nil, err - } - - k.bindings.add(k.vars) - - if err = checkOverlappingXorAnd(k); err != nil { - return nil, err - } - - return k, nil -} - -func checkOverlappingXorAnd(k *Kong) error { - xorGroups := map[string][]string{} - andGroups := map[string][]string{} - for _, flag := range k.Model.Node.Flags { - for _, xor := range flag.Xor { - xorGroups[xor] = append(xorGroups[xor], flag.Name) - } - for _, and := range flag.And { - andGroups[and] = append(andGroups[and], flag.Name) - } - } - for xor, xorSet := range xorGroups { - for and, andSet := range andGroups { - overlappingEntries := []string{} - for _, xorTag := range xorSet { - for _, andTag := range andSet { - if xorTag == andTag { - overlappingEntries = append(overlappingEntries, xorTag) - } - } - } - if len(overlappingEntries) > 1 { - return fmt.Errorf("invalid xor and combination, %s and %s overlap with more than one: %s", xor, and, overlappingEntries) - } - } - } - return nil -} - -type varStack []Vars - -func (v *varStack) head() Vars { return (*v)[len(*v)-1] } -func (v *varStack) pop() { *v = (*v)[:len(*v)-1] } -func (v *varStack) push(vars Vars) Vars { - if len(*v) != 0 { - vars = (*v)[len(*v)-1].CloneWith(vars) - } - *v = append(*v, vars) - return vars -} - -// Interpolate variables into model. -func (k *Kong) interpolate(node *Node) (err error) { - stack := varStack{} - return Visit(node, func(node Visitable, next Next) error { - switch node := node.(type) { - case *Node: - vars := stack.push(node.Vars()) - node.Help, err = interpolate(node.Help, vars, nil) - if err != nil { - return fmt.Errorf("help for %s: %s", node.Path(), err) - } - err = next(nil) - stack.pop() - return err - - case *Value: - return next(k.interpolateValue(node, stack.head())) - } - return next(nil) - }) -} - -func (k *Kong) interpolateValue(value *Value, vars Vars) (err error) { - if len(value.Tag.Vars) > 0 { - vars = vars.CloneWith(value.Tag.Vars) - } - if varsContributor, ok := value.Mapper.(VarsContributor); ok { - vars = vars.CloneWith(varsContributor.Vars(value)) - } - - if value.Enum, err = interpolate(value.Enum, vars, nil); err != nil { - return fmt.Errorf("enum for %s: %s", value.Summary(), err) - } - - if value.Default, err = interpolate(value.Default, vars, nil); err != nil { - return fmt.Errorf("default value for %s: %s", value.Summary(), err) - } - if value.Enum, err = interpolate(value.Enum, vars, nil); err != nil { - return fmt.Errorf("enum value for %s: %s", value.Summary(), err) - } - updatedVars := map[string]string{ - "default": value.Default, - "enum": value.Enum, - } - if value.Flag != nil { - for i, env := range value.Flag.Envs { - if value.Flag.Envs[i], err = interpolate(env, vars, updatedVars); err != nil { - return fmt.Errorf("env value for %s: %s", value.Summary(), err) - } - } - value.Tag.Envs = value.Flag.Envs - updatedVars["env"] = "" - if len(value.Flag.Envs) != 0 { - updatedVars["env"] = value.Flag.Envs[0] - } - - value.Flag.PlaceHolder, err = interpolate(value.Flag.PlaceHolder, vars, updatedVars) - if err != nil { - return fmt.Errorf("placeholder value for %s: %s", value.Summary(), err) - } - } - value.Help, err = interpolate(value.Help, vars, updatedVars) - if err != nil { - return fmt.Errorf("help for %s: %s", value.Summary(), err) - } - return nil -} - -// Provide additional builtin flags, if any. -func (k *Kong) extraFlags() []*Flag { - if k.noDefaultHelp { - return nil - } - var helpTarget helpFlag - value := reflect.ValueOf(&helpTarget).Elem() - helpFlag := &Flag{ - Short: 'h', - Value: &Value{ - Name: "help", - Help: "Show context-sensitive help.", - OrigHelp: "Show context-sensitive help.", - Target: value, - Tag: &Tag{}, - Mapper: k.registry.ForValue(value), - DefaultValue: reflect.ValueOf(false), - }, - } - helpFlag.Flag = helpFlag - k.helpFlag = helpFlag - return []*Flag{helpFlag} -} - -// Parse arguments into target. -// -// The return Context can be used to further inspect the parsed command-line, to format help, to find the -// selected command, to run command Run() methods, and so on. See Context and README for more information. -// -// Will return a ParseError if a *semantically* invalid command-line is encountered (as opposed to a syntactically -// invalid one, which will report a normal error). -func (k *Kong) Parse(args []string) (ctx *Context, err error) { - ctx, err = Trace(k, args) - if err != nil { // Trace is not expected to return an err - return nil, &ParseError{error: err, Context: ctx, exitCode: exitUsageError} - } - if ctx.Error != nil { - return nil, &ParseError{error: ctx.Error, Context: ctx, exitCode: exitUsageError} - } - if err = k.applyHook(ctx, "BeforeReset"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = ctx.Reset(); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = k.applyHook(ctx, "BeforeResolve"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = ctx.Resolve(); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = k.applyHook(ctx, "BeforeApply"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if _, err = ctx.Apply(); err != nil { // Apply is not expected to return an err - return nil, &ParseError{error: err, Context: ctx} - } - if err = ctx.Validate(); err != nil { - return nil, &ParseError{error: err, Context: ctx, exitCode: exitUsageError} - } - if err = k.applyHook(ctx, "AfterApply"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - return ctx, nil -} - -func (k *Kong) applyHook(ctx *Context, name string) error { - for _, trace := range ctx.Path { - var value reflect.Value - switch { - case trace.App != nil: - value = trace.App.Target - case trace.Argument != nil: - value = trace.Argument.Target - case trace.Command != nil: - value = trace.Command.Target - case trace.Positional != nil: - value = trace.Positional.Target - case trace.Flag != nil: - value = trace.Flag.Value.Target - default: - panic("unsupported Path") - } - for _, method := range k.getMethods(value, name) { - binds := k.bindings.clone() - binds.add(ctx, trace) - binds.add(trace.Node().Vars().CloneWith(k.vars)) - binds.merge(ctx.bindings) - if err := callFunction(method, binds); err != nil { - return err - } - } - } - // Path[0] will always be the app root. - return k.applyHookToDefaultFlags(ctx, ctx.Path[0].Node(), name) -} - -func (k *Kong) getMethods(value reflect.Value, name string) []reflect.Value { - return append( - // Identify callbacks by reflecting on value - getMethods(value, name), - - // Identify callbacks that were registered with a kong.Option - k.hooks[name]..., - ) -} - -// Call hook on any unset flags with default values. -func (k *Kong) applyHookToDefaultFlags(ctx *Context, node *Node, name string) error { - if node == nil { - return nil - } - return Visit(node, func(n Visitable, next Next) error { - node, ok := n.(*Node) - if !ok { - return next(nil) - } - binds := k.bindings.clone().add(ctx).add(node.Vars().CloneWith(k.vars)) - for _, flag := range node.Flags { - if !flag.HasDefault || ctx.values[flag.Value].IsValid() || !flag.Target.IsValid() { - continue - } - for _, method := range getMethods(flag.Target, name) { - path := &Path{Flag: flag} - if err := callFunction(method, binds.clone().add(path)); err != nil { - return next(err) - } - } - } - return next(nil) - }) -} - -func formatMultilineMessage(w io.Writer, leaders []string, format string, args ...any) { - lines := strings.Split(strings.TrimRight(fmt.Sprintf(format, args...), "\n"), "\n") - leader := "" - for _, l := range leaders { - if l == "" { - continue - } - leader += l + ": " - } - fmt.Fprintf(w, "%s%s\n", leader, lines[0]) - for _, line := range lines[1:] { - fmt.Fprintf(w, "%*s%s\n", len(leader), " ", line) - } -} - -// Printf writes a message to Kong.Stdout with the application name prefixed. -func (k *Kong) Printf(format string, args ...any) *Kong { - formatMultilineMessage(k.Stdout, []string{k.Model.Name}, format, args...) - return k -} - -// Errorf writes a message to Kong.Stderr with the application name prefixed. -func (k *Kong) Errorf(format string, args ...any) *Kong { - formatMultilineMessage(k.Stderr, []string{k.Model.Name, "error"}, format, args...) - return k -} - -// Fatalf writes a message to Kong.Stderr with the application name prefixed then exits with status 1. -func (k *Kong) Fatalf(format string, args ...any) { - k.Errorf(format, args...) - k.Exit(1) -} - -// FatalIfErrorf terminates with an error message if err != nil. -// If the error implements the ExitCoder interface, the ExitCode() method is called and -// the application exits with that status. Otherwise, the application exits with status 1. -func (k *Kong) FatalIfErrorf(err error, args ...any) { - if err == nil { - return - } - msg := err.Error() - if len(args) > 0 { - msg = fmt.Sprintf(args[0].(string), args[1:]...) + ": " + err.Error() //nolint - } - // Maybe display usage information. - var parseErr *ParseError - if errors.As(err, &parseErr) { - switch k.usageOnError { - case fullUsage: - _ = k.help(k.helpOptions, parseErr.Context) - fmt.Fprintln(k.Stdout) - case shortUsage: - _ = k.shortHelp(k.helpOptions, parseErr.Context) - fmt.Fprintln(k.Stdout) - } - } - k.Errorf("%s", msg) - k.Exit(exitCodeFromError(err)) -} - -// LoadConfig from path using the loader configured via Configuration(loader). -// -// "path" will have ~ and any variables expanded. -func (k *Kong) LoadConfig(path string) (Resolver, error) { - var err error - path = ExpandPath(path) - path, err = interpolate(path, k.vars, nil) - if err != nil { - return nil, err - } - r, err := os.Open(path) //nolint: gas - if err != nil { - return nil, err - } - defer r.Close() - - return k.loader(r) -} diff --git a/vendor/github.com/alecthomas/kong/kong.png b/vendor/github.com/alecthomas/kong/kong.png deleted file mode 100644 index 151fb08..0000000 Binary files a/vendor/github.com/alecthomas/kong/kong.png and /dev/null differ diff --git a/vendor/github.com/alecthomas/kong/kong.sketch b/vendor/github.com/alecthomas/kong/kong.sketch deleted file mode 100644 index 38816d5..0000000 Binary files a/vendor/github.com/alecthomas/kong/kong.sketch and /dev/null differ diff --git a/vendor/github.com/alecthomas/kong/lefthook.yml b/vendor/github.com/alecthomas/kong/lefthook.yml deleted file mode 100644 index 28ba9ad..0000000 --- a/vendor/github.com/alecthomas/kong/lefthook.yml +++ /dev/null @@ -1,11 +0,0 @@ -output: - - success - - failure -pre-push: - parallel: true - jobs: - - name: test - run: go test -v ./... - - - name: lint - run: golangci-lint run diff --git a/vendor/github.com/alecthomas/kong/levenshtein.go b/vendor/github.com/alecthomas/kong/levenshtein.go deleted file mode 100644 index 6837d6c..0000000 --- a/vendor/github.com/alecthomas/kong/levenshtein.go +++ /dev/null @@ -1,39 +0,0 @@ -package kong - -import "unicode/utf8" - -// https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Go -// License: https://creativecommons.org/licenses/by-sa/3.0/ -func levenshtein(a, b string) int { - f := make([]int, utf8.RuneCountInString(b)+1) - - for j := range f { - f[j] = j - } - - for _, ca := range a { - j := 1 - fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration - f[0]++ - for _, cb := range b { - mn := min(f[j]+1, f[j-1]+1) // delete & insert - if cb != ca { - mn = min(mn, fj1+1) // change - } else { - mn = min(mn, fj1) // matched - } - - fj1, f[j] = f[j], mn // save f[j] to fj1(j is about to increase), update f[j] to mn - j++ - } - } - - return f[len(f)-1] -} - -func min(a, b int) int { //nolint:predeclared - if a <= b { - return a - } - return b -} diff --git a/vendor/github.com/alecthomas/kong/mapper.go b/vendor/github.com/alecthomas/kong/mapper.go deleted file mode 100644 index 7e97836..0000000 --- a/vendor/github.com/alecthomas/kong/mapper.go +++ /dev/null @@ -1,934 +0,0 @@ -package kong - -import ( - "encoding" - "encoding/json" - "errors" - "fmt" - "io" - "math/bits" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "time" -) - -var ( - mapperValueType = reflect.TypeOf((*MapperValue)(nil)).Elem() - boolMapperValueType = reflect.TypeOf((*BoolMapperValue)(nil)).Elem() - jsonUnmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() - textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - binaryUnmarshalerType = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() -) - -// DecodeContext is passed to a Mapper's Decode(). -// -// It contains the Value being decoded into and the Scanner to parse from. -type DecodeContext struct { - // Value being decoded into. - Value *Value - // Scan contains the input to scan into Target. - Scan *Scanner -} - -// WithScanner creates a clone of this context with a new Scanner. -func (r *DecodeContext) WithScanner(scan *Scanner) *DecodeContext { - return &DecodeContext{ - Value: r.Value, - Scan: scan, - } -} - -// MapperValue may be implemented by fields in order to provide custom mapping. -// Mappers may additionally implement PlaceHolderProvider to provide custom placeholder text. -type MapperValue interface { - Decode(ctx *DecodeContext) error -} - -// BoolMapperValue may be implemented by fields in order to provide custom mappings for boolean values. -type BoolMapperValue interface { - MapperValue - IsBool() bool -} - -type mapperValueAdapter struct { - isBool bool -} - -func (m *mapperValueAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - if target.Type().Implements(mapperValueType) { - return target.Interface().(MapperValue).Decode(ctx) //nolint - } - return target.Addr().Interface().(MapperValue).Decode(ctx) //nolint -} - -func (m *mapperValueAdapter) IsBool() bool { - return m.isBool -} - -type textUnmarshalerAdapter struct{} - -func (m *textUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - var value string - err := ctx.Scan.PopValueInto("value", &value) - if err != nil { - return err - } - if target.Type().Implements(textUnmarshalerType) { - return target.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) //nolint - } - return target.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) //nolint -} - -type binaryUnmarshalerAdapter struct{} - -func (m *binaryUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - var value string - err := ctx.Scan.PopValueInto("value", &value) - if err != nil { - return err - } - if target.Type().Implements(binaryUnmarshalerType) { - return target.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) //nolint - } - return target.Addr().Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) //nolint -} - -type jsonUnmarshalerAdapter struct{} - -func (j *jsonUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - var value string - err := ctx.Scan.PopValueInto("value", &value) - if err != nil { - return err - } - if target.Type().Implements(jsonUnmarshalerType) { - return target.Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) //nolint - } - return target.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) //nolint -} - -// A Mapper represents how a field is mapped from command-line values to Go. -// -// Mappers can be associated with concrete fields via pointer, reflect.Type, reflect.Kind, or via a "type" tag. -// -// Additionally, if a type implements the MapperValue interface, it will be used. -type Mapper interface { - // Decode ctx.Value with ctx.Scanner into target. - Decode(ctx *DecodeContext, target reflect.Value) error -} - -// VarsContributor can be implemented by a Mapper to contribute Vars during interpolation. -type VarsContributor interface { - Vars(ctx *Value) Vars -} - -// A BoolMapper is a Mapper to a value that is a boolean. -// -// This is used solely for formatting help. -type BoolMapper interface { - Mapper - IsBool() bool -} - -// BoolMapperExt allows a Mapper to dynamically determine if a value is a boolean. -type BoolMapperExt interface { - Mapper - IsBoolFromValue(v reflect.Value) bool -} - -// A MapperFunc is a single function that complies with the Mapper interface. -type MapperFunc func(ctx *DecodeContext, target reflect.Value) error - -func (m MapperFunc) Decode(ctx *DecodeContext, target reflect.Value) error { //nolint: revive - return m(ctx, target) -} - -// A Registry contains a set of mappers and supporting lookup methods. -type Registry struct { - names map[string]Mapper - types map[reflect.Type]Mapper - kinds map[reflect.Kind]Mapper - values map[reflect.Value]Mapper -} - -// NewRegistry creates a new (empty) Registry. -func NewRegistry() *Registry { - return &Registry{ - names: map[string]Mapper{}, - types: map[reflect.Type]Mapper{}, - kinds: map[reflect.Kind]Mapper{}, - values: map[reflect.Value]Mapper{}, - } -} - -// ForNamedValue finds a mapper for a value with a user-specified name. -// -// Will return nil if a mapper can not be determined. -func (r *Registry) ForNamedValue(name string, value reflect.Value) Mapper { - if mapper, ok := r.names[name]; ok { - return mapper - } - return r.ForValue(value) -} - -// ForValue looks up the Mapper for a reflect.Value. -func (r *Registry) ForValue(value reflect.Value) Mapper { - if mapper, ok := r.values[value]; ok { - return mapper - } - return r.ForType(value.Type()) -} - -// ForNamedType finds a mapper for a type with a user-specified name. -// -// Will return nil if a mapper can not be determined. -func (r *Registry) ForNamedType(name string, typ reflect.Type) Mapper { - if mapper, ok := r.names[name]; ok { - return mapper - } - return r.ForType(typ) -} - -// ForType finds a mapper from a type, by type, then kind. -// -// Will return nil if a mapper can not be determined. -func (r *Registry) ForType(typ reflect.Type) Mapper { - // Check if the type implements MapperValue. - for _, impl := range []reflect.Type{typ, reflect.PtrTo(typ)} { - if impl.Implements(mapperValueType) { - // FIXME: This should pass in the bool mapper. - return &mapperValueAdapter{impl.Implements(boolMapperValueType)} - } - } - // Next, try explicitly registered types. - var mapper Mapper - var ok bool - if mapper, ok = r.types[typ]; ok { - return mapper - } - // Next try stdlib unmarshaler interfaces. - for _, impl := range []reflect.Type{typ, reflect.PtrTo(typ)} { - switch { - case impl.Implements(textUnmarshalerType): - return &textUnmarshalerAdapter{} - case impl.Implements(binaryUnmarshalerType): - return &binaryUnmarshalerAdapter{} - case impl.Implements(jsonUnmarshalerType): - return &jsonUnmarshalerAdapter{} - } - } - // Finally try registered kinds. - if mapper, ok = r.kinds[typ.Kind()]; ok { - return mapper - } - return nil -} - -// RegisterKind registers a Mapper for a reflect.Kind. -func (r *Registry) RegisterKind(kind reflect.Kind, mapper Mapper) *Registry { - r.kinds[kind] = mapper - return r -} - -// RegisterName registers a mapper to be used if the value mapper has a "type" tag matching name. -// -// eg. -// -// Mapper string `kong:"type='colour'` -// registry.RegisterName("colour", ...) -func (r *Registry) RegisterName(name string, mapper Mapper) *Registry { - r.names[name] = mapper - return r -} - -// RegisterType registers a Mapper for a reflect.Type. -func (r *Registry) RegisterType(typ reflect.Type, mapper Mapper) *Registry { - r.types[typ] = mapper - return r -} - -// RegisterValue registers a Mapper by pointer to the field value. -func (r *Registry) RegisterValue(ptr any, mapper Mapper) *Registry { - key := reflect.ValueOf(ptr) - if key.Kind() != reflect.Ptr { - panic("expected a pointer") - } - key = key.Elem() - r.values[key] = mapper - return r -} - -// RegisterDefaults registers Mappers for all builtin supported Go types and some common stdlib types. -func (r *Registry) RegisterDefaults() *Registry { - return r.RegisterKind(reflect.Int, intDecoder(bits.UintSize)). - RegisterKind(reflect.Int8, intDecoder(8)). - RegisterKind(reflect.Int16, intDecoder(16)). - RegisterKind(reflect.Int32, intDecoder(32)). - RegisterKind(reflect.Int64, intDecoder(64)). - RegisterKind(reflect.Uint, uintDecoder(bits.UintSize)). - RegisterKind(reflect.Uint8, uintDecoder(8)). - RegisterKind(reflect.Uint16, uintDecoder(16)). - RegisterKind(reflect.Uint32, uintDecoder(32)). - RegisterKind(reflect.Uint64, uintDecoder(64)). - RegisterKind(reflect.Float32, floatDecoder(32)). - RegisterKind(reflect.Float64, floatDecoder(64)). - RegisterKind(reflect.String, MapperFunc(func(ctx *DecodeContext, target reflect.Value) error { - return ctx.Scan.PopValueInto("string", target.Addr().Interface()) - })). - RegisterKind(reflect.Bool, boolMapper{}). - RegisterKind(reflect.Slice, sliceDecoder(r)). - RegisterKind(reflect.Map, mapDecoder(r)). - RegisterType(reflect.TypeOf(time.Time{}), timeDecoder()). - RegisterType(reflect.TypeOf(time.Duration(0)), durationDecoder()). - RegisterType(reflect.TypeOf(&url.URL{}), urlMapper()). - RegisterType(reflect.TypeOf(&os.File{}), fileMapper(r)). - RegisterName("path", pathMapper(r)). - RegisterName("existingfile", existingFileMapper(r)). - RegisterName("existingdir", existingDirMapper(r)). - RegisterName("counter", counterMapper()). - RegisterName("filecontent", fileContentMapper(r)). - RegisterKind(reflect.Ptr, ptrMapper{r}) -} - -type boolMapper struct{} - -func (boolMapper) Decode(ctx *DecodeContext, target reflect.Value) error { - if ctx.Scan.Peek().Type == FlagValueToken { - token := ctx.Scan.Pop() - switch v := token.Value.(type) { - case string: - v = strings.ToLower(v) - switch v { - case "true", "1", "yes": - target.SetBool(true) - - case "false", "0", "no": - target.SetBool(false) - - default: - return fmt.Errorf("bool value must be true, 1, yes, false, 0 or no but got %q", v) - } - - case bool: - target.SetBool(v) - - default: - return fmt.Errorf("expected bool but got %q (%T)", token.Value, token.Value) - } - } else { - target.SetBool(true) - } - return nil -} -func (boolMapper) IsBool() bool { return true } - -func durationDecoder() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("duration") - if err != nil { - return err - } - var d time.Duration - switch v := t.Value.(type) { - case string: - d, err = time.ParseDuration(v) - if err != nil { - return fmt.Errorf("expected duration but got %q: %v", v, err) - } - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64: - d = reflect.ValueOf(v).Convert(reflect.TypeOf(time.Duration(0))).Interface().(time.Duration) //nolint: forcetypeassert - default: - return fmt.Errorf("expected duration but got %q", v) - } - target.Set(reflect.ValueOf(d)) - return nil - } -} - -func timeDecoder() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - format := time.RFC3339 - if ctx.Value.Format != "" { - format = ctx.Value.Format - } - var value string - if err := ctx.Scan.PopValueInto("time", &value); err != nil { - return err - } - t, err := time.Parse(format, value) - if err != nil { - return err - } - target.Set(reflect.ValueOf(t)) - return nil - } -} - -func intDecoder(bits int) MapperFunc { //nolint: dupl - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("int") - if err != nil { - return err - } - var sv string - switch v := t.Value.(type) { - case string: - sv = v - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - sv = fmt.Sprintf("%v", v) - - case float32, float64: - sv = fmt.Sprintf("%0.f", v) - - default: - return fmt.Errorf("expected an int but got %q (%T)", t, t.Value) - } - n, err := strconv.ParseInt(sv, 0, bits) - if err != nil { - return fmt.Errorf("expected a valid %d bit int but got %q", bits, sv) - } - target.SetInt(n) - return nil - } -} - -func uintDecoder(bits int) MapperFunc { //nolint: dupl - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("uint") - if err != nil { - return err - } - var sv string - switch v := t.Value.(type) { - case string: - sv = v - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - sv = fmt.Sprintf("%v", v) - - case float32, float64: - sv = fmt.Sprintf("%0.f", v) - - default: - return fmt.Errorf("expected an int but got %q (%T)", t, t.Value) - } - n, err := strconv.ParseUint(sv, 0, bits) - if err != nil { - return fmt.Errorf("expected a valid %d bit uint but got %q", bits, sv) - } - target.SetUint(n) - return nil - } -} - -func floatDecoder(bits int) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("float") - if err != nil { - return err - } - switch v := t.Value.(type) { - case string: - n, err := strconv.ParseFloat(v, bits) - if err != nil { - return fmt.Errorf("expected a float but got %q (%T)", t, t.Value) - } - target.SetFloat(n) - - case float32: - target.SetFloat(float64(v)) - - case float64: - target.SetFloat(v) - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - target.Set(reflect.ValueOf(v)) - - default: - return fmt.Errorf("expected an int but got %q (%T)", t, t.Value) - } - return nil - } -} - -func mapDecoder(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.IsNil() { - target.Set(reflect.MakeMap(target.Type())) - } - el := target.Type() - mapsep := ctx.Value.Tag.MapSep - var childScanner *Scanner - if ctx.Value.Flag != nil { - t := ctx.Scan.Pop() - // If decoding a flag, we need an value. - if t.IsEOL() { - return fmt.Errorf("missing value, expecting \"=%c...\"", mapsep) - } - switch v := t.Value.(type) { - case string: - childScanner = ScanAsType(t.Type, SplitEscaped(v, mapsep)...) - - case []map[string]any: - for _, m := range v { - err := jsonTranscode(m, target.Addr().Interface()) - if err != nil { - return err - } - } - return nil - - case map[string]any: - return jsonTranscode(v, target.Addr().Interface()) - - default: - return fmt.Errorf("invalid map value %q (of type %T)", t, t.Value) - } - } else { - tokens := ctx.Scan.PopWhile(func(t Token) bool { return t.IsValue() }) - childScanner = ScanFromTokens(tokens...) - } - for !childScanner.Peek().IsEOL() { - var token string - err := childScanner.PopValueInto("map", &token) - if err != nil { - return err - } - parts := strings.SplitN(token, "=", 2) - if len(parts) != 2 { - return fmt.Errorf("expected \"=\" but got %q", token) - } - key, value := parts[0], parts[1] - - keyTypeName, valueTypeName := "", "" - if typ := ctx.Value.Tag.Type; typ != "" { - parts := strings.Split(typ, ":") - if len(parts) != 2 { - return errors.New("type:\"\" on map field must be in the form \"[]:[]\"") - } - keyTypeName, valueTypeName = parts[0], parts[1] - } - - keyScanner := ScanAsType(FlagValueToken, key) - keyDecoder := r.ForNamedType(keyTypeName, el.Key()) - keyValue := reflect.New(el.Key()).Elem() - if err := keyDecoder.Decode(ctx.WithScanner(keyScanner), keyValue); err != nil { - return fmt.Errorf("invalid map key %q", key) - } - - valueScanner := ScanAsType(FlagValueToken, value) - valueDecoder := r.ForNamedType(valueTypeName, el.Elem()) - valueValue := reflect.New(el.Elem()).Elem() - if err := valueDecoder.Decode(ctx.WithScanner(valueScanner), valueValue); err != nil { - return fmt.Errorf("invalid map value %q", value) - } - - target.SetMapIndex(keyValue, valueValue) - } - return nil - } -} - -func sliceDecoder(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - el := target.Type().Elem() - sep := ctx.Value.Tag.Sep - var childScanner *Scanner - if ctx.Value.Flag != nil { - t := ctx.Scan.Pop() - // If decoding a flag, we need a value. - if t.IsEOL() { - return fmt.Errorf("missing value, expecting \"%c...\"", sep) - } - switch v := t.Value.(type) { - case string: - childScanner = ScanAsType(t.Type, SplitEscaped(v, sep)...) - - case []any: - return jsonTranscode(v, target.Addr().Interface()) - - default: - v = []any{v} - return jsonTranscode(v, target.Addr().Interface()) - } - } else { - tokens := ctx.Scan.PopWhile(func(t Token) bool { return t.IsValue() }) - childScanner = ScanFromTokens(tokens...) - } - childDecoder := r.ForNamedType(ctx.Value.Tag.Type, el) - if childDecoder == nil { - return fmt.Errorf("no mapper for element type of %s", target.Type()) - } - for !childScanner.Peek().IsEOL() { - childValue := reflect.New(el).Elem() - err := childDecoder.Decode(ctx.WithScanner(childScanner), childValue) - if err != nil { - return err - } - target.Set(reflect.Append(target, childValue)) - } - return nil - } -} - -func pathMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - if target.Kind() == reflect.Ptr && target.Elem().Kind() == reflect.String { - if target.IsNil() { - return nil - } - target = target.Elem() - } - if target.Kind() != reflect.String { - return fmt.Errorf("\"path\" type must be applied to a string not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - if path != "-" { - path = ExpandPath(path) - } - target.SetString(path) - return nil - } -} - -func fileMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - var file *os.File - if path == "-" { - file = os.Stdin - } else { - path = ExpandPath(path) - file, err = os.Open(path) //nolint: gosec - if err != nil { - return err - } - } - target.Set(reflect.ValueOf(file)) - return nil - } -} - -func existingFileMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - if target.Kind() != reflect.String { - return fmt.Errorf("\"existingfile\" type must be applied to a string not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - - if !ctx.Value.Active || (ctx.Value.Set && ctx.Value.Target.Type() == target.Type()) { - // early return to avoid checking extra files that may not exist; - // this hack only works because the value provided on the cli is - // checked before the default value is checked (if default is set). - return nil - } - - if path != "-" { - path = ExpandPath(path) - stat, err := os.Stat(path) - if err != nil { - return err - } - if stat.IsDir() { - return fmt.Errorf("%q exists but is a directory", path) - } - } - target.SetString(path) - return nil - } -} - -func existingDirMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - if target.Kind() != reflect.String { - return fmt.Errorf("\"existingdir\" must be applied to a string not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - - if !ctx.Value.Active || (ctx.Value.Set && ctx.Value.Target.Type() == target.Type()) { - // early return to avoid checking extra dirs that may not exist; - // this hack only works because the value provided on the cli is - // checked before the default value is checked (if default is set). - return nil - } - - path = ExpandPath(path) - stat, err := os.Stat(path) - if err != nil { - return err - } - if !stat.IsDir() { - return fmt.Errorf("%q exists but is not a directory", path) - } - target.SetString(path) - return nil - } -} - -func fileContentMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() != reflect.Slice && target.Elem().Kind() != reflect.Uint8 { - return fmt.Errorf("\"filecontent\" must be applied to []byte not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - - if !ctx.Value.Active || ctx.Value.Set { - // early return to avoid checking extra dirs that may not exist; - // this hack only works because the value provided on the cli is - // checked before the default value is checked (if default is set). - return nil - } - - var data []byte - if path != "-" { - path = ExpandPath(path) - data, err = os.ReadFile(path) //nolint:gosec - } else { - data, err = io.ReadAll(os.Stdin) - } - if err != nil { - if info, statErr := os.Stat(path); statErr == nil && info.IsDir() { - return fmt.Errorf("%q exists but is a directory: %w", path, err) - } - return err - } - target.SetBytes(data) - return nil - } -} - -type ptrMapper struct { - r *Registry -} - -var _ BoolMapperExt = (*ptrMapper)(nil) - -// IsBoolFromValue implements BoolMapperExt -func (p ptrMapper) IsBoolFromValue(target reflect.Value) bool { - elem := reflect.New(target.Type().Elem()).Elem() - nestedMapper := p.r.ForValue(elem) - if nestedMapper == nil { - return false - } - if bm, ok := nestedMapper.(BoolMapper); ok && bm.IsBool() { - return true - } - if bm, ok := nestedMapper.(BoolMapperExt); ok && bm.IsBoolFromValue(target) { - return true - } - return target.Kind() == reflect.Ptr && target.Type().Elem().Kind() == reflect.Bool -} - -func (p ptrMapper) Decode(ctx *DecodeContext, target reflect.Value) error { - elem := reflect.New(target.Type().Elem()).Elem() - nestedMapper := p.r.ForValue(elem) - if nestedMapper == nil { - return fmt.Errorf("cannot find mapper for %v", target.Type().Elem().String()) - } - err := nestedMapper.Decode(ctx, elem) - if err != nil { - return err - } - target.Set(elem.Addr()) - return nil -} - -func counterMapper() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if ctx.Scan.Peek().Type == FlagValueToken { - t, err := ctx.Scan.PopValue("counter") - if err != nil { - return err - } - switch v := t.Value.(type) { - case string: - n, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return fmt.Errorf("expected a counter but got %q (%T)", t, t.Value) - } - target.SetInt(n) - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - target.Set(reflect.ValueOf(v)) - - default: - return fmt.Errorf("expected a counter but got %q (%T)", t, t.Value) - } - return nil - } - - switch target.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - target.SetInt(target.Int() + 1) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - target.SetUint(target.Uint() + 1) - - case reflect.Float32, reflect.Float64: - target.SetFloat(target.Float() + 1) - - default: - return fmt.Errorf("type:\"counter\" must be used with a numeric field") - } - return nil - } -} - -func urlMapper() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - var urlStr string - err := ctx.Scan.PopValueInto("url", &urlStr) - if err != nil { - return err - } - url, err := url.Parse(urlStr) - if err != nil { - return err - } - target.Set(reflect.ValueOf(url)) - return nil - } -} - -// SplitEscaped splits a string on a separator. -// -// It differs from strings.Split() in that the separator can exist in a field by escaping it with a \. eg. -// -// SplitEscaped(`hello\,there,bob`, ',') == []string{"hello,there", "bob"} -func SplitEscaped(s string, sep rune) (out []string) { - if sep == -1 { - return []string{s} - } - escaped := false - token := "" - for i, ch := range s { - switch { - case escaped: - if ch != sep { - token += `\` - } - token += string(ch) - escaped = false - case ch == '\\' && i < len(s)-1: - escaped = true - case ch == sep && !escaped: - out = append(out, token) - token = "" - escaped = false - default: - token += string(ch) - } - } - if token != "" { - out = append(out, token) - } - return -} - -// JoinEscaped joins a slice of strings on sep, but also escapes any instances of sep in the fields with \. eg. -// -// JoinEscaped([]string{"hello,there", "bob"}, ',') == `hello\,there,bob` -func JoinEscaped(s []string, sep rune) string { - escaped := []string{} - for _, e := range s { - escaped = append(escaped, strings.ReplaceAll(e, string(sep), `\`+string(sep))) - } - return strings.Join(escaped, string(sep)) -} - -// NamedFileContentFlag is a flag value that loads a file's contents and filename into its value. -type NamedFileContentFlag struct { - Filename string - Contents []byte -} - -func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error { //nolint: revive - var filename string - err := ctx.Scan.PopValueInto("filename", &filename) - if err != nil { - return err - } - // This allows unsetting of file content flags. - if filename == "" { - *f = NamedFileContentFlag{} - return nil - } - filename = ExpandPath(filename) - data, err := os.ReadFile(filename) //nolint: gosec - if err != nil { - return fmt.Errorf("failed to open %q: %v", filename, err) - } - f.Contents = data - f.Filename = filename - return nil -} - -// FileContentFlag is a flag value that loads a file's contents into its value. -type FileContentFlag []byte - -func (f *FileContentFlag) Decode(ctx *DecodeContext) error { //nolint: revive - var filename string - err := ctx.Scan.PopValueInto("filename", &filename) - if err != nil { - return err - } - // This allows unsetting of file content flags. - if filename == "" { - *f = nil - return nil - } - filename = ExpandPath(filename) - data, err := os.ReadFile(filename) //nolint: gosec - if err != nil { - return fmt.Errorf("failed to open %q: %v", filename, err) - } - *f = data - return nil -} - -func jsonTranscode(in, out any) error { - data, err := json.Marshal(in) - if err != nil { - return err - } - if err = json.Unmarshal(data, out); err != nil { - return fmt.Errorf("%#v -> %T: %v", in, out, err) - } - return nil -} diff --git a/vendor/github.com/alecthomas/kong/model.go b/vendor/github.com/alecthomas/kong/model.go deleted file mode 100644 index 33a6f33..0000000 --- a/vendor/github.com/alecthomas/kong/model.go +++ /dev/null @@ -1,514 +0,0 @@ -package kong - -import ( - "fmt" - "math" - "os" - "reflect" - "strconv" - "strings" -) - -// A Visitable component in the model. -type Visitable interface { - node() -} - -// Application is the root of the Kong model. -type Application struct { - *Node - // Help flag, if the NoDefaultHelp() option is not specified. - HelpFlag *Flag -} - -// Argument represents a branching positional argument. -type Argument = Node - -// Command represents a command in the CLI. -type Command = Node - -// NodeType is an enum representing the type of a Node. -type NodeType int - -// Node type enumerations. -const ( - ApplicationNode NodeType = iota - CommandNode - ArgumentNode -) - -// Node is a branch in the CLI. ie. a command or positional argument. -type Node struct { - Type NodeType - Parent *Node - Name string - Help string // Short help displayed in summaries. - Detail string // Detailed help displayed when describing command/arg alone. - Group *Group - Hidden bool - Flags []*Flag - Positional []*Positional - Children []*Node - DefaultCmd *Node - Target reflect.Value // Pointer to the value in the grammar that this Node is associated with. - Tag *Tag - Aliases []string - Passthrough bool // Set to true to stop flag parsing when encountered. - Active bool // Denotes the node is part of an active branch in the CLI. - - Argument *Value // Populated when Type is ArgumentNode. -} - -func (*Node) node() {} - -// Leaf returns true if this Node is a leaf node. -func (n *Node) Leaf() bool { - return len(n.Children) == 0 -} - -// Find a command/argument/flag by pointer to its field. -// -// Returns nil if not found. Panics if ptr is not a pointer. -func (n *Node) Find(ptr any) *Node { - key := reflect.ValueOf(ptr) - if key.Kind() != reflect.Ptr { - panic("expected a pointer") - } - return n.findNode(key) -} - -func (n *Node) findNode(key reflect.Value) *Node { - if n.Target == key { - return n - } - for _, child := range n.Children { - if found := child.findNode(key); found != nil { - return found - } - } - return nil -} - -// AllFlags returns flags from all ancestor branches encountered. -// -// If "hide" is true hidden flags will be omitted. -func (n *Node) AllFlags(hide bool) (out [][]*Flag) { - if n.Parent != nil { - out = append(out, n.Parent.AllFlags(hide)...) - } - group := []*Flag{} - for _, flag := range n.Flags { - if !hide || !flag.Hidden { - flag.Active = true - group = append(group, flag) - } - } - if len(group) > 0 { - out = append(out, group) - } - return -} - -// Leaves returns the leaf commands/arguments under Node. -// -// If "hidden" is true hidden leaves will be omitted. -func (n *Node) Leaves(hide bool) (out []*Node) { - _ = Visit(n, func(nd Visitable, next Next) error { - if nd == n { - return next(nil) - } - if node, ok := nd.(*Node); ok { - if hide && node.Hidden { - return nil - } - if len(node.Children) == 0 && node.Type != ApplicationNode { - out = append(out, node) - } - } - return next(nil) - }) - return -} - -// Depth of the command from the application root. -func (n *Node) Depth() int { - depth := 0 - p := n.Parent - for p != nil && p.Type != ApplicationNode { - depth++ - p = p.Parent - } - return depth -} - -// Summary help string for the node (not including application name). -func (n *Node) Summary() string { - summary := n.Path() - if flags := n.FlagSummary(true); flags != "" { - summary += " " + flags - } - args := []string{} - optional := 0 - for _, arg := range n.Positional { - argSummary := arg.Summary() - if arg.Tag.Optional { - optional++ - argSummary = strings.TrimRight(argSummary, "]") - } - args = append(args, argSummary) - } - if len(args) != 0 { - summary += " " + strings.Join(args, " ") + strings.Repeat("]", optional) - } else if len(n.Children) > 0 { - summary += " " - } - allFlags := n.Flags - if n.Parent != nil { - allFlags = append(allFlags, n.Parent.Flags...) - } - for _, flag := range allFlags { - if _, ok := flag.Target.Interface().(helpFlag); ok { - continue - } - if !flag.Required { - summary += " [flags]" - break - } - } - return summary -} - -// FlagSummary for the node. -func (n *Node) FlagSummary(hide bool) string { - required := []string{} - count := 0 - for _, group := range n.AllFlags(hide) { - for _, flag := range group { - count++ - if flag.Required { - required = append(required, flag.Summary()) - } - } - } - return strings.Join(required, " ") -} - -// FullPath is like Path() but includes the Application root node. -func (n *Node) FullPath() string { - root := n - for root.Parent != nil { - root = root.Parent - } - return strings.TrimSpace(root.Name + " " + n.Path()) -} - -// Vars returns the combined Vars defined by all ancestors of this Node. -func (n *Node) Vars() Vars { - if n == nil { - return Vars{} - } - return n.Parent.Vars().CloneWith(n.Tag.Vars) -} - -// Path through ancestors to this Node. -func (n *Node) Path() (out string) { - if n.Parent != nil { - out += " " + n.Parent.Path() - } - switch n.Type { - case CommandNode: - out += " " + n.Name - if len(n.Aliases) > 0 { - out += fmt.Sprintf(" (%s)", strings.Join(n.Aliases, ",")) - } - case ArgumentNode: - out += " " + "<" + n.Name + ">" - default: - } - return strings.TrimSpace(out) -} - -// ClosestGroup finds the first non-nil group in this node and its ancestors. -func (n *Node) ClosestGroup() *Group { - switch { - case n.Group != nil: - return n.Group - case n.Parent != nil: - return n.Parent.ClosestGroup() - default: - return nil - } -} - -// A Value is either a flag or a variable positional argument. -type Value struct { - Flag *Flag // Nil if positional argument. - Name string - Help string - OrigHelp string // Original help string, without interpolated variables. - HasDefault bool - Default string - DefaultValue reflect.Value - Enum string - Mapper Mapper - Tag *Tag - Target reflect.Value - Required bool - Set bool // Set to true when this value is set through some mechanism. - Format string // Formatting directive, if applicable. - Position int // Position (for positional arguments). - Passthrough bool // Deprecated: Use PassthroughMode instead. Set to true to stop flag parsing when encountered. - PassthroughMode PassthroughMode // - Active bool // Denotes the value is part of an active branch in the CLI. -} - -// EnumMap returns a map of the enums in this value. -func (v *Value) EnumMap() map[string]bool { - parts := strings.Split(v.Enum, ",") - out := make(map[string]bool, len(parts)) - for _, part := range parts { - out[strings.TrimSpace(part)] = true - } - return out -} - -// EnumSlice returns a slice of the enums in this value. -func (v *Value) EnumSlice() []string { - parts := strings.Split(v.Enum, ",") - out := make([]string, len(parts)) - for i, part := range parts { - out[i] = strings.TrimSpace(part) - } - return out -} - -// ShortSummary returns a human-readable summary of the value, not including any placeholders/defaults. -func (v *Value) ShortSummary() string { - if v.Flag != nil { - return fmt.Sprintf("--%s", v.Name) - } - argText := "<" + v.Name + ">" - if v.IsCumulative() { - argText += " ..." - } - if !v.Required { - argText = "[" + argText + "]" - } - return argText -} - -// Summary returns a human-readable summary of the value. -func (v *Value) Summary() string { - if v.Flag != nil { - if v.IsBool() { - return fmt.Sprintf("--%s", v.Name) - } - return fmt.Sprintf("--%s=%s", v.Name, v.Flag.FormatPlaceHolder()) - } - argText := "<" + v.Name + ">" - if v.IsCumulative() { - argText += " ..." - } - if !v.Required { - argText = "[" + argText + "]" - } - return argText -} - -// IsCumulative returns true if the type can be accumulated into. -func (v *Value) IsCumulative() bool { - return v.IsSlice() || v.IsMap() -} - -// IsSlice returns true if the value is a slice. -func (v *Value) IsSlice() bool { - return v.Target.Type().Name() == "" && v.Target.Kind() == reflect.Slice -} - -// IsMap returns true if the value is a map. -func (v *Value) IsMap() bool { - return v.Target.Kind() == reflect.Map -} - -// IsBool returns true if the underlying value is a boolean. -func (v *Value) IsBool() bool { - if m, ok := v.Mapper.(BoolMapperExt); ok && m.IsBoolFromValue(v.Target) { - return true - } - if m, ok := v.Mapper.(BoolMapper); ok && m.IsBool() { - return true - } - return v.Target.Kind() == reflect.Bool -} - -// IsCounter returns true if the value is a counter. -func (v *Value) IsCounter() bool { - return v.Tag.Type == "counter" -} - -// Parse tokens into value, parse, and validate, but do not write to the field. -func (v *Value) Parse(scan *Scanner, target reflect.Value) (err error) { - if target.Kind() == reflect.Ptr && target.IsNil() { - target.Set(reflect.New(target.Type().Elem())) - } - err = v.Mapper.Decode(&DecodeContext{Value: v, Scan: scan}, target) - if err != nil { - return fmt.Errorf("%s: %w", v.ShortSummary(), err) - } - v.Set = true - return nil -} - -// Apply value to field. -func (v *Value) Apply(value reflect.Value) { - v.Target.Set(value) - v.Set = true -} - -// ApplyDefault value to field if it is not already set. -func (v *Value) ApplyDefault() error { - if reflectValueIsZero(v.Target) { - return v.Reset() - } - v.Set = true - return nil -} - -// Reset this value to its default, either the zero value or the parsed result of its envar, -// or its "default" tag. -// -// Does not include resolvers. -func (v *Value) Reset() error { - v.Target.Set(reflect.Zero(v.Target.Type())) - if len(v.Tag.Envs) != 0 { - for _, env := range v.Tag.Envs { - envar, ok := os.LookupEnv(env) - // Parse the first non-empty ENV in the list - if ok { - err := v.Parse(ScanFromTokens(Token{Type: FlagValueToken, Value: envar}), v.Target) - if err != nil { - return fmt.Errorf("%s (from envar %s=%q)", err, env, envar) - } - return nil - } - } - } - if v.HasDefault { - return v.Parse(ScanFromTokens(Token{Type: FlagValueToken, Value: v.Default}), v.Target) - } - return nil -} - -func (*Value) node() {} - -// A Positional represents a non-branching command-line positional argument. -type Positional = Value - -// A Flag represents a command-line flag. -type Flag struct { - *Value - Group *Group // Logical grouping when displaying. May also be used by configuration loaders to group options logically. - Xor []string - And []string - PlaceHolder string - Envs []string - Aliases []string - Short rune - Hidden bool - Negated bool -} - -func (f *Flag) String() string { - out := "--" + f.Name - if f.Short != 0 { - out = fmt.Sprintf("-%c, %s", f.Short, out) - } - if !f.IsBool() && !f.IsCounter() { - out += "=" + f.FormatPlaceHolder() - } - return out -} - -// FormatPlaceHolder formats the placeholder string for a Flag. -func (f *Flag) FormatPlaceHolder() string { - placeholderHelper, ok := f.Value.Mapper.(PlaceHolderProvider) - if ok { - return placeholderHelper.PlaceHolder(f) - } - tail := "" - if f.Value.IsSlice() && f.Value.Tag.Sep != -1 && f.Tag.Type == "" { - tail += string(f.Value.Tag.Sep) + "..." - } - if f.PlaceHolder != "" { - return f.PlaceHolder + tail - } - if f.HasDefault { - if f.Value.Target.Kind() == reflect.String { - return strconv.Quote(f.Default) + tail - } - return f.Default + tail - } - if f.Value.IsMap() { - if f.Value.Tag.MapSep != -1 && f.Tag.Type == "" { - tail = string(f.Value.Tag.MapSep) + "..." - } - return "KEY=VALUE" + tail - } - if f.Tag != nil && f.Tag.TypeName != "" { - return strings.ToUpper(dashedString(f.Tag.TypeName)) + tail - } - return strings.ToUpper(f.Name) + tail -} - -// Group holds metadata about a command or flag group used when printing help. -type Group struct { - // Key is the `group` field tag value used to identify this group. - Key string - // Title is displayed above the grouped items. - Title string - // Description is optional and displayed under the Title when non empty. - // It can be used to introduce the group's purpose to the user. - Description string -} - -// This is directly from the Go 1.13 source code. -func reflectValueIsZero(v reflect.Value) bool { - switch v.Kind() { - 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 math.Float64bits(v.Float()) == 0 - case reflect.Complex64, reflect.Complex128: - c := v.Complex() - return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0 - case reflect.Array: - for i := 0; i < v.Len(); i++ { - if !reflectValueIsZero(v.Index(i)) { - return false - } - } - return true - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: - return v.IsNil() - case reflect.String: - return v.Len() == 0 - case reflect.Struct: - for i := 0; i < v.NumField(); i++ { - if !reflectValueIsZero(v.Field(i)) { - return false - } - } - return true - default: - // This should never happens, but will act as a safeguard for - // later, as a default value doesn't makes sense here. - panic(&reflect.ValueError{ - Method: "reflect.Value.IsZero", - Kind: v.Kind(), - }) - } -} diff --git a/vendor/github.com/alecthomas/kong/negatable.go b/vendor/github.com/alecthomas/kong/negatable.go deleted file mode 100644 index 7d8902a..0000000 --- a/vendor/github.com/alecthomas/kong/negatable.go +++ /dev/null @@ -1,19 +0,0 @@ -package kong - -// negatableDefault is a placeholder value for the Negatable tag to indicate -// the negated flag is --no-. This is needed as at the time of -// parsing a tag, the field's flag name is not yet known. -const negatableDefault = "_" - -// negatableFlagName returns the name of the flag for a negatable field, or -// an empty string if the field is not negatable. -func negatableFlagName(name, negation string) string { - switch negation { - case "": - return "" - case negatableDefault: - return "--no-" + name - default: - return "--" + negation - } -} diff --git a/vendor/github.com/alecthomas/kong/options.go b/vendor/github.com/alecthomas/kong/options.go deleted file mode 100644 index a1fa242..0000000 --- a/vendor/github.com/alecthomas/kong/options.go +++ /dev/null @@ -1,563 +0,0 @@ -package kong - -import ( - "errors" - "fmt" - "io" - "os" - "os/user" - "path/filepath" - "reflect" - "regexp" - "strings" -) - -// An Option applies optional changes to the Kong application. -type Option interface { - Apply(k *Kong) error -} - -// OptionFunc is function that adheres to the Option interface. -type OptionFunc func(k *Kong) error - -func (o OptionFunc) Apply(k *Kong) error { return o(k) } //nolint: revive - -// Vars sets the variables to use for interpolation into help strings and default values. -// -// See README for details. -type Vars map[string]string - -// Apply lets Vars act as an Option. -func (v Vars) Apply(k *Kong) error { - for key, value := range v { - k.vars[key] = value - } - return nil -} - -// CloneWith clones the current Vars and merges "vars" onto the clone. -func (v Vars) CloneWith(vars Vars) Vars { - out := make(Vars, len(v)+len(vars)) - for key, value := range v { - out[key] = value - } - for key, value := range vars { - out[key] = value - } - return out -} - -// Exit overrides the function used to terminate. This is useful for testing or interactive use. -func Exit(exit func(int)) Option { - return OptionFunc(func(k *Kong) error { - k.Exit = exit - return nil - }) -} - -// WithHyphenPrefixedParameters enables or disables hyphen-prefixed parameters. -// -// These are disabled by default. -func WithHyphenPrefixedParameters(enable bool) Option { - return OptionFunc(func(k *Kong) error { - k.allowHyphenated = enable - return nil - }) -} - -type embedded struct { - strct any - tags []string -} - -// Embed a struct into the root of the CLI. -// -// "strct" must be a pointer to a structure. -func Embed(strct any, tags ...string) Option { - t := reflect.TypeOf(strct) - if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct { - panic("kong: Embed() must be called with a pointer to a struct") - } - return OptionFunc(func(k *Kong) error { - k.embedded = append(k.embedded, embedded{strct, tags}) - return nil - }) -} - -type dynamicCommand struct { - name string - help string - group string - tags []string - cmd any -} - -// DynamicCommand registers a dynamically constructed command with the root of the CLI. -// -// This is useful for command-line structures that are extensible via user-provided plugins. -// -// "tags" is a list of extra tag strings to parse, in the form :"". -func DynamicCommand(name, help, group string, cmd any, tags ...string) Option { - return OptionFunc(func(k *Kong) error { - if run := getMethod(reflect.Indirect(reflect.ValueOf(cmd)), "Run"); !run.IsValid() { - return fmt.Errorf("kong: DynamicCommand %q must be a type with a 'Run' method; got %T", name, cmd) - } - - k.dynamicCommands = append(k.dynamicCommands, &dynamicCommand{ - name: name, - help: help, - group: group, - cmd: cmd, - tags: tags, - }) - return nil - }) -} - -// NoDefaultHelp disables the default help flags. -func NoDefaultHelp() Option { - return OptionFunc(func(k *Kong) error { - k.noDefaultHelp = true - return nil - }) -} - -// PostBuild provides read/write access to kong.Kong after initial construction of the model is complete but before -// parsing occurs. -// -// This is useful for, e.g., adding short options to flags, updating help, etc. -func PostBuild(fn func(*Kong) error) Option { - return OptionFunc(func(k *Kong) error { - k.postBuildOptions = append(k.postBuildOptions, OptionFunc(fn)) - return nil - }) -} - -// WithBeforeReset registers a hook to run before fields values are reset to their defaults -// (as specified in the grammar) or to zero values. -func WithBeforeReset(fn any) Option { - return withHook("BeforeReset", fn) -} - -// WithBeforeResolve registers a hook to run before resolvers are applied. -func WithBeforeResolve(fn any) Option { - return withHook("BeforeResolve", fn) -} - -// WithBeforeApply registers a hook to run before command line arguments are applied to the grammar. -func WithBeforeApply(fn any) Option { - return withHook("BeforeApply", fn) -} - -// WithAfterApply registers a hook to run after values are applied to the grammar and validated. -func WithAfterApply(fn any) Option { - return withHook("AfterApply", fn) -} - -// withHook registers a named hook. -func withHook(name string, fn any) Option { - value := reflect.ValueOf(fn) - if value.Kind() != reflect.Func { - panic(fmt.Errorf("expected function, got %s", value.Type())) - } - - return OptionFunc(func(k *Kong) error { - k.hooks[name] = append(k.hooks[name], value) - return nil - }) -} - -// Name overrides the application name. -func Name(name string) Option { - return PostBuild(func(k *Kong) error { - k.Model.Name = name - return nil - }) -} - -// Description sets the application description. -func Description(description string) Option { - return PostBuild(func(k *Kong) error { - k.Model.Help = description - return nil - }) -} - -// TypeMapper registers a mapper to a type. -func TypeMapper(typ reflect.Type, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterType(typ, mapper) - return nil - }) -} - -// KindMapper registers a mapper to a kind. -func KindMapper(kind reflect.Kind, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterKind(kind, mapper) - return nil - }) -} - -// ValueMapper registers a mapper to a field value. -func ValueMapper(ptr any, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterValue(ptr, mapper) - return nil - }) -} - -// NamedMapper registers a mapper to a name. -func NamedMapper(name string, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterName(name, mapper) - return nil - }) -} - -// Writers overrides the default writers. Useful for testing or interactive use. -func Writers(stdout, stderr io.Writer) Option { - return OptionFunc(func(k *Kong) error { - k.Stdout = stdout - k.Stderr = stderr - return nil - }) -} - -// Bind binds values for hooks and Run() function arguments. -// -// Any arguments passed will be available to the receiving hook functions, but may be omitted. Additionally, *Kong and -// the current *Context will also be made available. -// -// There are two hook points: -// -// BeforeApply(...) error -// AfterApply(...) error -// -// Called before validation/assignment, and immediately after validation/assignment, respectively. -func Bind(args ...any) Option { - return OptionFunc(func(k *Kong) error { - k.bindings.add(args...) - return nil - }) -} - -// BindTo allows binding of implementations to interfaces. -// -// BindTo(impl, (*iface)(nil)) -func BindTo(impl, iface any) Option { - return OptionFunc(func(k *Kong) error { - k.bindings.addTo(impl, iface) - return nil - }) -} - -// BindToProvider binds an injected value to a provider function. -// -// The provider function must have one of the following signatures: -// -// func(...) (T, error) -// func(...) T -// -// Where arguments to the function are injected by Kong. -// -// This is useful when the Run() function of different commands require different values that may -// not all be initialisable from the main() function. -func BindToProvider(provider any) Option { - return OptionFunc(func(k *Kong) error { - return k.bindings.addProvider(provider, false /* singleton */) - }) -} - -// BindSingletonProvider binds an injected value to a provider function. -// The provider function must have the signature: -// -// func(...) (T, error) -// func(...) T -// -// Unlike [BindToProvider], the provider function will only be called -// at most once, and the result will be cached and reused -// across multiple recipients of the injected value. -func BindSingletonProvider(provider any) Option { - return OptionFunc(func(k *Kong) error { - return k.bindings.addProvider(provider, true /* singleton */) - }) -} - -// Help printer to use. -func Help(help HelpPrinter) Option { - return OptionFunc(func(k *Kong) error { - k.help = help - return nil - }) -} - -// ShortHelp configures the short usage message. -// -// It should be used together with kong.ShortUsageOnError() to display a -// custom short usage message on errors. -func ShortHelp(shortHelp HelpPrinter) Option { - return OptionFunc(func(k *Kong) error { - k.shortHelp = shortHelp - return nil - }) -} - -// HelpFormatter configures how the help text is formatted. -// -// Deprecated: Use ValueFormatter() instead. -func HelpFormatter(helpFormatter HelpValueFormatter) Option { - return OptionFunc(func(k *Kong) error { - k.helpFormatter = helpFormatter - return nil - }) -} - -// ValueFormatter configures how the help text is formatted. -func ValueFormatter(helpFormatter HelpValueFormatter) Option { - return OptionFunc(func(k *Kong) error { - k.helpFormatter = helpFormatter - return nil - }) -} - -// ConfigureHelp sets the HelpOptions to use for printing help. -func ConfigureHelp(options HelpOptions) Option { - return OptionFunc(func(k *Kong) error { - k.helpOptions = options - return nil - }) -} - -// AutoGroup automatically assigns groups to flags. -func AutoGroup(format func(parent Visitable, flag *Flag) *Group) Option { - return PostBuild(func(kong *Kong) error { - parents := []Visitable{kong.Model} - return Visit(kong.Model, func(node Visitable, next Next) error { - if flag, ok := node.(*Flag); ok && flag.Group == nil { - flag.Group = format(parents[len(parents)-1], flag) - } - parents = append(parents, node) - defer func() { parents = parents[:len(parents)-1] }() - return next(nil) - }) - }) -} - -// Groups associates `group` field tags with group metadata. -// -// This option is used to simplify Kong tags while providing -// rich group information such as title and optional description. -// -// Each key in the "groups" map corresponds to the value of a -// `group` Kong tag, while the first line of the value will be -// the title, and subsequent lines if any will be the description of -// the group. -// -// See also ExplicitGroups for a more structured alternative. -type Groups map[string]string - -func (g Groups) Apply(k *Kong) error { //nolint: revive - for key, info := range g { - lines := strings.Split(info, "\n") - title := strings.TrimSpace(lines[0]) - description := "" - if len(lines) > 1 { - description = strings.TrimSpace(strings.Join(lines[1:], "\n")) - } - k.groups = append(k.groups, Group{ - Key: key, - Title: title, - Description: description, - }) - } - return nil -} - -// ExplicitGroups associates `group` field tags with their metadata. -// -// It can be used to provide a title or header to a command or flag group. -func ExplicitGroups(groups []Group) Option { - return OptionFunc(func(k *Kong) error { - k.groups = groups - return nil - }) -} - -// UsageOnError configures Kong to display context-sensitive usage if FatalIfErrorf is called with an error. -func UsageOnError() Option { - return OptionFunc(func(k *Kong) error { - k.usageOnError = fullUsage - return nil - }) -} - -// ShortUsageOnError configures Kong to display context-sensitive short -// usage if FatalIfErrorf is called with an error. The default short -// usage message can be overridden with kong.ShortHelp(...). -func ShortUsageOnError() Option { - return OptionFunc(func(k *Kong) error { - k.usageOnError = shortUsage - return nil - }) -} - -// ClearResolvers clears all existing resolvers. -func ClearResolvers() Option { - return OptionFunc(func(k *Kong) error { - k.resolvers = nil - return nil - }) -} - -// Resolvers registers flag resolvers. -func Resolvers(resolvers ...Resolver) Option { - return OptionFunc(func(k *Kong) error { - k.resolvers = append(k.resolvers, resolvers...) - return nil - }) -} - -// IgnoreFields will cause kong.New() to skip field names that match any -// of the provided regex patterns. This is useful if you are not able to add a -// kong="-" struct tag to a struct/element before the call to New. -// -// Example: When referencing protoc generated structs, you will likely want to -// ignore/skip XXX_* fields. -func IgnoreFields(regexes ...string) Option { - return OptionFunc(func(k *Kong) error { - for _, r := range regexes { - if r == "" { - return errors.New("regex input cannot be empty") - } - - re, err := regexp.Compile(r) - if err != nil { - return fmt.Errorf("unable to compile regex: %v", err) - } - - k.ignoreFields = append(k.ignoreFields, re) - } - - return nil - }) -} - -// ConfigurationLoader is a function that builds a resolver from a file. -type ConfigurationLoader func(r io.Reader) (Resolver, error) - -// Configuration provides Kong with support for loading defaults from a set of configuration files. -// -// Paths will be opened in order, and "loader" will be used to provide a Resolver which is registered with Kong. -// -// Note: The JSON function is a ConfigurationLoader. -// -// ~ and variable expansion will occur on the provided paths. -func Configuration(loader ConfigurationLoader, paths ...string) Option { - return OptionFunc(func(k *Kong) error { - k.loader = loader - for _, path := range paths { - f, err := os.Open(ExpandPath(path)) - if err != nil { - if os.IsNotExist(err) || os.IsPermission(err) { - continue - } - - return err - } - f.Close() - - resolver, err := k.LoadConfig(path) - if err != nil { - return fmt.Errorf("%s: %v", path, err) - } - if resolver != nil { - k.resolvers = append(k.resolvers, resolver) - } - } - return nil - }) -} - -// ExpandPath is a helper function to expand a relative or home-relative path to an absolute path. -// -// eg. ~/.someconf -> /home/alec/.someconf -func ExpandPath(path string) string { - if filepath.IsAbs(path) { - return path - } - if strings.HasPrefix(path, "~/") { - user, err := user.Current() - if err != nil { - return path - } - return filepath.Join(user.HomeDir, path[2:]) - } - abspath, err := filepath.Abs(path) - if err != nil { - return path - } - return abspath -} - -func siftStrings(ss []string, filter func(s string) bool) []string { - i := 0 - ss = append([]string(nil), ss...) - for _, s := range ss { - if filter(s) { - ss[i] = s - i++ - } - } - return ss[0:i] -} - -// DefaultEnvars option inits environment names for flags. -// The name will not generate if tag "env" is "-". -// Predefined environment variables are skipped. -// -// For example: -// -// --some.value -> PREFIX_SOME_VALUE -func DefaultEnvars(prefix string) Option { - processFlag := func(flag *Flag) { - switch env := flag.Envs; { - case flag.Name == "help": - return - case len(env) == 1 && env[0] == "-": - flag.Envs = nil - return - case len(env) > 0: - return - } - replacer := strings.NewReplacer("-", "_", ".", "_") - names := append([]string{prefix}, camelCase(replacer.Replace(flag.Name))...) - names = siftStrings(names, func(s string) bool { return !(s == "_" || strings.TrimSpace(s) == "") }) - name := strings.ToUpper(strings.Join(names, "_")) - flag.Envs = append(flag.Envs, name) - flag.Value.Tag.Envs = append(flag.Value.Tag.Envs, name) - } - - var processNode func(node *Node) - processNode = func(node *Node) { - for _, flag := range node.Flags { - processFlag(flag) - } - for _, node := range node.Children { - processNode(node) - } - } - - return PostBuild(func(k *Kong) error { - processNode(k.Model.Node) - return nil - }) -} - -// FlagNamer allows you to override the default kebab-case automated flag name generation. -func FlagNamer(namer func(fieldName string) string) Option { - return OptionFunc(func(k *Kong) error { - k.flagNamer = namer - return nil - }) -} diff --git a/vendor/github.com/alecthomas/kong/renovate.json5 b/vendor/github.com/alecthomas/kong/renovate.json5 deleted file mode 100644 index 561d59f..0000000 --- a/vendor/github.com/alecthomas/kong/renovate.json5 +++ /dev/null @@ -1,18 +0,0 @@ -{ - $schema: "https://docs.renovatebot.com/renovate-schema.json", - extends: [ - "config:recommended", - ":semanticCommits", - ":semanticCommitTypeAll(chore)", - ":semanticCommitScope(deps)", - "group:allNonMajor", - "schedule:earlyMondays", // Run once a week. - ], - packageRules: [ - { - "matchPackageNames": ["golangci-lint"], - "matchManagers": ["hermit"], - "enabled": false - }, - ] -} diff --git a/vendor/github.com/alecthomas/kong/resolver.go b/vendor/github.com/alecthomas/kong/resolver.go deleted file mode 100644 index 3e37ca7..0000000 --- a/vendor/github.com/alecthomas/kong/resolver.go +++ /dev/null @@ -1,68 +0,0 @@ -package kong - -import ( - "encoding/json" - "io" - "strings" -) - -// A Resolver resolves a Flag value from an external source. -type Resolver interface { - // Validate configuration against Application. - // - // This can be used to validate that all provided configuration is valid within this application. - Validate(app *Application) error - - // Resolve the value for a Flag. - Resolve(context *Context, parent *Path, flag *Flag) (any, error) -} - -// ResolverFunc is a convenience type for non-validating Resolvers. -type ResolverFunc func(context *Context, parent *Path, flag *Flag) (any, error) - -var _ Resolver = ResolverFunc(nil) - -func (r ResolverFunc) Resolve(context *Context, parent *Path, flag *Flag) (any, error) { //nolint: revive - return r(context, parent, flag) -} -func (r ResolverFunc) Validate(app *Application) error { return nil } //nolint: revive - -// JSON returns a Resolver that retrieves values from a JSON source. -// -// Flag names are used as JSON keys indirectly, by tring snake_case and camelCase variants. -func JSON(r io.Reader) (Resolver, error) { - values := map[string]any{} - err := json.NewDecoder(r).Decode(&values) - if err != nil { - return nil, err - } - var f ResolverFunc = func(context *Context, parent *Path, flag *Flag) (any, error) { - name := strings.ReplaceAll(flag.Name, "-", "_") - snakeCaseName := snakeCase(flag.Name) - raw, ok := values[name] - if ok { - return raw, nil - } else if raw, ok = values[snakeCaseName]; ok { - return raw, nil - } - raw = values - for _, part := range strings.Split(name, ".") { - if values, ok := raw.(map[string]any); ok { - raw, ok = values[part] - if !ok { - return nil, nil - } - } else { - return nil, nil - } - } - return raw, nil - } - - return f, nil -} - -func snakeCase(name string) string { - name = strings.Join(strings.Split(strings.Title(name), "-"), "") //nolint:staticcheck // Unicode punctuation not an issue - return strings.ToLower(name[:1]) + name[1:] -} diff --git a/vendor/github.com/alecthomas/kong/scanner.go b/vendor/github.com/alecthomas/kong/scanner.go deleted file mode 100644 index 511bf8f..0000000 --- a/vendor/github.com/alecthomas/kong/scanner.go +++ /dev/null @@ -1,236 +0,0 @@ -package kong - -import ( - "fmt" - "strings" -) - -// TokenType is the type of a token. -type TokenType int - -// Token types. -const ( - UntypedToken TokenType = iota - EOLToken - FlagToken // -- - FlagValueToken // = - ShortFlagToken // -[ - PositionalArgumentToken // -) - -func (t TokenType) String() string { - switch t { - case UntypedToken: - return "untyped" - case EOLToken: - return "" - case FlagToken: // -- - return "long flag" - case FlagValueToken: // = - return "flag value" - case ShortFlagToken: // -[ - return "short flag remainder" - case PositionalArgumentToken: // - return "positional argument" - } - panic("unsupported type") -} - -// Token created by Scanner. -type Token struct { - Value any - Type TokenType -} - -func (t Token) String() string { - switch t.Type { - case FlagToken: - return fmt.Sprintf("--%v", t.Value) - - case ShortFlagToken: - return fmt.Sprintf("-%v", t.Value) - - case EOLToken: - return "EOL" - - default: - return fmt.Sprintf("%v", t.Value) - } -} - -// IsEOL returns true if this Token is past the end of the line. -func (t Token) IsEOL() bool { - return t.Type == EOLToken -} - -// IsAny returns true if the token's type is any of those provided. -func (t TokenType) IsAny(types ...TokenType) bool { - for _, typ := range types { - if t == typ { - return true - } - } - return false -} - -// InferredType tries to infer the type of a token. -func (t Token) InferredType() TokenType { - if t.Type != UntypedToken { - return t.Type - } - if v, ok := t.Value.(string); ok { - if strings.HasPrefix(v, "--") { //nolint: gocritic - return FlagToken - } else if v == "-" { - return PositionalArgumentToken - } else if strings.HasPrefix(v, "-") { - return ShortFlagToken - } - } - return t.Type -} - -// IsValue returns true if token is usable as a parseable value. -// -// A parseable value is either a value typed token, or an untyped token NOT starting with a hyphen. -func (t Token) IsValue() bool { - tt := t.InferredType() - return tt.IsAny(FlagValueToken, ShortFlagTailToken, PositionalArgumentToken) || - (tt == UntypedToken && !strings.HasPrefix(t.String(), "-")) -} - -// Scanner is a stack-based scanner over command-line tokens. -// -// Initially all tokens are untyped. As the parser consumes tokens it assigns types, splits tokens, and pushes them back -// onto the stream. -// -// For example, the token "--foo=bar" will be split into the following by the parser: -// -// [{FlagToken, "foo"}, {FlagValueToken, "bar"}] -type Scanner struct { - allowHyphenated bool - args []Token -} - -// ScanAsType creates a new Scanner from args with the given type. -func ScanAsType(ttype TokenType, args ...string) *Scanner { - s := &Scanner{} - for _, arg := range args { - s.args = append(s.args, Token{Value: arg, Type: ttype}) - } - return s -} - -// Scan creates a new Scanner from args with untyped tokens. -func Scan(args ...string) *Scanner { - return ScanAsType(UntypedToken, args...) -} - -// ScanFromTokens creates a new Scanner from a slice of tokens. -func ScanFromTokens(tokens ...Token) *Scanner { - return &Scanner{args: tokens} -} - -// AllowHyphenPrefixedParameters enables or disables hyphen-prefixed flag parameters on this Scanner. -// -// Disabled by default. -func (s *Scanner) AllowHyphenPrefixedParameters(enable bool) *Scanner { - s.allowHyphenated = enable - return s -} - -// Len returns the number of input arguments. -func (s *Scanner) Len() int { - return len(s.args) -} - -// Pop the front token off the Scanner. -func (s *Scanner) Pop() Token { - if len(s.args) == 0 { - return Token{Type: EOLToken} - } - arg := s.args[0] - s.args = s.args[1:] - return arg -} - -type expectedError struct { - context string - token Token -} - -func (e *expectedError) Error() string { - return fmt.Sprintf("expected %s value but got %q (%s)", e.context, e.token, e.token.InferredType()) -} - -// PopValue pops a value token, or returns an error. -// -// "context" is used to assist the user if the value can not be popped, eg. "expected value but got " -func (s *Scanner) PopValue(context string) (Token, error) { - t := s.Pop() - if !s.allowHyphenated && !t.IsValue() { - return t, &expectedError{context, t} - } - return t, nil -} - -// PopValueInto pops a value token into target or returns an error. -// -// "context" is used to assist the user if the value can not be popped, eg. "expected value but got " -func (s *Scanner) PopValueInto(context string, target any) error { - t, err := s.PopValue(context) - if err != nil { - return err - } - return jsonTranscode(t.Value, target) -} - -// PopWhile predicate returns true. -func (s *Scanner) PopWhile(predicate func(Token) bool) (values []Token) { - for predicate(s.Peek()) { - values = append(values, s.Pop()) - } - return -} - -// PopUntil predicate returns true. -func (s *Scanner) PopUntil(predicate func(Token) bool) (values []Token) { - for !predicate(s.Peek()) { - values = append(values, s.Pop()) - } - return -} - -// Peek at the next Token or return an EOLToken. -func (s *Scanner) Peek() Token { - if len(s.args) == 0 { - return Token{Type: EOLToken} - } - return s.args[0] -} - -// PeekAll remaining tokens -func (s *Scanner) PeekAll() []Token { - return s.args -} - -// Push an untyped Token onto the front of the Scanner. -func (s *Scanner) Push(arg any) *Scanner { - s.PushToken(Token{Value: arg}) - return s -} - -// PushTyped pushes a typed token onto the front of the Scanner. -func (s *Scanner) PushTyped(arg any, typ TokenType) *Scanner { - s.PushToken(Token{Value: arg, Type: typ}) - return s -} - -// PushToken pushes a preconstructed Token onto the front of the Scanner. -func (s *Scanner) PushToken(token Token) *Scanner { - s.args = append([]Token{token}, s.args...) - return s -} diff --git a/vendor/github.com/alecthomas/kong/tag.go b/vendor/github.com/alecthomas/kong/tag.go deleted file mode 100644 index a2bc4a9..0000000 --- a/vendor/github.com/alecthomas/kong/tag.go +++ /dev/null @@ -1,386 +0,0 @@ -package kong - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// PassthroughMode indicates how parameters are passed through when "passthrough" is set. -type PassthroughMode int - -const ( - // PassThroughModeNone indicates passthrough mode is disabled. - PassThroughModeNone PassthroughMode = iota - // PassThroughModeAll indicates that all parameters, including flags, are passed through. It is the default. - PassThroughModeAll - // PassThroughModePartial will validate flags until the first positional argument is encountered, then pass through all remaining positional arguments. - PassThroughModePartial -) - -// Tag represents the parsed state of Kong tags in a struct field tag. -type Tag struct { - Ignored bool // Field is ignored by Kong. ie. kong:"-" - Cmd bool - Arg bool - Required bool - Optional bool - Name string - Help string - Type string - TypeName string - HasDefault bool - Default string - Format string - PlaceHolder string - Envs []string - Short rune - Hidden bool - Sep rune - MapSep rune - Enum string - Group string - Xor []string - And []string - Vars Vars - Prefix string // Optional prefix on anonymous structs. All sub-flags will have this prefix. - EnvPrefix string - XorPrefix string // Optional prefix on XOR/AND groups. - Embed bool - Aliases []string - Negatable string - Passthrough bool // Deprecated: use PassthroughMode instead. - PassthroughMode PassthroughMode - - // Storage for all tag keys for arbitrary lookups. - items map[string][]string -} - -func (t *Tag) String() string { - out := []string{} - for key, list := range t.items { - for _, value := range list { - out = append(out, fmt.Sprintf("%s:%q", key, value)) - } - } - return strings.Join(out, " ") -} - -type tagChars struct { - sep, quote, assign rune - needsUnquote bool -} - -var kongChars = tagChars{sep: ',', quote: '\'', assign: '=', needsUnquote: false} -var bareChars = tagChars{sep: ' ', quote: '"', assign: ':', needsUnquote: true} - -//nolint:gocyclo -func parseTagItems(tagString string, chr tagChars) (map[string][]string, error) { - d := map[string][]string{} - key := []rune{} - value := []rune{} - quotes := false - inKey := true - - add := func() error { - // Bare tags are quoted, therefore we need to unquote them in the same fashion reflect.Lookup() (implicitly) - // unquotes "kong tags". - s := string(value) - - if chr.needsUnquote && s != "" { - if unquoted, err := strconv.Unquote(fmt.Sprintf(`"%s"`, s)); err == nil { - s = unquoted - } else { - return fmt.Errorf("unquoting tag value `%s`: %w", s, err) - } - } - - d[string(key)] = append(d[string(key)], s) - key = []rune{} - value = []rune{} - inKey = true - - return nil - } - - runes := []rune(tagString) - for idx := 0; idx < len(runes); idx++ { - r := runes[idx] - next := rune(0) - eof := false - if idx < len(runes)-1 { - next = runes[idx+1] - } else { - eof = true - } - if !quotes && r == chr.sep { - if err := add(); err != nil { - return nil, err - } - - continue - } - if r == chr.assign && inKey { - inKey = false - continue - } - if r == '\\' { - if next == chr.quote { - idx++ - - // We need to keep the backslashes, otherwise subsequent unquoting cannot work - if chr.needsUnquote { - value = append(value, r) - } - - r = chr.quote - } - } else if r == chr.quote { - if quotes { - quotes = false - if next == chr.sep || eof { - continue - } - return nil, fmt.Errorf("%v has an unexpected char at pos %v", tagString, idx) - } - quotes = true - continue - } - if inKey { - key = append(key, r) - } else { - value = append(value, r) - } - } - if quotes { - return nil, fmt.Errorf("%v is not quoted properly", tagString) - } - - if err := add(); err != nil { - return nil, err - } - - return d, nil -} - -func getTagInfo(ft reflect.StructField) (string, tagChars) { - s, ok := ft.Tag.Lookup("kong") - if ok { - return s, kongChars - } - - return string(ft.Tag), bareChars -} - -func newEmptyTag() *Tag { - return &Tag{items: map[string][]string{}} -} - -func tagSplitFn(r rune) bool { - return r == ',' || r == ' ' -} - -func parseTagString(s string) (*Tag, error) { - items, err := parseTagItems(s, bareChars) - if err != nil { - return nil, err - } - t := &Tag{ - items: items, - } - err = hydrateTag(t, nil) - if err != nil { - return nil, fmt.Errorf("%s: %s", s, err) - } - return t, nil -} - -func parseTag(parent reflect.Value, ft reflect.StructField) (*Tag, error) { - if ft.Tag.Get("kong") == "-" { - t := newEmptyTag() - t.Ignored = true - return t, nil - } - items, err := parseTagItems(getTagInfo(ft)) - if err != nil { - return nil, err - } - t := &Tag{ - items: items, - } - err = hydrateTag(t, ft.Type) - if err != nil { - return nil, failField(parent, ft, "%s", err) - } - return t, nil -} - -func hydrateTag(t *Tag, typ reflect.Type) error { //nolint: gocyclo - var typeName string - var isBool bool - var isBoolPtr bool - if typ != nil { - typeName = typ.Name() - isBool = typ.Kind() == reflect.Bool - isBoolPtr = typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Bool - } - var err error - t.Cmd = t.Has("cmd") - t.Arg = t.Has("arg") - required := t.Has("required") - optional := t.Has("optional") - if required && optional { - return fmt.Errorf("can't specify both required and optional") - } - t.Required = required - t.Optional = optional - t.HasDefault = t.Has("default") - t.Default = t.Get("default") - // Arguments with defaults are always optional. - if t.Arg && t.HasDefault { - t.Optional = true - } else if t.Arg && !optional { // Arguments are required unless explicitly made optional. - t.Required = true - } - t.Name = t.Get("name") - t.Help = t.Get("help") - t.Type = t.Get("type") - t.TypeName = typeName - for _, env := range t.GetAll("env") { - t.Envs = append(t.Envs, strings.FieldsFunc(env, tagSplitFn)...) - } - t.Short, err = t.GetRune("short") - if err != nil && t.Get("short") != "" { - return fmt.Errorf("invalid short flag name %q: %s", t.Get("short"), err) - } - t.Hidden = t.Has("hidden") - t.Format = t.Get("format") - t.Sep, _ = t.GetSep("sep", ',') - t.MapSep, _ = t.GetSep("mapsep", ';') - t.Group = t.Get("group") - for _, xor := range t.GetAll("xor") { - t.Xor = append(t.Xor, strings.FieldsFunc(xor, tagSplitFn)...) - } - for _, and := range t.GetAll("and") { - t.And = append(t.And, strings.FieldsFunc(and, tagSplitFn)...) - } - t.Prefix = t.Get("prefix") - t.EnvPrefix = t.Get("envprefix") - t.XorPrefix = t.Get("xorprefix") - t.Embed = t.Has("embed") - if t.Has("negatable") { - if !isBool && !isBoolPtr { - return fmt.Errorf("negatable can only be set on booleans") - } - negatable := t.Get("negatable") - if negatable == "" { - negatable = negatableDefault // placeholder for default negation of --no- - } - t.Negatable = negatable - } - aliases := t.Get("aliases") - if len(aliases) > 0 { - t.Aliases = append(t.Aliases, strings.FieldsFunc(aliases, tagSplitFn)...) - } - t.Vars = Vars{} - for _, set := range t.GetAll("set") { - parts := strings.SplitN(set, "=", 2) - if len(parts) == 0 { - return fmt.Errorf("set should be in the form key=value but got %q", set) - } - t.Vars[parts[0]] = parts[1] - } - t.PlaceHolder = t.Get("placeholder") - t.Enum = t.Get("enum") - scalarType := typ == nil || !(typ.Kind() == reflect.Slice || typ.Kind() == reflect.Map || typ.Kind() == reflect.Ptr) - if t.Enum != "" && !(t.Required || t.HasDefault) && scalarType { - return fmt.Errorf("enum value is only valid if it is either required or has a valid default value") - } - passthrough := t.Has("passthrough") - if passthrough && !t.Arg && !t.Cmd { - return fmt.Errorf("passthrough only makes sense for positional arguments or commands") - } - t.Passthrough = passthrough - if t.Passthrough { - passthroughMode := t.Get("passthrough") - switch passthroughMode { - case "partial": - t.PassthroughMode = PassThroughModePartial - case "all", "": - t.PassthroughMode = PassThroughModeAll - default: - return fmt.Errorf("invalid passthrough mode %q, must be one of 'partial' or 'all'", passthroughMode) - } - } - return nil -} - -// Has returns true if the tag contained the given key. -func (t *Tag) Has(k string) bool { - _, ok := t.items[k] - return ok -} - -// Get returns the value of the given tag. -// -// Note that this will return the empty string if the tag is missing. -func (t *Tag) Get(k string) string { - values := t.items[k] - if len(values) == 0 { - return "" - } - return values[0] -} - -// GetAll returns all encountered values for a tag, in the case of multiple occurrences. -func (t *Tag) GetAll(k string) []string { - return t.items[k] -} - -// GetBool returns true if the given tag looks like a boolean truth string. -func (t *Tag) GetBool(k string) (bool, error) { - return strconv.ParseBool(t.Get(k)) -} - -// GetFloat parses the given tag as a float64. -func (t *Tag) GetFloat(k string) (float64, error) { - return strconv.ParseFloat(t.Get(k), 64) -} - -// GetInt parses the given tag as an int64. -func (t *Tag) GetInt(k string) (int64, error) { - return strconv.ParseInt(t.Get(k), 10, 64) -} - -// GetRune parses the given tag as a rune. -func (t *Tag) GetRune(k string) (rune, error) { - value := t.Get(k) - r, size := utf8.DecodeRuneInString(value) - if r == utf8.RuneError || size < len(value) { - return 0, errors.New("invalid rune") - } - return r, nil -} - -// GetSep parses the given tag as a rune separator, allowing for a default or none. -// The separator is returned, or -1 if "none" is specified. If the tag value is an -// invalid utf8 sequence, the default rune is returned as well as an error. If the -// tag value is more than one rune, the first rune is returned as well as an error. -func (t *Tag) GetSep(k string, dflt rune) (rune, error) { - tv := t.Get(k) - if tv == "none" { - return -1, nil - } else if tv == "" { - return dflt, nil - } - r, size := utf8.DecodeRuneInString(tv) - if r == utf8.RuneError { - return dflt, fmt.Errorf(`%v:"%v" has a rune error`, k, tv) - } else if size != len(tv) { - return r, fmt.Errorf(`%v:"%v" is more than a single rune`, k, tv) - } - return r, nil -} diff --git a/vendor/github.com/alecthomas/kong/util.go b/vendor/github.com/alecthomas/kong/util.go deleted file mode 100644 index 8b70664..0000000 --- a/vendor/github.com/alecthomas/kong/util.go +++ /dev/null @@ -1,57 +0,0 @@ -package kong - -import ( - "fmt" - "os" - "reflect" -) - -// ConfigFlag uses the configured (via kong.Configuration(loader)) configuration loader to load configuration -// from a file specified by a flag. -// -// Use this as a flag value to support loading of custom configuration via a flag. -type ConfigFlag string - -// BeforeResolve adds a resolver. -func (c ConfigFlag) BeforeResolve(kong *Kong, ctx *Context, trace *Path) error { - if kong.loader == nil { - return fmt.Errorf("kong must be configured with kong.Configuration(...)") - } - path := string(ctx.FlagValue(trace.Flag).(ConfigFlag)) //nolint - resolver, err := kong.LoadConfig(path) - if err != nil { - return err - } - ctx.AddResolver(resolver) - return nil -} - -// VersionFlag is a flag type that can be used to display a version number, stored in the "version" variable. -type VersionFlag bool - -// BeforeReset writes the version variable and terminates with a 0 exit status. -func (v VersionFlag) BeforeReset(app *Kong, vars Vars) error { - fmt.Fprintln(app.Stdout, vars["version"]) - app.Exit(0) - return nil -} - -// ChangeDirFlag changes the current working directory to a path specified by a flag -// early in the parsing process, changing how other flags resolve relative paths. -// -// Use this flag to provide a "git -C" like functionality. -// -// It is not compatible with custom named decoders, e.g., existingdir. -type ChangeDirFlag string - -// Decode is used to create a side effect of changing the current working directory. -func (c ChangeDirFlag) Decode(ctx *DecodeContext) error { - var path string - err := ctx.Scan.PopValueInto("string", &path) - if err != nil { - return err - } - path = ExpandPath(path) - ctx.Value.Target.Set(reflect.ValueOf(ChangeDirFlag(path))) - return os.Chdir(path) -} diff --git a/vendor/github.com/alecthomas/kong/visit.go b/vendor/github.com/alecthomas/kong/visit.go deleted file mode 100644 index f7dab53..0000000 --- a/vendor/github.com/alecthomas/kong/visit.go +++ /dev/null @@ -1,58 +0,0 @@ -package kong - -import ( - "fmt" -) - -// Next should be called by Visitor to proceed with the walk. -// -// The walk will terminate if "err" is non-nil. -type Next func(err error) error - -// Visitor can be used to walk all nodes in the model. -type Visitor func(node Visitable, next Next) error - -// Visit all nodes. -func Visit(node Visitable, visitor Visitor) error { - return visitor(node, func(err error) error { - if err != nil { - return err - } - switch node := node.(type) { - case *Application: - return visitNodeChildren(node.Node, visitor) - case *Node: - return visitNodeChildren(node, visitor) - case *Value: - case *Flag: - return Visit(node.Value, visitor) - default: - panic(fmt.Sprintf("unsupported node type %T", node)) - } - return nil - }) -} - -func visitNodeChildren(node *Node, visitor Visitor) error { - if node.Argument != nil { - if err := Visit(node.Argument, visitor); err != nil { - return err - } - } - for _, flag := range node.Flags { - if err := Visit(flag, visitor); err != nil { - return err - } - } - for _, pos := range node.Positional { - if err := Visit(pos, visitor); err != nil { - return err - } - } - for _, child := range node.Children { - if err := Visit(child, visitor); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/.fernignore b/vendor/github.com/anduril/lattice-sdk-go/v2/.fernignore deleted file mode 100644 index 21a5d9c..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/.fernignore +++ /dev/null @@ -1,4 +0,0 @@ -SECURITY.md -.github/CODEOWNERS -third-party-licenses.txt - diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/LICENSE b/vendor/github.com/anduril/lattice-sdk-go/v2/LICENSE deleted file mode 100644 index 9623e9f..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/LICENSE +++ /dev/null @@ -1,189 +0,0 @@ -# Anduril Lattice Software Development Kit License Agreement - -## Terms and Conditions - -This is the Anduril Lattice Software Development Kit (SDK) License Agreement (the “License Agreement”). - -1. **Introduction** - - 1.1 "Anduril" means Anduril Industries, Inc., organized under the laws of the State of Delaware, USA, and operating under the laws of - the USA with principal place of business at 1400 Anduril, Costa Mesa, California 92626, USA. - - 1.2 "Lattice" means the Anduril Lattice™ software stack for devices, as made available by Anduril, as updated from time to time. - - 1.3 The Anduril Lattice Software Development Kit (referred to in the License Agreement as the "SDK" and specifically including the - Lattice system files, packaged APIs, and Anduril APIs add-ons) is licensed to you subject to the terms of the License Agreement. - The License Agreement forms a legally binding contract between you and Anduril in relation to your use of the SDK. SDK, as used - herein, also includes any software libraries and/or packages that reference this License. - - 1.4 A "compatible implementation" means any use that (i) is compatible with Lattice; or (ii) successfully is validated by Anduril to be - compatible with Lattice. The determination of a compatible implementation is solely at the discretion of Anduril. - -2. **Accepting this License Agreement** - - - 2.1 In order to use the SDK, you must first agree to the License Agreement. You may not use the SDK if you do not accept the License -Agreement. - - 2.2 By clicking to accept and/or using this SDK, you hereby agree to the terms of the License Agreement. - - 2.3 You may not use the SDK and may not accept the License Agreement if you are a person barred from receiving the SDK under the -laws of the United States or other countries, including the country in which you are resident or from which you use the SDK. - - 2.4 If you are agreeing to be bound by the License Agreement on behalf of your employer or other entity, you represent and warrant that -you have full legal authority to bind your employer or such entity to the License Agreement. If you do not have the requisite authority, you -may not accept the License Agreement or use the SDK on behalf of your employer or other entity. Use of the SDK on hardware owned -by an entity such as your employer binds your employer to this License Agreement. - -3. **SDK License from Anduril** - - - 3.1 Subject to the terms of the License Agreement, Anduril grants you a limited, revocable, worldwide, royalty-free, non-assignable, - non- exclusive, and non-sublicensable license to use the SDK, or the software referencing this License Agreement, solely to develop - applications for compatible implementations of Anduril technology including without limitation systems, hardware and software such as Anduril Lattice. - - 3.2 You may not use this SDK to develop applications for other platforms (including non-compatible implementations of Lattice) or to -develop another SDK. You are of course free to develop applications for other platforms, including non-compatible implementations of -Lattice, provided that this SDK is not used for that purpose. - - 3.3 You agree that Anduril or third parties own all legal right, title and interest in and to the SDK, including any Intellectual Property Rights -that subsist in the SDK. "Intellectual Property Rights" means any and all rights under patent law, copyright law, trade secret law, trademark -law, and any and all other proprietary rights. Anduril reserves all rights not expressly granted to you. - - 3.4 You may not use the SDK for any purpose not expressly permitted by the License Agreement. Except to the extent required by -applicable third party licenses, you may not copy (except for backup purposes), modify, adapt, redistribute, de compile, reverse engineer, -disassemble, or create derivative works of the SDK or any part of the SDK. - - 3.5 Use, reproduction and distribution of components of the SDK licensed under an open-source software license are governed solely by -the terms of that open-source software license and not the License Agreement. - - 3.6 You agree that the form and nature of the SDK that Anduril provides may change without prior notice to you and that future versions -of the SDK may be incompatible with applications developed on previous versions of the SDK. You agree that Anduril may stop -(permanently or temporarily) providing the SDK (or any features within the SDK) to you or to users generally at Anduril's sole discretion, -without prior notice to you. - - 3.7 Nothing in the License Agreement gives you a right to use any of Anduril's trade names, trademarks, service marks, logos, domain -names, or other distinctive brand features. - - 3.8 You agree that you will not remove, obscure, or alter any proprietary rights notices (including copyright and trademark notices) that -may be affixed to or contained within the SDK. - -4. **Use of the SDK by You** - - - 4.1 Anduril agrees that it obtains no right, title or interest from you (or your licensors) under the License Agreement in or to any software -applications that you develop using the SDK, including any intellectual property rights that subsist in those applications. - - 4.2 You agree to use the SDK and write applications only for purposes that are permitted by (a) the License Agreement and (b) any -applicable law, regulation or generally accepted practices or guidelines in the relevant jurisdictions (including any laws regarding the -export of data or software to and from the United States or other relevant countries). - - 4.3 You agree that if you use the SDK to develop applications for Anduril Lattice users, you will protect the privacy and legal rights of -those users. If your application stores personal or sensitive information, it must do so securely. You may not use a third-party’s Lattice -account information or credentials to access Lattice. - - 4.4 You agree that you will not engage in any activity with the SDK, including the development or distribution of an application, that -interferes with, disrupts, damages, or accesses in an unauthorized manner the servers, networks, or other properties or services of any -third party including, but not limited to, Anduril or any fixed or mobile communications carrier. - - 4.5 You agree that you are solely responsible for (and that Anduril has no responsibility to you or to any third party for) any data, content, -or resources that you create, transmit or display through Anduril Lattice and/or applications for Lattice, and for the consequences of your -actions (including any loss or damage which Anduril may suffer) by doing so. - - 4.6 You agree that you are solely responsible for (and that Anduril has no responsibility to you or to any third party for) any breach of your -obligations under the License Agreement, any applicable third party contract or Terms of Service, or any applicable law or regulation, and -for the consequences (including any loss or damage which Anduril or any third party may suffer) of any such breach. - -5. **Your Developer Credentials** - - - 5.1 You agree that you are responsible for maintaining the confidentiality of any developer credentials that may be issued to you by -Anduril or which you may choose yourself and that you will be solely responsible for all applications that are developed under your -developer credentials. - -6. **Privacy and Information** - - - 6.1 In order to continually innovate and improve the SDK, Anduril may collect certain usage statistics from the software including but not -limited to a unique identifier, associated IP address, version number of the software, and information on which tools and/or services in -the SDK are being used and how they are being used. - - 6.2 Anonymized and aggregated sets of the data may be used or shared by Anduril to improve the SDK. - -7. **Third Party Applications** - - - 7.1 If you use the SDK to run applications developed by a third party or that access data, content or resources provided by a third party, -you agree that Anduril is not responsible for those applications, data, content, or resources. You understand that all data, content or -resources which you may access through such third party applications are the sole responsibility of the person from which they originated -and that Anduril is not liable for any loss or damage that you may experience as a result of the use or access of any of those third party -applications, data, content, or resources. - - 7.2 You should be aware the data, content, and resources presented to you through such a third party application may be protected by -intellectual property rights which are owned by the providers (or by other persons or companies on their behalf). You may not modify, -rent, lease, loan, sell, distribute or create derivative works based on these data, content, or resources (either in whole or in part) unless -you have been specifically given permission to do so by the relevant owners. - - 7.3 You acknowledge that your use of such third party applications, data, content, or resources may be subject to separate terms between -you and the relevant third party. In that case, the License Agreement does not affect your legal relationship with these third parties. - -8. **Using Lattice APIs** - - - 8.1 Anduril Data APIs - - 8.1.1 If you use any API to retrieve data, you acknowledge that the data may be protected by intellectual property rights which are owned -by Anduril or those parties that provide the data (or by other persons or companies on their behalf). Your use of any such API may be -subject to additional Terms of Service. You may not modify, rent, lease, loan, sell, distribute or create derivative works based on this data -(either in whole or in part) unless allowed by the relevant owner and/or terms of service. - - 8.1.2 If you use any API to retrieve a user's data, you acknowledge and agree that you shall retrieve data only with the user's explicit -consent and only when, and for the limited purposes for which, the user has given you permission to do so. - -9. **Terminating this License Agreement** - - - 9.1 The License Agreement will continue to apply until terminated by either you or Anduril as set out below. - - 9.2 If you want to terminate the License Agreement, you may do so by ceasing your use of the SDK and any relevant developer -credentials. - - 9.3 Anduril may at any time, terminate the License Agreement with you if: (i) you have breached any provision of the License Agreement; -or (ii) Anduril is required to do so by law; or (iii) the partner with whom Anduril offered certain parts of SDK (such as APIs) to you has -terminated its relationship with Anduril or ceased to offer certain parts of the SDK to you; or (iv) Anduril decides to no longer provide the -SDK to you, or (v) in Anduril's sole discretion, it is no longer commercially viable to provide the SDK. - - 9.4 When the License Agreement comes to an end, you shall delete all copies in your possession of the SDK, and discontinue using the -SDK and related APIs.The provisions of paragraph 14.7 shall continue to apply indefinitely. - -10. **DISCLAIMER OF WARRANTIES** - - - 10.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT YOUR USE OF THE SDK IS AT YOUR SOLE RISK AND THAT THE SDK -IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTY OF ANY KIND FROM ANDURIL. - - 10.2 YOUR USE OF THE SDK AND ANY MATERIAL DOWNLOADED OR OTHERWISE OBTAINED THROUGH THE USE OF THE -SDK IS AT YOUR OWN DISCRETION AND RISK AND YOU ARE SOLELY RESPONSIBLE FOR ANY DAMAGE TO YOUR COMPUTER -SYSTEM OR OTHER DEVICE OR LOSS OF DATA THAT RESULTS FROM SUCH USE. - - 10.3 ANDURIL FURTHER EXPRESSLY DISCLAIMS ALL WARRANTIES AND CONDITIONS OF ANY KIND, WHETHER EXPRESS OR -IMPLIED, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. - -11. **LIMITATION OF LIABILITY** - - - 11.1 YOU EXPRESSLY UNDERSTAND AND AGREE THAT ANDURIL, ITS SUBSIDIARIES AND AFFILIATES, AND ITS LICENSORS -SHALL NOT BE LIABLE TO YOU UNDER ANY THEORY OF LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -CONSEQUENTIAL OR EXEMPLARY DAMAGES THAT MAY BE INCURRED BY YOU, INCLUDING ANY LOSS OF DATA, WHETHER -OR NOT ANDURIL OR ITS REPRESENTATIVES HAVE BEEN ADVISED OF OR SHOULD HAVE BEEN AWARE OF THE POSSIBILITY -OF ANY SUCH LOSSES ARISING. - -12. **Indemnification** - - - 12.1 To the maximum extent permitted by law, you agree to defend, indemnify and hold harmless Anduril, its affiliates and their respective -directors, officers, employees and agents from and against any and all claims, actions, suits or proceedings, as well as any and all losses, -liabilities, damages, costs and expenses (including reasonable attorneys fees) arising out of or accruing from (a) your use of the SDK, -(b) any application you develop on the SDK that infringes any copyright, trademark, trade secret, trade dress, patent or other intellectual -property right of any person or defames any person or violates their rights of publicity or privacy, and (c) any non-compliance by you with -the License Agreement. - -13. **Changes to the License Agreement** - - - 13.1 Anduril may make changes to the License Agreement as it distributes new versions of the SDK. When these changes are made, -Anduril will make a new version of the License Agreement available on the website where the SDK is made available. - -14. **General Legal Terms** - - - 14.1 The License Agreement constitutes the whole legal agreement between you and Anduril and governs your use of the SDK (excluding -any services which Anduril may provide to you under a separate written agreement), and completely replaces any prior agreements -between you and Anduril in relation to the SDK. - - 14.2 You agree that if Anduril does not exercise or enforce any legal right or remedy which is contained in the License Agreement (or -which Anduril has the benefit of under any applicable law), this will not be taken to be a formal waiver of Anduril's rights and that those -rights or remedies will still be available to Anduril. - - 14.3 If any court of law, having the jurisdiction to decide on this matter, rules that any provision of the License Agreement is invalid, then -that provision will be removed from the License Agreement without affecting the rest of the License Agreement. The remaining provisions -of the License Agreement will continue to be valid and enforceable. - - 14.4 You acknowledge and agree that any subsidiaries or affiliates of Anduril is the parent shall be third party beneficiaries to the License -Agreement and that such other companies shall be entitled to directly enforce, and rely upon, any provision of the License Agreement -that confers a benefit on (or rights in favor of) them. Other than this, no other person or company shall be third party beneficiaries to the -License Agreement. - - 14.5 EXPORT RESTRICTIONS. YOU MAY NOT EXPORT THIS LICENSE. THE SDK MAY BE SUBJECT TO UNITED STATES EXPORT -LAWS AND REGULATIONS. YOU MUST COMPLY WITH ALL DOMESTIC AND INTERNATIONAL EXPORT LAWS AND -REGULATIONS THAT APPLY TO THE SDK. THESE LAWS INCLUDE RESTRICTIONS ON DESTINATIONS, END USERS AND END -USE. - - 14.6 The rights granted in the License Agreement may not be assigned or transferred by either you or Anduril without the prior written -approval of the other party. Neither you nor Anduril shall be permitted to delegate their responsibilities or obligations under the License -Agreement without the prior written approval of the other party. - - 14.7 The License Agreement, and your relationship with Anduril under the License Agreement, shall be governed by the laws of the State -of Delaware without regard to its conflict of laws provisions. Except for claims for injunctive or equitable relief, and claims regarding -intellectual property rights to the extent not relating to indemnification under this Agreement (all of which may be brought in any competent -state or federal court), any dispute arising under this Agreement shall be finally settled in accordance with the Comprehensive Arbitration -Rules of the Judicial Arbitration and Mediation Service, Inc. (“JAMS”) by three arbitrators appointed in accordance with such Rules. The -arbitration shall take place in Irvine, California and the arbitral decision may be enforced in any competent U.S. federal court. In the event -of any court action, you agree to submit to the exclusive jurisdiction of the courts located in the city of Irvine located in Orange, California. -Notwithstanding this, you agree that Anduril shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal -relief) in any jurisdiction. - -**April 14, 2025** \ No newline at end of file diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/README.md b/vendor/github.com/anduril/lattice-sdk-go/v2/README.md deleted file mode 100644 index 206d7f4..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/README.md +++ /dev/null @@ -1,164 +0,0 @@ -# Lattice SDK Go library - -![](https://www.anduril.com/lattice-sdk/) - -The Lattice SDK Go library provides convenient access to the Lattice API from Go. - -## Documentation - -API reference documentation is available [here](https://developer.anduril.com/). - -## Requirements - -To use the SDK please ensure you have the following installed: - -* [Go](https://go.dev/doc/install) - -## Installation - -Install the Lattice SDK package with - -``` -go get github.com/anduril/lattice-sdk-go/v2 -``` - -## Support - -For support with this library please reach out to your Anduril representative. - -## Usage - -Instantiate and use the client with the following: - -```go -package example - -import ( - client "github.com/anduril/lattice-sdk-go/v2/client" - option "github.com/anduril/lattice-sdk-go/v2/option" - context "context" - Lattice "github.com/anduril/lattice-sdk-go/v2" -) - -func do() { - client := client.NewClient( - option.WithToken( - "", - ), - ) - client.Entities.LongPollEntityEvents( - context.TODO(), - &Lattice.EntityEventRequest{ - SessionToken: "sessionToken", - }, - ) -} -``` - -## Environments - -You can choose between different environments by using the `option.WithBaseURL` option. You can configure any arbitrary base -URL, which is particularly useful in test environments. - -```go -client := client.NewClient( - option.WithBaseURL(Lattice.Environments.Default), -) -``` - -## Errors - -Structured error types are returned from API calls that return non-success status codes. These errors are compatible -with the `errors.Is` and `errors.As` APIs, so you can access the error like so: - -```go -response, err := client.Entities.LongPollEntityEvents(...) -if err != nil { - var apiError *core.APIError - if errors.As(err, apiError) { - // Do something with the API error ... - } - return err -} -``` - -## Request Options - -A variety of request options are included to adapt the behavior of the library, which includes configuring -authorization tokens, or providing your own instrumented `*http.Client`. - -These request options can either be -specified on the client so that they're applied on every request, or for an individual request, like so: - -> Providing your own `*http.Client` is recommended. Otherwise, the `http.DefaultClient` will be used, -> and your client will wait indefinitely for a response (unless the per-request, context-based timeout -> is used). - -```go -// Specify default options applied on every request. -client := client.NewClient( - option.WithToken(""), - option.WithHTTPClient( - &http.Client{ - Timeout: 5 * time.Second, - }, - ), -) - -// Specify options for an individual request. -response, err := client.Entities.LongPollEntityEvents( - ..., - option.WithToken(""), -) -``` - -## Advanced - -### Response Headers - -You can access the raw HTTP response data by using the `WithRawResponse` field on the client. This is useful -when you need to examine the response headers received from the API call. - -```go -response, err := client.Entities.WithRawResponse.LongPollEntityEvents(...) -if err != nil { - return err -} -fmt.Printf("Got response headers: %v", response.Header) -``` - -### Retries - -The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long -as the request is deemed retryable and the number of retry attempts has not grown larger than the configured -retry limit (default: 2). - -A request is deemed retryable when any of the following HTTP status codes is returned: - -- [408](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) (Timeout) -- [429](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) (Too Many Requests) -- [5XX](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) (Internal Server Errors) - -Use the `option.WithMaxAttempts` option to configure this behavior for the entire client or an individual request: - -```go -client := client.NewClient( - option.WithMaxAttempts(1), -) - -response, err := client.Entities.LongPollEntityEvents( - ..., - option.WithMaxAttempts(1), -) -``` - -### Timeouts - -Setting a timeout for each individual request is as simple as using the standard context library. Setting a one second timeout for an individual API call looks like the following: - -```go -ctx, cancel := context.WithTimeout(ctx, time.Second) -defer cancel() - -response, err := client.Entities.LongPollEntityEvents(ctx, ...) -``` diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/SECURITY.md b/vendor/github.com/anduril/lattice-sdk-go/v2/SECURITY.md deleted file mode 100644 index ffa35e9..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/SECURITY.md +++ /dev/null @@ -1,5 +0,0 @@ -# Security Policy - -## Reporting a Vulnerability - -Please report any security issues to the Anduril Information Security team using the email disclosures@anduril.com. Additional information including our pgp key can be found in the [security.txt page](https://www.anduril.com/.well-known/security.txt) of our website. diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/client/client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/client/client.go deleted file mode 100644 index a799ecb..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/client/client.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package client - -import ( - core "github.com/anduril/lattice-sdk-go/v2/core" - entities "github.com/anduril/lattice-sdk-go/v2/entities" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - objects "github.com/anduril/lattice-sdk-go/v2/objects" - option "github.com/anduril/lattice-sdk-go/v2/option" - tasks "github.com/anduril/lattice-sdk-go/v2/tasks" - http "net/http" -) - -type Client struct { - Entities *entities.Client - Tasks *tasks.Client - Objects *objects.Client - - baseURL string - caller *internal.Caller - header http.Header -} - -func NewClient(opts ...option.RequestOption) *Client { - options := core.NewRequestOptions(opts...) - return &Client{ - Entities: entities.NewClient(opts...), - Tasks: tasks.NewClient(opts...), - Objects: objects.NewClient(opts...), - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/core/api_error.go b/vendor/github.com/anduril/lattice-sdk-go/v2/core/api_error.go deleted file mode 100644 index 6168388..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/core/api_error.go +++ /dev/null @@ -1,47 +0,0 @@ -package core - -import ( - "fmt" - "net/http" -) - -// APIError is a lightweight wrapper around the standard error -// interface that preserves the status code from the RPC, if any. -type APIError struct { - err error - - StatusCode int `json:"-"` - Header http.Header `json:"-"` -} - -// NewAPIError constructs a new API error. -func NewAPIError(statusCode int, header http.Header, err error) *APIError { - return &APIError{ - err: err, - Header: header, - StatusCode: statusCode, - } -} - -// Unwrap returns the underlying error. This also makes the error compatible -// with errors.As and errors.Is. -func (a *APIError) Unwrap() error { - if a == nil { - return nil - } - return a.err -} - -// Error returns the API error's message. -func (a *APIError) Error() string { - if a == nil || (a.err == nil && a.StatusCode == 0) { - return "" - } - if a.err == nil { - return fmt.Sprintf("%d", a.StatusCode) - } - if a.StatusCode == 0 { - return a.err.Error() - } - return fmt.Sprintf("%d: %s", a.StatusCode, a.err.Error()) -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/core/http.go b/vendor/github.com/anduril/lattice-sdk-go/v2/core/http.go deleted file mode 100644 index 92c4356..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/core/http.go +++ /dev/null @@ -1,15 +0,0 @@ -package core - -import "net/http" - -// HTTPClient is an interface for a subset of the *http.Client. -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Response is an HTTP response from an HTTP client. -type Response[T any] struct { - StatusCode int - Header http.Header - Body T -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/core/page.go b/vendor/github.com/anduril/lattice-sdk-go/v2/core/page.go deleted file mode 100644 index 96badc7..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/core/page.go +++ /dev/null @@ -1,70 +0,0 @@ -package core - -import ( - "context" - "errors" -) - -// ErrNoPages is a sentinel error used to signal that no pages remain. -// -// This error should be used similar to io.EOF, such that it represents -// a non-actionable error. -var ErrNoPages = errors.New("no pages remain") - -// Page represents a single page of results. -type Page[T any] struct { - Results []T - NextPageFunc func(context.Context) (*Page[T], error) -} - -// GetNextPage fetches the next page, if any. If no pages remain, -// the ErrNoPages error is returned. -func (p *Page[T]) GetNextPage(ctx context.Context) (*Page[T], error) { - return p.NextPageFunc(ctx) -} - -// Iterator returns an iterator that starts at the current page. -func (p *Page[T]) Iterator() *PageIterator[T] { - return &PageIterator[T]{ - page: p, - } -} - -// PageIterator is an auto-iterator for paginated endpoints. -type PageIterator[T any] struct { - page *Page[T] - current T - index int - err error -} - -// Next returns true if the given iterator has more results, -// fetching the next page as needed. -func (p *PageIterator[T]) Next(ctx context.Context) bool { - if p.page == nil || len(p.page.Results) == 0 { - return false - } - if p.index >= len(p.page.Results) { - p.index = 0 - p.page, p.err = p.page.GetNextPage(ctx) - if p.err != nil || p.page == nil || len(p.page.Results) == 0 { - return false - } - } - p.current = p.page.Results[p.index] - p.index += 1 - return true -} - -// Current returns the current element. -func (p *PageIterator[T]) Current() T { - return p.current -} - -// Err returns a non-nil error if the iterator encountered an error. -func (p *PageIterator[T]) Err() error { - if errors.Is(p.err, ErrNoPages) { - return nil - } - return p.err -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/core/request_option.go b/vendor/github.com/anduril/lattice-sdk-go/v2/core/request_option.go deleted file mode 100644 index 09ceed2..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/core/request_option.go +++ /dev/null @@ -1,125 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package core - -import ( - http "net/http" - url "net/url" -) - -// RequestOption adapts the behavior of the client or an individual request. -type RequestOption interface { - applyRequestOptions(*RequestOptions) -} - -// RequestOptions defines all of the possible request options. -// -// This type is primarily used by the generated code and is not meant -// to be used directly; use the option package instead. -type RequestOptions struct { - BaseURL string - HTTPClient HTTPClient - HTTPHeader http.Header - BodyProperties map[string]interface{} - QueryParameters url.Values - MaxAttempts uint - Token string -} - -// NewRequestOptions returns a new *RequestOptions value. -// -// This function is primarily used by the generated code and is not meant -// to be used directly; use RequestOption instead. -func NewRequestOptions(opts ...RequestOption) *RequestOptions { - options := &RequestOptions{ - HTTPHeader: make(http.Header), - BodyProperties: make(map[string]interface{}), - QueryParameters: make(url.Values), - } - for _, opt := range opts { - opt.applyRequestOptions(options) - } - return options -} - -// ToHeader maps the configured request options into a http.Header used -// for the request(s). -func (r *RequestOptions) ToHeader() http.Header { - header := r.cloneHeader() - if r.Token != "" { - header.Set("Authorization", "Bearer "+r.Token) - } - return header -} - -func (r *RequestOptions) cloneHeader() http.Header { - headers := r.HTTPHeader.Clone() - headers.Set("X-Fern-Language", "Go") - headers.Set("X-Fern-SDK-Name", "github.com/anduril/lattice-sdk-go/v2") - headers.Set("X-Fern-SDK-Version", "v2.2.0") - headers.Set("User-Agent", "github.com/anduril/lattice-sdk-go/2.2.0") - return headers -} - -// BaseURLOption implements the RequestOption interface. -type BaseURLOption struct { - BaseURL string -} - -func (b *BaseURLOption) applyRequestOptions(opts *RequestOptions) { - opts.BaseURL = b.BaseURL -} - -// HTTPClientOption implements the RequestOption interface. -type HTTPClientOption struct { - HTTPClient HTTPClient -} - -func (h *HTTPClientOption) applyRequestOptions(opts *RequestOptions) { - opts.HTTPClient = h.HTTPClient -} - -// HTTPHeaderOption implements the RequestOption interface. -type HTTPHeaderOption struct { - HTTPHeader http.Header -} - -func (h *HTTPHeaderOption) applyRequestOptions(opts *RequestOptions) { - opts.HTTPHeader = h.HTTPHeader -} - -// BodyPropertiesOption implements the RequestOption interface. -type BodyPropertiesOption struct { - BodyProperties map[string]interface{} -} - -func (b *BodyPropertiesOption) applyRequestOptions(opts *RequestOptions) { - opts.BodyProperties = b.BodyProperties -} - -// QueryParametersOption implements the RequestOption interface. -type QueryParametersOption struct { - QueryParameters url.Values -} - -func (q *QueryParametersOption) applyRequestOptions(opts *RequestOptions) { - opts.QueryParameters = q.QueryParameters -} - -// MaxAttemptsOption implements the RequestOption interface. -type MaxAttemptsOption struct { - MaxAttempts uint -} - -func (m *MaxAttemptsOption) applyRequestOptions(opts *RequestOptions) { - opts.MaxAttempts = m.MaxAttempts -} - -// TokenOption implements the RequestOption interface. -type TokenOption struct { - Token string -} - -func (t *TokenOption) applyRequestOptions(opts *RequestOptions) { - opts.Token = t.Token -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/core/stream.go b/vendor/github.com/anduril/lattice-sdk-go/v2/core/stream.go deleted file mode 100644 index 85e8508..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/core/stream.go +++ /dev/null @@ -1,328 +0,0 @@ -package core - -import ( - "bufio" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "slices" - "strings" -) - -type StreamFormat string - -const ( - StreamFormatSSE StreamFormat = "sse" - StreamFormatEmpty StreamFormat = "" -) - -const ( - defaultMaxBufSize = 64 * 1024 // 64KB -) - -// defaultStreamDelimiter is the default stream delimiter used to split messages. -const defaultStreamDelimiter = '\n' - -// Stream represents a stream of messages sent from a server. -type Stream[T any] struct { - reader streamReader - closer io.Closer -} - -// StreamOption adapts the behavior of the Stream. -type StreamOption func(*streamOptions) - -// WithDelimiter overrides the delimiter for the Stream. -// -// By default, the Stream is newline-delimited. -func WithDelimiter(delimiter string) StreamOption { - return func(opts *streamOptions) { - opts.delimiter = delimiter - } -} - -// WithPrefix overrides the prefix for the Stream. -// -// By default, the Stream doesn't have a prefix. -func WithPrefix(prefix string) StreamOption { - return func(opts *streamOptions) { - opts.prefix = prefix - } -} - -// WithTerminator overrides the terminator for the Stream. -// -// By default, the Stream terminates on EOF. -func WithTerminator(terminator string) StreamOption { - return func(opts *streamOptions) { - opts.terminator = terminator - } -} - -// WithFormat overrides the isSSE flag for the Stream. -// -// By default, the Stream is not SSE. -func WithFormat(format StreamFormat) StreamOption { - return func(opts *streamOptions) { - opts.format = format - } -} - -// NewStream constructs a new Stream from the given *http.Response. -func NewStream[T any](response *http.Response, opts ...StreamOption) *Stream[T] { - options := new(streamOptions) - for _, opt := range opts { - opt(options) - } - return &Stream[T]{ - reader: newStreamReader(response.Body, options), - closer: response.Body, - } -} - -// Recv reads a message from the stream, returning io.EOF when -// all the messages have been read. -func (s Stream[T]) Recv() (T, error) { - var value T - bytes, err := s.reader.ReadFromStream() - if err != nil { - return value, err - } - if err := json.Unmarshal(bytes, &value); err != nil { - return value, err - } - return value, nil -} - -// Close closes the Stream. -func (s Stream[T]) Close() error { - return s.closer.Close() -} - -// streamReader reads data from a stream. -type streamReader interface { - ReadFromStream() ([]byte, error) -} - -// newStreamReader returns a new streamReader based on the given -// delimiter. -// -// By default, the streamReader uses a simple a *bufio.Reader -// which splits on newlines, and otherwise use a *bufio.Scanner to -// split on custom delimiters. -func newStreamReader(reader io.Reader, options *streamOptions) streamReader { - if !options.isEmpty() { - if options.maxBufSize == 0 { - options.maxBufSize = defaultMaxBufSize - } - if options.delimiter == "" { - options.delimiter = string(defaultStreamDelimiter) - } - if options.format == StreamFormatSSE { - return newSseStreamReader(reader, options) - } - return newScannerStreamReader(reader, options) - } - return newBufferStreamReader(reader) -} - -// BufferStreamReader reads data from a *bufio.Reader, which splits -// on newlines. -type BufferStreamReader struct { - reader *bufio.Reader -} - -func newBufferStreamReader(reader io.Reader) *BufferStreamReader { - return &BufferStreamReader{ - reader: bufio.NewReader(reader), - } -} - -func (b *BufferStreamReader) ReadFromStream() ([]byte, error) { - return b.reader.ReadBytes(defaultStreamDelimiter) -} - -// ScannerStreamReader reads data from a *bufio.Scanner, which allows for -// configurable delimiters. -type ScannerStreamReader struct { - scanner *bufio.Scanner - options *streamOptions -} - -func newScannerStreamReader( - reader io.Reader, - options *streamOptions, -) *ScannerStreamReader { - scanner := bufio.NewScanner(reader) - stream := &ScannerStreamReader{ - scanner: scanner, - options: options, - } - scanner.Split(func(bytes []byte, atEOF bool) (int, []byte, error) { - if atEOF && len(bytes) == 0 { - return 0, nil, nil - } - n, data, err := stream.parse(bytes) - if stream.isTerminated(data) { - return 0, nil, io.EOF - } - return n, data, err - }) - return stream -} - -func (s *ScannerStreamReader) ReadFromStream() ([]byte, error) { - if s.scanner.Scan() { - return s.scanner.Bytes(), nil - } - if err := s.scanner.Err(); err != nil { - return nil, err - } - return nil, io.EOF -} - -func (s *ScannerStreamReader) parse(bytes []byte) (int, []byte, error) { - var startIndex int - if s.options != nil && s.options.prefix != "" { - if i := strings.Index(string(bytes), s.options.prefix); i >= 0 { - startIndex = i + len(s.options.prefix) - } - } - data := bytes[startIndex:] - delimIndex := strings.Index(string(data), s.options.delimiter) - if delimIndex < 0 { - return startIndex + len(data), data, nil - } - endIndex := delimIndex + len(s.options.delimiter) - parsedData := data[:endIndex] - n := startIndex + endIndex - return n, parsedData, nil -} - -func (s *ScannerStreamReader) isTerminated(bytes []byte) bool { - if s.options == nil || s.options.terminator == "" { - return false - } - return strings.Contains(string(bytes), s.options.terminator) -} - -type streamOptions struct { - delimiter string - prefix string - terminator string - format StreamFormat - maxBufSize int -} - -func (s *streamOptions) isEmpty() bool { - return s.delimiter == "" && s.prefix == "" && s.terminator == "" && s.format == StreamFormatEmpty -} - -// SseStreamReader reads data from a *bufio.Scanner, which allows for -// configurable delimiters. -type SseStreamReader struct { - scanner *bufio.Scanner - options *streamOptions -} - -func newSseStreamReader( - reader io.Reader, - options *streamOptions, -) *SseStreamReader { - scanner := bufio.NewScanner(reader) - stream := &SseStreamReader{ - scanner: scanner, - options: options, - } - scanner.Buffer(make([]byte, slices.Min([]int{4096, options.maxBufSize})), options.maxBufSize) - scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF && len(data) == 0 { - return 0, nil, nil - } - if i := strings.Index(string(data), stream.options.delimiter+stream.options.delimiter); i >= 0 { - return i + 1, data[0:i], nil - } - - if atEOF || stream.isTerminated(data) { - return len(data), data, nil - } - return 0, nil, nil - }) - return stream -} - -func (s *SseStreamReader) isTerminated(bytes []byte) bool { - if s.options == nil || s.options.terminator == "" { - return false - } - return strings.Contains(string(bytes), s.options.terminator) -} - -func (s *SseStreamReader) ReadFromStream() ([]byte, error) { - - event, err := s.nextEvent() - if err != nil { - return nil, err - } - return event.data, nil -} - -func (s *SseStreamReader) nextEvent() (*SseEvent, error) { - - event := SseEvent{} - if s.scanner.Scan() { - rawEvent := s.scanner.Bytes() - - lines := strings.Split(string(rawEvent), s.options.delimiter) - for _, line := range lines { - s.parseSseLine([]byte(line), &event) - } - - if event.size() > s.options.maxBufSize { - return nil, errors.New("SseStreamReader.ReadFromStream: buffer limit exceeded") - } - return &event, nil - } - return &event, io.EOF -} - -func (s *SseStreamReader) parseSseLine(_bytes []byte, event *SseEvent) error { - if bytes.HasPrefix(_bytes, sseDataPrefix) { - if len(event.data) > 0 { - event.data = append(event.data, s.options.delimiter...) - } - event.data = append(event.data, _bytes[len(sseDataPrefix):]...) - } else if bytes.HasPrefix(_bytes, sseIdPrefix) { - event.id = append(event.id, _bytes[len(sseIdPrefix):]...) - } else if bytes.HasPrefix(_bytes, sseEventPrefix) { - event.event = append(event.event, _bytes[len(sseEventPrefix):]...) - } else if bytes.HasPrefix(_bytes, sseRetryPrefix) { - event.retry = append(event.retry, _bytes[len(sseRetryPrefix):]...) - } - return nil -} - -func (event *SseEvent) size() int { - return len(event.id) + len(event.data) + len(event.event) + len(event.retry) -} - -func (event *SseEvent) String() string { - return fmt.Sprintf("SseEvent{id: %q, event: %q, data: %q, retry: %q}", event.id, event.event, event.data, event.retry) -} - -type SseEvent struct { - id []byte - data []byte - event []byte - retry []byte -} - -var ( - sseIdPrefix = []byte("id: ") - sseDataPrefix = []byte("data: ") - sseEventPrefix = []byte("event: ") - sseRetryPrefix = []byte("retry: ") -) diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/entities.go b/vendor/github.com/anduril/lattice-sdk-go/v2/entities.go deleted file mode 100644 index 0f57198..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/entities.go +++ /dev/null @@ -1,532 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package Lattice - -import ( - json "encoding/json" - fmt "fmt" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - time "time" -) - -type EntityEventRequest struct { - // Long-poll session identifier. Leave empty to start a new polling session. - SessionToken string `json:"sessionToken" url:"-"` - // Maximum size of response batch. Defaults to 100. Must be between 1 and 2000 (inclusive). - BatchSize *int `json:"batchSize,omitempty" url:"-"` -} - -type EntityOverride struct { - // The entity containing the overridden fields. The service will extract the overridable fields from - // the object and ignore all other fields. - Entity *Entity `json:"entity,omitempty" url:"-"` - // Additional information about the source of the override. - Provenance *Provenance `json:"provenance,omitempty" url:"-"` -} - -type EntityStreamRequest struct { - // at what interval to send heartbeat events, defaults to 30s. - HeartbeatIntervalMs *int `json:"heartbeatIntervalMS,omitempty" url:"-"` - // only stream pre-existing entities in the environment and then close the connection, defaults to false. - PreExistingOnly *bool `json:"preExistingOnly,omitempty" url:"-"` - // list of components to include, leave empty to include all components. - ComponentsToInclude []string `json:"componentsToInclude,omitempty" url:"-"` -} - -// Event representing some type of entity change. -type EntityEvent struct { - EventType *EntityEventEventType `json:"eventType,omitempty" url:"eventType,omitempty"` - Time *time.Time `json:"time,omitempty" url:"time,omitempty"` - Entity *Entity `json:"entity,omitempty" url:"entity,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *EntityEvent) GetEventType() *EntityEventEventType { - if e == nil { - return nil - } - return e.EventType -} - -func (e *EntityEvent) GetTime() *time.Time { - if e == nil { - return nil - } - return e.Time -} - -func (e *EntityEvent) GetEntity() *Entity { - if e == nil { - return nil - } - return e.Entity -} - -func (e *EntityEvent) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *EntityEvent) UnmarshalJSON(data []byte) error { - type embed EntityEvent - var unmarshaler = struct { - embed - Time *internal.DateTime `json:"time,omitempty"` - }{ - embed: embed(*e), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *e = EntityEvent(unmarshaler.embed) - e.Time = unmarshaler.Time.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *EntityEvent) MarshalJSON() ([]byte, error) { - type embed EntityEvent - var marshaler = struct { - embed - Time *internal.DateTime `json:"time,omitempty"` - }{ - embed: embed(*e), - Time: internal.NewOptionalDateTime(e.Time), - } - return json.Marshal(marshaler) -} - -func (e *EntityEvent) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -type EntityEventEventType string - -const ( - EntityEventEventTypeEventTypeInvalid EntityEventEventType = "EVENT_TYPE_INVALID" - EntityEventEventTypeEventTypeCreated EntityEventEventType = "EVENT_TYPE_CREATED" - EntityEventEventTypeEventTypeUpdate EntityEventEventType = "EVENT_TYPE_UPDATE" - EntityEventEventTypeEventTypeDeleted EntityEventEventType = "EVENT_TYPE_DELETED" - EntityEventEventTypeEventTypePreexisting EntityEventEventType = "EVENT_TYPE_PREEXISTING" - EntityEventEventTypeEventTypePostExpiryOverride EntityEventEventType = "EVENT_TYPE_POST_EXPIRY_OVERRIDE" -) - -func NewEntityEventEventTypeFromString(s string) (EntityEventEventType, error) { - switch s { - case "EVENT_TYPE_INVALID": - return EntityEventEventTypeEventTypeInvalid, nil - case "EVENT_TYPE_CREATED": - return EntityEventEventTypeEventTypeCreated, nil - case "EVENT_TYPE_UPDATE": - return EntityEventEventTypeEventTypeUpdate, nil - case "EVENT_TYPE_DELETED": - return EntityEventEventTypeEventTypeDeleted, nil - case "EVENT_TYPE_PREEXISTING": - return EntityEventEventTypeEventTypePreexisting, nil - case "EVENT_TYPE_POST_EXPIRY_OVERRIDE": - return EntityEventEventTypeEventTypePostExpiryOverride, nil - } - var t EntityEventEventType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (e EntityEventEventType) Ptr() *EntityEventEventType { - return &e -} - -type EntityEventResponse struct { - // Long-poll session identifier. Use this token to resume polling on subsequent requests. - SessionToken *string `json:"sessionToken,omitempty" url:"sessionToken,omitempty"` - EntityEvents []*EntityEvent `json:"entityEvents,omitempty" url:"entityEvents,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *EntityEventResponse) GetSessionToken() *string { - if e == nil { - return nil - } - return e.SessionToken -} - -func (e *EntityEventResponse) GetEntityEvents() []*EntityEvent { - if e == nil { - return nil - } - return e.EntityEvents -} - -func (e *EntityEventResponse) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *EntityEventResponse) UnmarshalJSON(data []byte) error { - type unmarshaler EntityEventResponse - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = EntityEventResponse(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *EntityEventResponse) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -type EntityStreamEvent struct { - EventType *EntityEventEventType `json:"eventType,omitempty" url:"eventType,omitempty"` - Time *time.Time `json:"time,omitempty" url:"time,omitempty"` - Entity *Entity `json:"entity,omitempty" url:"entity,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *EntityStreamEvent) GetEventType() *EntityEventEventType { - if e == nil { - return nil - } - return e.EventType -} - -func (e *EntityStreamEvent) GetTime() *time.Time { - if e == nil { - return nil - } - return e.Time -} - -func (e *EntityStreamEvent) GetEntity() *Entity { - if e == nil { - return nil - } - return e.Entity -} - -func (e *EntityStreamEvent) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *EntityStreamEvent) UnmarshalJSON(data []byte) error { - type embed EntityStreamEvent - var unmarshaler = struct { - embed - Time *internal.DateTime `json:"time,omitempty"` - }{ - embed: embed(*e), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *e = EntityStreamEvent(unmarshaler.embed) - e.Time = unmarshaler.Time.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *EntityStreamEvent) MarshalJSON() ([]byte, error) { - type embed EntityStreamEvent - var marshaler = struct { - embed - Time *internal.DateTime `json:"time,omitempty"` - }{ - embed: embed(*e), - Time: internal.NewOptionalDateTime(e.Time), - } - return json.Marshal(marshaler) -} - -func (e *EntityStreamEvent) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -type EntityStreamHeartbeat struct { - // timestamp of the heartbeat - Timestamp *time.Time `json:"timestamp,omitempty" url:"timestamp,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *EntityStreamHeartbeat) GetTimestamp() *time.Time { - if e == nil { - return nil - } - return e.Timestamp -} - -func (e *EntityStreamHeartbeat) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *EntityStreamHeartbeat) UnmarshalJSON(data []byte) error { - type embed EntityStreamHeartbeat - var unmarshaler = struct { - embed - Timestamp *internal.DateTime `json:"timestamp,omitempty"` - }{ - embed: embed(*e), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *e = EntityStreamHeartbeat(unmarshaler.embed) - e.Timestamp = unmarshaler.Timestamp.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *EntityStreamHeartbeat) MarshalJSON() ([]byte, error) { - type embed EntityStreamHeartbeat - var marshaler = struct { - embed - Timestamp *internal.DateTime `json:"timestamp,omitempty"` - }{ - embed: embed(*e), - Timestamp: internal.NewOptionalDateTime(e.Timestamp), - } - return json.Marshal(marshaler) -} - -func (e *EntityStreamHeartbeat) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -type HeartbeatObject struct { - // timestamp of the heartbeat - Timestamp *time.Time `json:"timestamp,omitempty" url:"timestamp,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (h *HeartbeatObject) GetTimestamp() *time.Time { - if h == nil { - return nil - } - return h.Timestamp -} - -func (h *HeartbeatObject) GetExtraProperties() map[string]interface{} { - return h.extraProperties -} - -func (h *HeartbeatObject) UnmarshalJSON(data []byte) error { - type embed HeartbeatObject - var unmarshaler = struct { - embed - Timestamp *internal.DateTime `json:"timestamp,omitempty"` - }{ - embed: embed(*h), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *h = HeartbeatObject(unmarshaler.embed) - h.Timestamp = unmarshaler.Timestamp.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *h) - if err != nil { - return err - } - h.extraProperties = extraProperties - h.rawJSON = json.RawMessage(data) - return nil -} - -func (h *HeartbeatObject) MarshalJSON() ([]byte, error) { - type embed HeartbeatObject - var marshaler = struct { - embed - Timestamp *internal.DateTime `json:"timestamp,omitempty"` - }{ - embed: embed(*h), - Timestamp: internal.NewOptionalDateTime(h.Timestamp), - } - return json.Marshal(marshaler) -} - -func (h *HeartbeatObject) String() string { - if len(h.rawJSON) > 0 { - if value, err := internal.StringifyJSON(h.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(h); err == nil { - return value - } - return fmt.Sprintf("%#v", h) -} - -// The stream event response. -type StreamEntitiesResponse struct { - Event string - Heartbeat *EntityStreamHeartbeat - Entity *EntityStreamEvent -} - -func (s *StreamEntitiesResponse) GetEvent() string { - if s == nil { - return "" - } - return s.Event -} - -func (s *StreamEntitiesResponse) GetHeartbeat() *EntityStreamHeartbeat { - if s == nil { - return nil - } - return s.Heartbeat -} - -func (s *StreamEntitiesResponse) GetEntity() *EntityStreamEvent { - if s == nil { - return nil - } - return s.Entity -} - -func (s *StreamEntitiesResponse) UnmarshalJSON(data []byte) error { - var unmarshaler struct { - Event string `json:"event"` - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - s.Event = unmarshaler.Event - if unmarshaler.Event == "" { - return fmt.Errorf("%T did not include discriminant event", s) - } - switch unmarshaler.Event { - case "heartbeat": - value := new(EntityStreamHeartbeat) - if err := json.Unmarshal(data, &value); err != nil { - return err - } - s.Heartbeat = value - case "entity": - value := new(EntityStreamEvent) - if err := json.Unmarshal(data, &value); err != nil { - return err - } - s.Entity = value - } - return nil -} - -func (s StreamEntitiesResponse) MarshalJSON() ([]byte, error) { - if err := s.validate(); err != nil { - return nil, err - } - if s.Heartbeat != nil { - return internal.MarshalJSONWithExtraProperty(s.Heartbeat, "event", "heartbeat") - } - if s.Entity != nil { - return internal.MarshalJSONWithExtraProperty(s.Entity, "event", "entity") - } - return nil, fmt.Errorf("type %T does not define a non-empty union type", s) -} - -type StreamEntitiesResponseVisitor interface { - VisitHeartbeat(*EntityStreamHeartbeat) error - VisitEntity(*EntityStreamEvent) error -} - -func (s *StreamEntitiesResponse) Accept(visitor StreamEntitiesResponseVisitor) error { - if s.Heartbeat != nil { - return visitor.VisitHeartbeat(s.Heartbeat) - } - if s.Entity != nil { - return visitor.VisitEntity(s.Entity) - } - return fmt.Errorf("type %T does not define a non-empty union type", s) -} - -func (s *StreamEntitiesResponse) validate() error { - if s == nil { - return fmt.Errorf("type %T is nil", s) - } - var fields []string - if s.Heartbeat != nil { - fields = append(fields, "heartbeat") - } - if s.Entity != nil { - fields = append(fields, "entity") - } - if len(fields) == 0 { - if s.Event != "" { - return fmt.Errorf("type %T defines a discriminant set to %q but the field is not set", s, s.Event) - } - return fmt.Errorf("type %T is empty", s) - } - if len(fields) > 1 { - return fmt.Errorf("type %T defines values for %s, but only one value is allowed", s, fields) - } - if s.Event != "" { - field := fields[0] - if s.Event != field { - return fmt.Errorf( - "type %T defines a discriminant set to %q, but it does not match the %T field; either remove or update the discriminant to match", - s, - s.Event, - s, - ) - } - } - return nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/entities/client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/entities/client.go deleted file mode 100644 index f19b9f7..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/entities/client.go +++ /dev/null @@ -1,201 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package entities - -import ( - context "context" - v2 "github.com/anduril/lattice-sdk-go/v2" - core "github.com/anduril/lattice-sdk-go/v2/core" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - option "github.com/anduril/lattice-sdk-go/v2/option" - http "net/http" -) - -type Client struct { - WithRawResponse *RawClient - - baseURL string - caller *internal.Caller - header http.Header -} - -func NewClient(opts ...option.RequestOption) *Client { - options := core.NewRequestOptions(opts...) - return &Client{ - WithRawResponse: NewRawClient(options), - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} - -// Publish an entity for ingest into the Entities API. Entities created with this method are "owned" by the originator: other sources, -// such as the UI, may not edit or delete these entities. The server validates entities at API call time and -// returns an error if the entity is invalid. -// -// An entity ID must be provided when calling this endpoint. If the entity referenced by the entity ID does not exist -// then it will be created. Otherwise the entity will be updated. An entity will only be updated if its -// provenance.sourceUpdateTime is greater than the provenance.sourceUpdateTime of the existing entity. -func (c *Client) PublishEntity( - ctx context.Context, - request *v2.Entity, - opts ...option.RequestOption, -) (*v2.Entity, error) { - response, err := c.WithRawResponse.PublishEntity( - ctx, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -func (c *Client) GetEntity( - ctx context.Context, - // ID of the entity to return - entityID string, - opts ...option.RequestOption, -) (*v2.Entity, error) { - response, err := c.WithRawResponse.GetEntity( - ctx, - entityID, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// Only fields marked with overridable can be overridden. Please refer to our documentation to see the comprehensive -// list of fields that can be overridden. The entity in the request body should only have a value set on the field -// specified in the field path parameter. Field paths are rooted in the base entity object and must be represented -// using lower_snake_case. Do not include "entity" in the field path. -// -// Note that overrides are applied in an eventually consistent manner. If multiple overrides are created -// concurrently for the same field path, the last writer wins. -func (c *Client) OverrideEntity( - ctx context.Context, - // The unique ID of the entity to override - entityID string, - // fieldPath to override - fieldPath string, - request *v2.EntityOverride, - opts ...option.RequestOption, -) (*v2.Entity, error) { - response, err := c.WithRawResponse.OverrideEntity( - ctx, - entityID, - fieldPath, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// This operation clears the override value from the specified field path on the entity. -func (c *Client) RemoveEntityOverride( - ctx context.Context, - // The unique ID of the entity to undo an override from. - entityID string, - // The fieldPath to clear overrides from. - fieldPath string, - opts ...option.RequestOption, -) (*v2.Entity, error) { - response, err := c.WithRawResponse.RemoveEntityOverride( - ctx, - entityID, - fieldPath, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// This is a long polling API that will first return all pre-existing data and then return all new data as -// it becomes available. If you want to start a new polling session then open a request with an empty -// 'sessionToken' in the request body. The server will return a new session token in the response. -// If you want to retrieve the next batch of results from an existing polling session then send the session -// token you received from the server in the request body. If no new data is available then the server will -// hold the connection open for up to 5 minutes. After the 5 minute timeout period, the server will close the -// connection with no results and you may resume polling with the same session token. If your session falls behind -// more than 3x the total number of entities in the environment, the server will terminate your session. -// In this case you must start a new session by sending a request with an empty session token. -func (c *Client) LongPollEntityEvents( - ctx context.Context, - request *v2.EntityEventRequest, - opts ...option.RequestOption, -) (*v2.EntityEventResponse, error) { - response, err := c.WithRawResponse.LongPollEntityEvents( - ctx, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// Establishes a persistent connection to stream entity events as they occur. -func (c *Client) StreamEntities( - ctx context.Context, - request *v2.EntityStreamRequest, - opts ...option.RequestOption, -) (*core.Stream[v2.StreamEntitiesResponse], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - c.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/entities/stream" - headers := internal.MergeHeaders( - c.header.Clone(), - options.ToHeader(), - ) - headers.Add("Accept", "text/event-stream") - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - } - streamer := internal.NewStreamer[v2.StreamEntitiesResponse](c.caller) - return streamer.Stream( - ctx, - &internal.StreamParams{ - URL: endpointURL, - Method: http.MethodPost, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Prefix: internal.DefaultSSEDataPrefix, - Terminator: internal.DefaultSSETerminator, - Format: core.StreamFormatSSE, - Request: request, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/entities/doc.go b/vendor/github.com/anduril/lattice-sdk-go/v2/entities/doc.go deleted file mode 100644 index 10bba86..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/entities/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -// The Entities API -package entities diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/entities/raw_client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/entities/raw_client.go deleted file mode 100644 index e409d2c..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/entities/raw_client.go +++ /dev/null @@ -1,350 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package entities - -import ( - context "context" - v2 "github.com/anduril/lattice-sdk-go/v2" - core "github.com/anduril/lattice-sdk-go/v2/core" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - option "github.com/anduril/lattice-sdk-go/v2/option" - http "net/http" -) - -type RawClient struct { - baseURL string - caller *internal.Caller - header http.Header -} - -func NewRawClient(options *core.RequestOptions) *RawClient { - return &RawClient{ - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} - -func (r *RawClient) PublishEntity( - ctx context.Context, - request *v2.Entity, - opts ...option.RequestOption, -) (*core.Response[*v2.Entity], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/entities" - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - } - var response *v2.Entity - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPut, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Entity]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) GetEntity( - ctx context.Context, - // ID of the entity to return - entityID string, - opts ...option.RequestOption, -) (*core.Response[*v2.Entity], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/entities/%v", - entityID, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - } - var response *v2.Entity - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodGet, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Entity]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) OverrideEntity( - ctx context.Context, - // The unique ID of the entity to override - entityID string, - // fieldPath to override - fieldPath string, - request *v2.EntityOverride, - opts ...option.RequestOption, -) (*core.Response[*v2.Entity], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/entities/%v/override/%v", - entityID, - fieldPath, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - } - var response *v2.Entity - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPut, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Entity]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) RemoveEntityOverride( - ctx context.Context, - // The unique ID of the entity to undo an override from. - entityID string, - // The fieldPath to clear overrides from. - fieldPath string, - opts ...option.RequestOption, -) (*core.Response[*v2.Entity], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/entities/%v/override/%v", - entityID, - fieldPath, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - } - var response *v2.Entity - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodDelete, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Entity]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) LongPollEntityEvents( - ctx context.Context, - request *v2.EntityEventRequest, - opts ...option.RequestOption, -) (*core.Response[*v2.EntityEventResponse], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/entities/events" - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - 408: func(apiError *core.APIError) error { - return &v2.RequestTimeoutError{ - APIError: apiError, - } - }, - 429: func(apiError *core.APIError) error { - return &v2.TooManyRequestsError{ - APIError: apiError, - } - }, - } - var response *v2.EntityEventResponse - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPost, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.EntityEventResponse]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/environments.go b/vendor/github.com/anduril/lattice-sdk-go/v2/environments.go deleted file mode 100644 index 82b9a6d..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/environments.go +++ /dev/null @@ -1,13 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package Lattice - -// Environments defines all of the API environments. -// These values can be used with the WithBaseURL -// RequestOption to override the client's default environment, -// if any. -var Environments = struct { - Default string -}{ - Default: "https://example.developer.anduril.com", -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/errors.go b/vendor/github.com/anduril/lattice-sdk-go/v2/errors.go deleted file mode 100644 index 967d146..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/errors.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package Lattice - -import ( - json "encoding/json" - core "github.com/anduril/lattice-sdk-go/v2/core" -) - -// Bad request -type BadRequestError struct { - *core.APIError - Body interface{} -} - -func (b *BadRequestError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - b.StatusCode = 400 - b.Body = body - return nil -} - -func (b *BadRequestError) MarshalJSON() ([]byte, error) { - return json.Marshal(b.Body) -} - -func (b *BadRequestError) Unwrap() error { - return b.APIError -} - -// Content too large -type ContentTooLargeError struct { - *core.APIError - Body interface{} -} - -func (c *ContentTooLargeError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - c.StatusCode = 413 - c.Body = body - return nil -} - -func (c *ContentTooLargeError) MarshalJSON() ([]byte, error) { - return json.Marshal(c.Body) -} - -func (c *ContentTooLargeError) Unwrap() error { - return c.APIError -} - -// Insuccifient Storage -type InsufficientStorageError struct { - *core.APIError - Body interface{} -} - -func (i *InsufficientStorageError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - i.StatusCode = 507 - i.Body = body - return nil -} - -func (i *InsufficientStorageError) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Body) -} - -func (i *InsufficientStorageError) Unwrap() error { - return i.APIError -} - -// Internal server error -type InternalServerError struct { - *core.APIError - Body interface{} -} - -func (i *InternalServerError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - i.StatusCode = 500 - i.Body = body - return nil -} - -func (i *InternalServerError) MarshalJSON() ([]byte, error) { - return json.Marshal(i.Body) -} - -func (i *InternalServerError) Unwrap() error { - return i.APIError -} - -// The specified resource was not found -type NotFoundError struct { - *core.APIError - Body interface{} -} - -func (n *NotFoundError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - n.StatusCode = 404 - n.Body = body - return nil -} - -func (n *NotFoundError) MarshalJSON() ([]byte, error) { - return json.Marshal(n.Body) -} - -func (n *NotFoundError) Unwrap() error { - return n.APIError -} - -// The server has terminated the session. The server will send this error when the client has fallen too far -// behind in processing entity events. If the server sends this error, then the session token is invalid and a -// new session must be initiated to receive entity events. -type RequestTimeoutError struct { - *core.APIError - Body interface{} -} - -func (r *RequestTimeoutError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - r.StatusCode = 408 - r.Body = body - return nil -} - -func (r *RequestTimeoutError) MarshalJSON() ([]byte, error) { - return json.Marshal(r.Body) -} - -func (r *RequestTimeoutError) Unwrap() error { - return r.APIError -} - -// Server is out of resources or reaching rate limiting or quota and cannot accept the request at this time. -type TooManyRequestsError struct { - *core.APIError - Body interface{} -} - -func (t *TooManyRequestsError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - t.StatusCode = 429 - t.Body = body - return nil -} - -func (t *TooManyRequestsError) MarshalJSON() ([]byte, error) { - return json.Marshal(t.Body) -} - -func (t *TooManyRequestsError) Unwrap() error { - return t.APIError -} - -// Unauthorized to access resource -type UnauthorizedError struct { - *core.APIError - Body interface{} -} - -func (u *UnauthorizedError) UnmarshalJSON(data []byte) error { - var body interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - u.StatusCode = 401 - u.Body = body - return nil -} - -func (u *UnauthorizedError) MarshalJSON() ([]byte, error) { - return json.Marshal(u.Body) -} - -func (u *UnauthorizedError) Unwrap() error { - return u.APIError -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/file_param.go b/vendor/github.com/anduril/lattice-sdk-go/v2/file_param.go deleted file mode 100644 index 2e66ead..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/file_param.go +++ /dev/null @@ -1,41 +0,0 @@ -package Lattice - -import ( - "io" -) - -// FileParam is a file type suitable for multipart/form-data uploads. -type FileParam struct { - io.Reader - filename string - contentType string -} - -// FileParamOption adapts the behavior of the FileParam. No options are -// implemented yet, but this interface allows for future extensibility. -type FileParamOption interface { - apply() -} - -// NewFileParam returns a *FileParam type suitable for multipart/form-data uploads. All file -// upload endpoints accept a simple io.Reader, which is usually created by opening a file -// via os.Open. -// -// However, some endpoints require additional metadata about the file such as a specific -// Content-Type or custom filename. FileParam makes it easier to create the correct type -// signature for these endpoints. -func NewFileParam( - reader io.Reader, - filename string, - contentType string, - opts ...FileParamOption, -) *FileParam { - return &FileParam{ - Reader: reader, - filename: filename, - contentType: contentType, - } -} - -func (f *FileParam) Name() string { return f.filename } -func (f *FileParam) ContentType() string { return f.contentType } diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/caller.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/caller.go deleted file mode 100644 index 3f3b9ea..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/caller.go +++ /dev/null @@ -1,250 +0,0 @@ -package internal - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "net/url" - "reflect" - "strings" - - "github.com/anduril/lattice-sdk-go/v2/core" -) - -const ( - // contentType specifies the JSON Content-Type header value. - contentType = "application/json" - contentTypeHeader = "Content-Type" -) - -// Caller calls APIs and deserializes their response, if any. -type Caller struct { - client core.HTTPClient - retrier *Retrier -} - -// CallerParams represents the parameters used to constrcut a new *Caller. -type CallerParams struct { - Client core.HTTPClient - MaxAttempts uint -} - -// NewCaller returns a new *Caller backed by the given parameters. -func NewCaller(params *CallerParams) *Caller { - var httpClient core.HTTPClient = http.DefaultClient - if params.Client != nil { - httpClient = params.Client - } - var retryOptions []RetryOption - if params.MaxAttempts > 0 { - retryOptions = append(retryOptions, WithMaxAttempts(params.MaxAttempts)) - } - return &Caller{ - client: httpClient, - retrier: NewRetrier(retryOptions...), - } -} - -// CallParams represents the parameters used to issue an API call. -type CallParams struct { - URL string - Method string - MaxAttempts uint - Headers http.Header - BodyProperties map[string]interface{} - QueryParameters url.Values - Client core.HTTPClient - Request interface{} - Response interface{} - ResponseIsOptional bool - ErrorDecoder ErrorDecoder -} - -// CallResponse is a parsed HTTP response from an API call. -type CallResponse struct { - StatusCode int - Header http.Header -} - -// Call issues an API call according to the given call parameters. -func (c *Caller) Call(ctx context.Context, params *CallParams) (*CallResponse, error) { - url := buildURL(params.URL, params.QueryParameters) - req, err := newRequest( - ctx, - url, - params.Method, - params.Headers, - params.Request, - params.BodyProperties, - ) - if err != nil { - return nil, err - } - - // If the call has been cancelled, don't issue the request. - if err := ctx.Err(); err != nil { - return nil, err - } - - client := c.client - if params.Client != nil { - // Use the HTTP client scoped to the request. - client = params.Client - } - - var retryOptions []RetryOption - if params.MaxAttempts > 0 { - retryOptions = append(retryOptions, WithMaxAttempts(params.MaxAttempts)) - } - - resp, err := c.retrier.Run( - client.Do, - req, - params.ErrorDecoder, - retryOptions..., - ) - if err != nil { - return nil, err - } - - // Close the response body after we're done. - defer resp.Body.Close() - - // Check if the call was cancelled before we return the error - // associated with the call and/or unmarshal the response data. - if err := ctx.Err(); err != nil { - return nil, err - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return nil, decodeError(resp, params.ErrorDecoder) - } - - // Mutate the response parameter in-place. - if params.Response != nil { - if writer, ok := params.Response.(io.Writer); ok { - _, err = io.Copy(writer, resp.Body) - } else { - err = json.NewDecoder(resp.Body).Decode(params.Response) - } - if err != nil { - if err == io.EOF { - if params.ResponseIsOptional { - // The response is optional, so we should ignore the - // io.EOF error - return &CallResponse{ - StatusCode: resp.StatusCode, - Header: resp.Header, - }, nil - } - return nil, fmt.Errorf("expected a %T response, but the server responded with nothing", params.Response) - } - return nil, err - } - } - - return &CallResponse{ - StatusCode: resp.StatusCode, - Header: resp.Header, - }, nil -} - -// buildURL constructs the final URL by appending the given query parameters (if any). -func buildURL( - url string, - queryParameters url.Values, -) string { - if len(queryParameters) == 0 { - return url - } - if strings.ContainsRune(url, '?') { - url += "&" - } else { - url += "?" - } - url += queryParameters.Encode() - return url -} - -// newRequest returns a new *http.Request with all of the fields -// required to issue the call. -func newRequest( - ctx context.Context, - url string, - method string, - endpointHeaders http.Header, - request interface{}, - bodyProperties map[string]interface{}, -) (*http.Request, error) { - requestBody, err := newRequestBody(request, bodyProperties) - if err != nil { - return nil, err - } - req, err := http.NewRequestWithContext(ctx, method, url, requestBody) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - req.Header.Set(contentTypeHeader, contentType) - for name, values := range endpointHeaders { - req.Header[name] = values - } - return req, nil -} - -// newRequestBody returns a new io.Reader that represents the HTTP request body. -func newRequestBody(request interface{}, bodyProperties map[string]interface{}) (io.Reader, error) { - if isNil(request) { - if len(bodyProperties) == 0 { - return nil, nil - } - requestBytes, err := json.Marshal(bodyProperties) - if err != nil { - return nil, err - } - return bytes.NewReader(requestBytes), nil - } - if body, ok := request.(io.Reader); ok { - return body, nil - } - requestBytes, err := MarshalJSONWithExtraProperties(request, bodyProperties) - if err != nil { - return nil, err - } - return bytes.NewReader(requestBytes), nil -} - -// decodeError decodes the error from the given HTTP response. Note that -// it's the caller's responsibility to close the response body. -func decodeError(response *http.Response, errorDecoder ErrorDecoder) error { - if errorDecoder != nil { - // This endpoint has custom errors, so we'll - // attempt to unmarshal the error into a structured - // type based on the status code. - return errorDecoder(response.StatusCode, response.Header, response.Body) - } - // This endpoint doesn't have any custom error - // types, so we just read the body as-is, and - // put it into a normal error. - bytes, err := io.ReadAll(response.Body) - if err != nil && err != io.EOF { - return err - } - if err == io.EOF { - // The error didn't have a response body, - // so all we can do is return an error - // with the status code. - return core.NewAPIError(response.StatusCode, response.Header, nil) - } - return core.NewAPIError(response.StatusCode, response.Header, errors.New(string(bytes))) -} - -// isNil is used to determine if the request value is equal to nil (i.e. an interface -// value that holds a nil concrete value is itself non-nil). -func isNil(value interface{}) bool { - return value == nil || reflect.ValueOf(value).IsNil() -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/error_decoder.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/error_decoder.go deleted file mode 100644 index 85c735b..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/error_decoder.go +++ /dev/null @@ -1,47 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - - "github.com/anduril/lattice-sdk-go/v2/core" -) - -// ErrorDecoder decodes *http.Response errors and returns a -// typed API error (e.g. *core.APIError). -type ErrorDecoder func(statusCode int, header http.Header, body io.Reader) error - -// ErrorCodes maps HTTP status codes to error constructors. -type ErrorCodes map[int]func(*core.APIError) error - -// NewErrorDecoder returns a new ErrorDecoder backed by the given error codes. -func NewErrorDecoder(errorCodes ErrorCodes) ErrorDecoder { - return func(statusCode int, header http.Header, body io.Reader) error { - raw, err := io.ReadAll(body) - if err != nil { - return fmt.Errorf("failed to read error from response body: %w", err) - } - apiError := core.NewAPIError( - statusCode, - header, - errors.New(string(raw)), - ) - newErrorFunc, ok := errorCodes[statusCode] - if !ok { - // This status code isn't recognized, so we return - // the API error as-is. - return apiError - } - customError := newErrorFunc(apiError) - if err := json.NewDecoder(bytes.NewReader(raw)).Decode(customError); err != nil { - // If we fail to decode the error, we return the - // API error as-is. - return apiError - } - return customError - } -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/extra_properties.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/extra_properties.go deleted file mode 100644 index 540c3fd..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/extra_properties.go +++ /dev/null @@ -1,141 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" -) - -// MarshalJSONWithExtraProperty marshals the given value to JSON, including the extra property. -func MarshalJSONWithExtraProperty(marshaler interface{}, key string, value interface{}) ([]byte, error) { - return MarshalJSONWithExtraProperties(marshaler, map[string]interface{}{key: value}) -} - -// MarshalJSONWithExtraProperties marshals the given value to JSON, including any extra properties. -func MarshalJSONWithExtraProperties(marshaler interface{}, extraProperties map[string]interface{}) ([]byte, error) { - bytes, err := json.Marshal(marshaler) - if err != nil { - return nil, err - } - if len(extraProperties) == 0 { - return bytes, nil - } - keys, err := getKeys(marshaler) - if err != nil { - return nil, err - } - for _, key := range keys { - if _, ok := extraProperties[key]; ok { - return nil, fmt.Errorf("cannot add extra property %q because it is already defined on the type", key) - } - } - extraBytes, err := json.Marshal(extraProperties) - if err != nil { - return nil, err - } - if isEmptyJSON(bytes) { - if isEmptyJSON(extraBytes) { - return bytes, nil - } - return extraBytes, nil - } - result := bytes[:len(bytes)-1] - result = append(result, ',') - result = append(result, extraBytes[1:len(extraBytes)-1]...) - result = append(result, '}') - return result, nil -} - -// ExtractExtraProperties extracts any extra properties from the given value. -func ExtractExtraProperties(bytes []byte, value interface{}, exclude ...string) (map[string]interface{}, error) { - val := reflect.ValueOf(value) - for val.Kind() == reflect.Ptr { - if val.IsNil() { - return nil, fmt.Errorf("value must be non-nil to extract extra properties") - } - val = val.Elem() - } - if err := json.Unmarshal(bytes, &value); err != nil { - return nil, err - } - var extraProperties map[string]interface{} - if err := json.Unmarshal(bytes, &extraProperties); err != nil { - return nil, err - } - for i := 0; i < val.Type().NumField(); i++ { - key := jsonKey(val.Type().Field(i)) - if key == "" || key == "-" { - continue - } - delete(extraProperties, key) - } - for _, key := range exclude { - delete(extraProperties, key) - } - if len(extraProperties) == 0 { - return nil, nil - } - return extraProperties, nil -} - -// getKeys returns the keys associated with the given value. The value must be a -// a struct or a map with string keys. -func getKeys(value interface{}) ([]string, error) { - val := reflect.ValueOf(value) - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - if !val.IsValid() { - return nil, nil - } - switch val.Kind() { - case reflect.Struct: - return getKeysForStructType(val.Type()), nil - case reflect.Map: - var keys []string - if val.Type().Key().Kind() != reflect.String { - return nil, fmt.Errorf("cannot extract keys from %T; only structs and maps with string keys are supported", value) - } - for _, key := range val.MapKeys() { - keys = append(keys, key.String()) - } - return keys, nil - default: - return nil, fmt.Errorf("cannot extract keys from %T; only structs and maps with string keys are supported", value) - } -} - -// getKeysForStructType returns all the keys associated with the given struct type, -// visiting embedded fields recursively. -func getKeysForStructType(structType reflect.Type) []string { - if structType.Kind() == reflect.Pointer { - structType = structType.Elem() - } - if structType.Kind() != reflect.Struct { - return nil - } - var keys []string - for i := 0; i < structType.NumField(); i++ { - field := structType.Field(i) - if field.Anonymous { - keys = append(keys, getKeysForStructType(field.Type)...) - continue - } - keys = append(keys, jsonKey(field)) - } - return keys -} - -// jsonKey returns the JSON key from the struct tag of the given field, -// excluding the omitempty flag (if any). -func jsonKey(field reflect.StructField) string { - return strings.TrimSuffix(field.Tag.Get("json"), ",omitempty") -} - -// isEmptyJSON returns true if the given data is empty, the empty JSON object, or -// an explicit null. -func isEmptyJSON(data []byte) bool { - return len(data) <= 2 || bytes.Equal(data, []byte("null")) -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/http.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/http.go deleted file mode 100644 index 768968b..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/http.go +++ /dev/null @@ -1,48 +0,0 @@ -package internal - -import ( - "fmt" - "net/http" - "net/url" -) - -// HTTPClient is an interface for a subset of the *http.Client. -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// ResolveBaseURL resolves the base URL from the given arguments, -// preferring the first non-empty value. -func ResolveBaseURL(values ...string) string { - for _, value := range values { - if value != "" { - return value - } - } - return "" -} - -// EncodeURL encodes the given arguments into the URL, escaping -// values as needed. -func EncodeURL(urlFormat string, args ...interface{}) string { - escapedArgs := make([]interface{}, 0, len(args)) - for _, arg := range args { - escapedArgs = append(escapedArgs, url.PathEscape(fmt.Sprintf("%v", arg))) - } - return fmt.Sprintf(urlFormat, escapedArgs...) -} - -// MergeHeaders merges the given headers together, where the right -// takes precedence over the left. -func MergeHeaders(left, right http.Header) http.Header { - for key, values := range right { - if len(values) > 1 { - left[key] = values - continue - } - if value := right.Get(key); value != "" { - left.Set(key, value) - } - } - return left -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/pager.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/pager.go deleted file mode 100644 index 73b3a95..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/pager.go +++ /dev/null @@ -1,127 +0,0 @@ -package internal - -import ( - "context" - - "github.com/anduril/lattice-sdk-go/v2/core" -) - -// PagerMode represents the different types of pagination modes. -type PagerMode uint - -// The available set of pagination modes. -const ( - PagerModeCursor PagerMode = iota + 1 - PagerModeOffset -) - -// Pager is the primary abstraction used to call paginated APIs. -type Pager[ - Cursor comparable, - Response any, - Results any, -] struct { - mode PagerMode - caller *Caller - prepareCall PageRequestFunc[Cursor] - readPageResponse PageResponseFunc[Cursor, Response, Results] -} - -// PageRequest represents the information required to identify a single page. -type PageRequest[Cursor comparable] struct { - Cursor Cursor - - // Holds the value of the response type (populated by the *Caller). - Response any -} - -// PageResponse represents the information associated with a single page. -type PageResponse[Cursor comparable, Result any] struct { - Results []Result - Next Cursor - Done bool -} - -// PageRequestFunc prepares the *CallParams from the given page request. -type PageRequestFunc[Cursor comparable] func(request *PageRequest[Cursor]) *CallParams - -// PageResponseFunc extracts the next page information from the response. -type PageResponseFunc[ - Cursor comparable, - Response any, - Results any, -] func(Response) *PageResponse[Cursor, Results] - -// NewCursorPager constructs a new Pager that fetches pages from a paginated endpoint. -func NewCursorPager[Cursor comparable, Response any, Results any]( - caller *Caller, - prepareCall PageRequestFunc[Cursor], - readPageResponse PageResponseFunc[Cursor, Response, Results], -) *Pager[Cursor, Response, Results] { - return &Pager[Cursor, Response, Results]{ - mode: PagerModeCursor, - caller: caller, - prepareCall: prepareCall, - readPageResponse: readPageResponse, - } -} - -// NewOffsetPager constructs a new Pager that fetches pages from an offset paginated endpoint. -func NewOffsetPager[Cursor comparable, Response any, Results any]( - caller *Caller, - prepareCall PageRequestFunc[Cursor], - readPageResponse PageResponseFunc[Cursor, Response, Results], -) *Pager[Cursor, Response, Results] { - return &Pager[Cursor, Response, Results]{ - mode: PagerModeOffset, - caller: caller, - prepareCall: prepareCall, - readPageResponse: readPageResponse, - } -} - -// GetPage retrieves the page associated with the given cursor. -func (p *Pager[ - Cursor, - Response, - Results, -]) GetPage(ctx context.Context, cursor Cursor) (*core.Page[Results], error) { - var response Response - pageRequest := &PageRequest[Cursor]{ - Cursor: cursor, - Response: &response, - } - - callParams := p.prepareCall(pageRequest) - if _, err := p.caller.Call(ctx, callParams); err != nil { - return nil, err - } - - pageResponse := p.readPageResponse(response) - - if p.mode == PagerModeOffset { - return &core.Page[Results]{ - Results: pageResponse.Results, - NextPageFunc: func(ctx context.Context) (*core.Page[Results], error) { - page, err := p.GetPage(ctx, pageResponse.Next) - if err != nil { - return nil, err - } - if len(page.Results) == 0 { - return nil, core.ErrNoPages - } - return page, nil - }, - }, nil - } - - return &core.Page[Results]{ - Results: pageResponse.Results, - NextPageFunc: func(ctx context.Context) (*core.Page[Results], error) { - if pageResponse.Done { - return nil, core.ErrNoPages - } - return p.GetPage(ctx, pageResponse.Next) - }, - }, nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/query.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/query.go deleted file mode 100644 index 24ec496..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/query.go +++ /dev/null @@ -1,300 +0,0 @@ -package internal - -import ( - "encoding/base64" - "fmt" - "net/url" - "reflect" - "strings" - "time" - - "github.com/google/uuid" -) - -var ( - bytesType = reflect.TypeOf([]byte{}) - queryEncoderType = reflect.TypeOf(new(QueryEncoder)).Elem() - timeType = reflect.TypeOf(time.Time{}) - uuidType = reflect.TypeOf(uuid.UUID{}) -) - -// QueryEncoder is an interface implemented by any type that wishes to encode -// itself into URL values in a non-standard way. -type QueryEncoder interface { - EncodeQueryValues(key string, v *url.Values) error -} - -// QueryValues encodes url.Values from request objects. -// -// Note: This type is inspired by Google's query encoding library, but -// supports far less customization and is tailored to fit this SDK's use case. -// -// Ref: https://github.com/google/go-querystring -func QueryValues(v interface{}) (url.Values, error) { - values := make(url.Values) - val := reflect.ValueOf(v) - for val.Kind() == reflect.Ptr { - if val.IsNil() { - return values, nil - } - val = val.Elem() - } - - if v == nil { - return values, nil - } - - if val.Kind() != reflect.Struct { - return nil, fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind()) - } - - err := reflectValue(values, val, "") - return values, err -} - -// reflectValue populates the values parameter from the struct fields in val. -// Embedded structs are followed recursively (using the rules defined in the -// Values function documentation) breadth-first. -func reflectValue(values url.Values, val reflect.Value, scope string) error { - typ := val.Type() - for i := 0; i < typ.NumField(); i++ { - sf := typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { - // Skip unexported fields. - continue - } - - sv := val.Field(i) - tag := sf.Tag.Get("url") - if tag == "" || tag == "-" { - continue - } - - name, opts := parseTag(tag) - if name == "" { - name = sf.Name - } - - if scope != "" { - name = scope + "[" + name + "]" - } - - if opts.Contains("omitempty") && isEmptyValue(sv) { - continue - } - - if sv.Type().Implements(queryEncoderType) { - // If sv is a nil pointer and the custom encoder is defined on a non-pointer - // method receiver, set sv to the zero value of the underlying type - if !reflect.Indirect(sv).IsValid() && sv.Type().Elem().Implements(queryEncoderType) { - sv = reflect.New(sv.Type().Elem()) - } - - m := sv.Interface().(QueryEncoder) - if err := m.EncodeQueryValues(name, &values); err != nil { - return err - } - continue - } - - // Recursively dereference pointers, but stop at nil pointers. - for sv.Kind() == reflect.Ptr { - if sv.IsNil() { - break - } - sv = sv.Elem() - } - - if sv.Type() == uuidType || sv.Type() == bytesType || sv.Type() == timeType { - values.Add(name, valueString(sv, opts, sf)) - continue - } - - if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array { - if sv.Len() == 0 { - // Skip if slice or array is empty. - continue - } - for i := 0; i < sv.Len(); i++ { - value := sv.Index(i) - if isStructPointer(value) && !value.IsNil() { - if err := reflectValue(values, value.Elem(), name); err != nil { - return err - } - } else { - values.Add(name, valueString(value, opts, sf)) - } - } - continue - } - - if sv.Kind() == reflect.Map { - if err := reflectMap(values, sv, name); err != nil { - return err - } - continue - } - - if sv.Kind() == reflect.Struct { - if err := reflectValue(values, sv, name); err != nil { - return err - } - continue - } - - values.Add(name, valueString(sv, opts, sf)) - } - - return nil -} - -// reflectMap handles map types specifically, generating query parameters in the format key[mapkey]=value -func reflectMap(values url.Values, val reflect.Value, scope string) error { - if val.IsNil() { - return nil - } - - iter := val.MapRange() - for iter.Next() { - k := iter.Key() - v := iter.Value() - - key := fmt.Sprint(k.Interface()) - paramName := scope + "[" + key + "]" - - for v.Kind() == reflect.Ptr { - if v.IsNil() { - break - } - v = v.Elem() - } - - for v.Kind() == reflect.Interface { - v = v.Elem() - } - - if v.Kind() == reflect.Map { - if err := reflectMap(values, v, paramName); err != nil { - return err - } - continue - } - - if v.Kind() == reflect.Struct { - if err := reflectValue(values, v, paramName); err != nil { - return err - } - continue - } - - if v.Kind() == reflect.Slice || v.Kind() == reflect.Array { - if v.Len() == 0 { - continue - } - for i := 0; i < v.Len(); i++ { - value := v.Index(i) - if isStructPointer(value) && !value.IsNil() { - if err := reflectValue(values, value.Elem(), paramName); err != nil { - return err - } - } else { - values.Add(paramName, valueString(value, tagOptions{}, reflect.StructField{})) - } - } - continue - } - - values.Add(paramName, valueString(v, tagOptions{}, reflect.StructField{})) - } - - return nil -} - -// valueString returns the string representation of a value. -func valueString(v reflect.Value, opts tagOptions, sf reflect.StructField) string { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - return "" - } - v = v.Elem() - } - - if v.Type() == timeType { - t := v.Interface().(time.Time) - if format := sf.Tag.Get("format"); format == "date" { - return t.Format("2006-01-02") - } - return t.Format(time.RFC3339) - } - - if v.Type() == uuidType { - u := v.Interface().(uuid.UUID) - return u.String() - } - - if v.Type() == bytesType { - b := v.Interface().([]byte) - return base64.StdEncoding.EncodeToString(b) - } - - return fmt.Sprint(v.Interface()) -} - -// isEmptyValue checks if a value should be considered empty for the purposes -// of omitting fields with the "omitempty" option. -func isEmptyValue(v reflect.Value) bool { - type zeroable interface { - IsZero() bool - } - - if !v.IsZero() { - if z, ok := v.Interface().(zeroable); ok { - return z.IsZero() - } - } - - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - 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() - case reflect.Invalid, reflect.Complex64, reflect.Complex128, reflect.Chan, reflect.Func, reflect.Struct, reflect.UnsafePointer: - return false - } - - return false -} - -// isStructPointer returns true if the given reflect.Value is a pointer to a struct. -func isStructPointer(v reflect.Value) bool { - return v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct -} - -// tagOptions is the string following a comma in a struct field's "url" tag, or -// the empty string. It does not include the leading comma. -type tagOptions []string - -// parseTag splits a struct field's url tag into its name and comma-separated -// options. -func parseTag(tag string) (string, tagOptions) { - s := strings.Split(tag, ",") - return s[0], s[1:] -} - -// Contains checks whether the tagOptions contains the specified option. -func (o tagOptions) Contains(option string) bool { - for _, s := range o { - if s == option { - return true - } - } - return false -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/retrier.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/retrier.go deleted file mode 100644 index 3418f00..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/retrier.go +++ /dev/null @@ -1,165 +0,0 @@ -package internal - -import ( - "crypto/rand" - "math/big" - "net/http" - "time" -) - -const ( - defaultRetryAttempts = 2 - minRetryDelay = 500 * time.Millisecond - maxRetryDelay = 5000 * time.Millisecond -) - -// RetryOption adapts the behavior the *Retrier. -type RetryOption func(*retryOptions) - -// RetryFunc is a retryable HTTP function call (i.e. *http.Client.Do). -type RetryFunc func(*http.Request) (*http.Response, error) - -// WithMaxAttempts configures the maximum number of attempts -// of the *Retrier. -func WithMaxAttempts(attempts uint) RetryOption { - return func(opts *retryOptions) { - opts.attempts = attempts - } -} - -// Retrier retries failed requests a configurable number of times with an -// exponential back-off between each retry. -type Retrier struct { - attempts uint -} - -// NewRetrier constructs a new *Retrier with the given options, if any. -func NewRetrier(opts ...RetryOption) *Retrier { - options := new(retryOptions) - for _, opt := range opts { - opt(options) - } - attempts := uint(defaultRetryAttempts) - if options.attempts > 0 { - attempts = options.attempts - } - return &Retrier{ - attempts: attempts, - } -} - -// Run issues the request and, upon failure, retries the request if possible. -// -// The request will be retried as long as the request is deemed retryable and the -// number of retry attempts has not grown larger than the configured retry limit. -func (r *Retrier) Run( - fn RetryFunc, - request *http.Request, - errorDecoder ErrorDecoder, - opts ...RetryOption, -) (*http.Response, error) { - options := new(retryOptions) - for _, opt := range opts { - opt(options) - } - maxRetryAttempts := r.attempts - if options.attempts > 0 { - maxRetryAttempts = options.attempts - } - var ( - retryAttempt uint - previousError error - ) - return r.run( - fn, - request, - errorDecoder, - maxRetryAttempts, - retryAttempt, - previousError, - ) -} - -func (r *Retrier) run( - fn RetryFunc, - request *http.Request, - errorDecoder ErrorDecoder, - maxRetryAttempts uint, - retryAttempt uint, - previousError error, -) (*http.Response, error) { - if retryAttempt >= maxRetryAttempts { - return nil, previousError - } - - // If the call has been cancelled, don't issue the request. - if err := request.Context().Err(); err != nil { - return nil, err - } - - response, err := fn(request) - if err != nil { - return nil, err - } - - if r.shouldRetry(response) { - defer response.Body.Close() - - delay, err := r.retryDelay(retryAttempt) - if err != nil { - return nil, err - } - - time.Sleep(delay) - - return r.run( - fn, - request, - errorDecoder, - maxRetryAttempts, - retryAttempt+1, - decodeError(response, errorDecoder), - ) - } - - return response, nil -} - -// shouldRetry returns true if the request should be retried based on the given -// response status code. -func (r *Retrier) shouldRetry(response *http.Response) bool { - return response.StatusCode == http.StatusTooManyRequests || - response.StatusCode == http.StatusRequestTimeout || - response.StatusCode >= http.StatusInternalServerError -} - -// retryDelay calculates the delay time in milliseconds based on the retry attempt. -func (r *Retrier) retryDelay(retryAttempt uint) (time.Duration, error) { - // Apply exponential backoff. - delay := minRetryDelay + minRetryDelay*time.Duration(retryAttempt*retryAttempt) - - // Do not allow the number to exceed maxRetryDelay. - if delay > maxRetryDelay { - delay = maxRetryDelay - } - - // Apply some jitter by randomizing the value in the range of 75%-100%. - max := big.NewInt(int64(delay / 4)) - jitter, err := rand.Int(rand.Reader, max) - if err != nil { - return 0, err - } - - delay -= time.Duration(jitter.Int64()) - - // Never sleep less than the base sleep seconds. - if delay < minRetryDelay { - delay = minRetryDelay - } - - return delay, nil -} - -type retryOptions struct { - attempts uint -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/streamer.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/streamer.go deleted file mode 100644 index c5ff06c..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/streamer.go +++ /dev/null @@ -1,118 +0,0 @@ -package internal - -import ( - "context" - "net/http" - "net/url" - - "github.com/anduril/lattice-sdk-go/v2/core" -) - -const ( - // DefaultDataPrefix is the default prefix used for SSE streaming. - DefaultSSEDataPrefix = "data: " - - // DefaultTerminator is the default terminator used for SSE streaming. - DefaultSSETerminator = "[DONE]" -) - -// Streamer calls APIs and streams responses using a *Stream. -type Streamer[T any] struct { - client HTTPClient - retrier *Retrier -} - -// NewStreamer returns a new *Streamer backed by the given caller's HTTP client. -func NewStreamer[T any](caller *Caller) *Streamer[T] { - return &Streamer[T]{ - client: caller.client, - retrier: caller.retrier, - } -} - -// StreamParams represents the parameters used to issue an API streaming call. -type StreamParams struct { - URL string - Method string - Prefix string - Delimiter string - Terminator string - MaxAttempts uint - Headers http.Header - BodyProperties map[string]interface{} - QueryParameters url.Values - Client HTTPClient - Request interface{} - ErrorDecoder ErrorDecoder - Format core.StreamFormat -} - -// Stream issues an API streaming call according to the given stream parameters. -func (s *Streamer[T]) Stream(ctx context.Context, params *StreamParams) (*core.Stream[T], error) { - url := buildURL(params.URL, params.QueryParameters) - req, err := newRequest( - ctx, - url, - params.Method, - params.Headers, - params.Request, - params.BodyProperties, - ) - if err != nil { - return nil, err - } - - // If the call has been cancelled, don't issue the request. - if err := ctx.Err(); err != nil { - return nil, err - } - - client := s.client - if params.Client != nil { - // Use the HTTP client scoped to the request. - client = params.Client - } - - var retryOptions []RetryOption - if params.MaxAttempts > 0 { - retryOptions = append(retryOptions, WithMaxAttempts(params.MaxAttempts)) - } - - resp, err := s.retrier.Run( - client.Do, - req, - params.ErrorDecoder, - retryOptions..., - ) - if err != nil { - return nil, err - } - - // Check if the call was cancelled before we return the error - // associated with the call and/or unmarshal the response data. - if err := ctx.Err(); err != nil { - defer resp.Body.Close() - return nil, err - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - defer resp.Body.Close() - return nil, decodeError(resp, params.ErrorDecoder) - } - - var opts []core.StreamOption - if params.Delimiter != "" { - opts = append(opts, core.WithDelimiter(params.Delimiter)) - } - if params.Prefix != "" { - opts = append(opts, core.WithPrefix(params.Prefix)) - } - if params.Terminator != "" { - opts = append(opts, core.WithTerminator(params.Terminator)) - } - if params.Format != core.StreamFormatEmpty { - opts = append(opts, core.WithFormat(params.Format)) - } - - return core.NewStream[T](resp, opts...), nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/stringer.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/stringer.go deleted file mode 100644 index 3128018..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/stringer.go +++ /dev/null @@ -1,13 +0,0 @@ -package internal - -import "encoding/json" - -// StringifyJSON returns a pretty JSON string representation of -// the given value. -func StringifyJSON(value interface{}) (string, error) { - bytes, err := json.MarshalIndent(value, "", " ") - if err != nil { - return "", err - } - return string(bytes), nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/time.go b/vendor/github.com/anduril/lattice-sdk-go/v2/internal/time.go deleted file mode 100644 index ab0e269..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/internal/time.go +++ /dev/null @@ -1,137 +0,0 @@ -package internal - -import ( - "encoding/json" - "time" -) - -const dateFormat = "2006-01-02" - -// DateTime wraps time.Time and adapts its JSON representation -// to conform to a RFC3339 date (e.g. 2006-01-02). -// -// Ref: https://ijmacd.github.io/rfc3339-iso8601 -type Date struct { - t *time.Time -} - -// NewDate returns a new *Date. If the given time.Time -// is nil, nil will be returned. -func NewDate(t time.Time) *Date { - return &Date{t: &t} -} - -// NewOptionalDate returns a new *Date. If the given time.Time -// is nil, nil will be returned. -func NewOptionalDate(t *time.Time) *Date { - if t == nil { - return nil - } - return &Date{t: t} -} - -// Time returns the Date's underlying time, if any. If the -// date is nil, the zero value is returned. -func (d *Date) Time() time.Time { - if d == nil || d.t == nil { - return time.Time{} - } - return *d.t -} - -// TimePtr returns a pointer to the Date's underlying time.Time, if any. -func (d *Date) TimePtr() *time.Time { - if d == nil || d.t == nil { - return nil - } - if d.t.IsZero() { - return nil - } - return d.t -} - -func (d *Date) MarshalJSON() ([]byte, error) { - if d == nil || d.t == nil { - return nil, nil - } - return json.Marshal(d.t.Format(dateFormat)) -} - -func (d *Date) UnmarshalJSON(data []byte) error { - var raw string - if err := json.Unmarshal(data, &raw); err != nil { - return err - } - - parsedTime, err := time.Parse(dateFormat, raw) - if err != nil { - return err - } - - *d = Date{t: &parsedTime} - return nil -} - -// DateTime wraps time.Time and adapts its JSON representation -// to conform to a RFC3339 date-time (e.g. 2017-07-21T17:32:28Z). -// -// Ref: https://ijmacd.github.io/rfc3339-iso8601 -type DateTime struct { - t *time.Time -} - -// NewDateTime returns a new *DateTime. -func NewDateTime(t time.Time) *DateTime { - return &DateTime{t: &t} -} - -// NewOptionalDateTime returns a new *DateTime. If the given time.Time -// is nil, nil will be returned. -func NewOptionalDateTime(t *time.Time) *DateTime { - if t == nil { - return nil - } - return &DateTime{t: t} -} - -// Time returns the DateTime's underlying time, if any. If the -// date-time is nil, the zero value is returned. -func (d *DateTime) Time() time.Time { - if d == nil || d.t == nil { - return time.Time{} - } - return *d.t -} - -// TimePtr returns a pointer to the DateTime's underlying time.Time, if any. -func (d *DateTime) TimePtr() *time.Time { - if d == nil || d.t == nil { - return nil - } - if d.t.IsZero() { - return nil - } - return d.t -} - -func (d *DateTime) MarshalJSON() ([]byte, error) { - if d == nil || d.t == nil { - return nil, nil - } - return json.Marshal(d.t.Format(time.RFC3339)) -} - -func (d *DateTime) UnmarshalJSON(data []byte) error { - var raw string - if err := json.Unmarshal(data, &raw); err != nil { - return err - } - - parsedTime, err := time.Parse(time.RFC3339, raw) - if err != nil { - return err - } - - *d = DateTime{t: &parsedTime} - return nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/objects.go b/vendor/github.com/anduril/lattice-sdk-go/v2/objects.go deleted file mode 100644 index 97b39d2..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/objects.go +++ /dev/null @@ -1,254 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package Lattice - -import ( - json "encoding/json" - fmt "fmt" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - time "time" -) - -type GetObjectRequest struct { - // If set, Lattice will compress the response using the specified compression method. If the header is not defined, or the compression method is set to `identity`, no compression will be applied to the response. - AcceptEncoding *GetObjectRequestAcceptEncoding `json:"-" url:"-"` -} - -type ListObjectsRequest struct { - // Filters the objects based on the specified prefix path. If no path is specified, all objects are returned. - Prefix *string `json:"-" url:"prefix,omitempty"` - // Sets the age for the oldest objects to query across the environment. - SinceTimestamp *time.Time `json:"-" url:"sinceTimestamp,omitempty"` - // Base64 and URL-encoded cursor returned by the service to continue paging. - PageToken *string `json:"-" url:"pageToken,omitempty"` - // Lists objects across all environment nodes in a Lattice Mesh. - AllObjectsInMesh *bool `json:"-" url:"allObjectsInMesh,omitempty"` -} - -type ContentIdentifier struct { - // A valid path must not contain the following: - // - Spaces or Tabs - // - Special characters other than underscore (_), dash (-), period (.) and slash (/) - // - Non-ASCII characters such as accents or symbols - // Paths must not start with a leading space. - Path string `json:"path" url:"path"` - // The SHA-256 checksum of this object. - Checksum string `json:"checksum" url:"checksum"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *ContentIdentifier) GetPath() string { - if c == nil { - return "" - } - return c.Path -} - -func (c *ContentIdentifier) GetChecksum() string { - if c == nil { - return "" - } - return c.Checksum -} - -func (c *ContentIdentifier) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *ContentIdentifier) UnmarshalJSON(data []byte) error { - type unmarshaler ContentIdentifier - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = ContentIdentifier(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *ContentIdentifier) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -type ListResponse struct { - PathMetadatas []*PathMetadata `json:"path_metadatas" url:"path_metadatas"` - NextPageToken *string `json:"next_page_token,omitempty" url:"next_page_token,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (l *ListResponse) GetPathMetadatas() []*PathMetadata { - if l == nil { - return nil - } - return l.PathMetadatas -} - -func (l *ListResponse) GetNextPageToken() *string { - if l == nil { - return nil - } - return l.NextPageToken -} - -func (l *ListResponse) GetExtraProperties() map[string]interface{} { - return l.extraProperties -} - -func (l *ListResponse) UnmarshalJSON(data []byte) error { - type unmarshaler ListResponse - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *l = ListResponse(value) - extraProperties, err := internal.ExtractExtraProperties(data, *l) - if err != nil { - return err - } - l.extraProperties = extraProperties - l.rawJSON = json.RawMessage(data) - return nil -} - -func (l *ListResponse) String() string { - if len(l.rawJSON) > 0 { - if value, err := internal.StringifyJSON(l.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(l); err == nil { - return value - } - return fmt.Sprintf("%#v", l) -} - -type PathMetadata struct { - ContentIdentifier *ContentIdentifier `json:"content_identifier" url:"content_identifier"` - SizeBytes int64 `json:"size_bytes" url:"size_bytes"` - LastUpdatedAt time.Time `json:"last_updated_at" url:"last_updated_at"` - ExpiryTime *time.Time `json:"expiry_time,omitempty" url:"expiry_time,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PathMetadata) GetContentIdentifier() *ContentIdentifier { - if p == nil { - return nil - } - return p.ContentIdentifier -} - -func (p *PathMetadata) GetSizeBytes() int64 { - if p == nil { - return 0 - } - return p.SizeBytes -} - -func (p *PathMetadata) GetLastUpdatedAt() time.Time { - if p == nil { - return time.Time{} - } - return p.LastUpdatedAt -} - -func (p *PathMetadata) GetExpiryTime() *time.Time { - if p == nil { - return nil - } - return p.ExpiryTime -} - -func (p *PathMetadata) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PathMetadata) UnmarshalJSON(data []byte) error { - type embed PathMetadata - var unmarshaler = struct { - embed - LastUpdatedAt *internal.DateTime `json:"last_updated_at"` - ExpiryTime *internal.DateTime `json:"expiry_time,omitempty"` - }{ - embed: embed(*p), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *p = PathMetadata(unmarshaler.embed) - p.LastUpdatedAt = unmarshaler.LastUpdatedAt.Time() - p.ExpiryTime = unmarshaler.ExpiryTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PathMetadata) MarshalJSON() ([]byte, error) { - type embed PathMetadata - var marshaler = struct { - embed - LastUpdatedAt *internal.DateTime `json:"last_updated_at"` - ExpiryTime *internal.DateTime `json:"expiry_time,omitempty"` - }{ - embed: embed(*p), - LastUpdatedAt: internal.NewDateTime(p.LastUpdatedAt), - ExpiryTime: internal.NewOptionalDateTime(p.ExpiryTime), - } - return json.Marshal(marshaler) -} - -func (p *PathMetadata) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type GetObjectRequestAcceptEncoding string - -const ( - GetObjectRequestAcceptEncodingIdentity GetObjectRequestAcceptEncoding = "identity" - GetObjectRequestAcceptEncodingZstd GetObjectRequestAcceptEncoding = "zstd" -) - -func NewGetObjectRequestAcceptEncodingFromString(s string) (GetObjectRequestAcceptEncoding, error) { - switch s { - case "identity": - return GetObjectRequestAcceptEncodingIdentity, nil - case "zstd": - return GetObjectRequestAcceptEncodingZstd, nil - } - var t GetObjectRequestAcceptEncoding - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (g GetObjectRequestAcceptEncoding) Ptr() *GetObjectRequestAcceptEncoding { - return &g -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/objects/client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/objects/client.go deleted file mode 100644 index 6f491ea..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/objects/client.go +++ /dev/null @@ -1,188 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package objects - -import ( - context "context" - v2 "github.com/anduril/lattice-sdk-go/v2" - core "github.com/anduril/lattice-sdk-go/v2/core" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - option "github.com/anduril/lattice-sdk-go/v2/option" - io "io" - http "net/http" -) - -type Client struct { - WithRawResponse *RawClient - - baseURL string - caller *internal.Caller - header http.Header -} - -func NewClient(opts ...option.RequestOption) *Client { - options := core.NewRequestOptions(opts...) - return &Client{ - WithRawResponse: NewRawClient(options), - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} - -// Lists objects in your environment. You can define a prefix to list a subset of your objects. If you do not set a prefix, Lattice returns all available objects. By default this endpoint will list local objects only. -func (c *Client) ListObjects( - ctx context.Context, - request *v2.ListObjectsRequest, - opts ...option.RequestOption, -) (*core.Page[*v2.PathMetadata], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - c.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/objects" - queryParams, err := internal.QueryValues(request) - if err != nil { - return nil, err - } - headers := internal.MergeHeaders( - c.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 500: func(apiError *core.APIError) error { - return &v2.InternalServerError{ - APIError: apiError, - } - }, - } - prepareCall := func(pageRequest *internal.PageRequest[*string]) *internal.CallParams { - if pageRequest.Cursor != nil { - queryParams.Set("pageToken", *pageRequest.Cursor) - } - nextURL := endpointURL - if len(queryParams) > 0 { - nextURL += "?" + queryParams.Encode() - } - return &internal.CallParams{ - URL: nextURL, - Method: http.MethodGet, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Response: pageRequest.Response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - } - } - readPageResponse := func(response *v2.ListResponse) *internal.PageResponse[*string, *v2.PathMetadata] { - var zeroValue *string - next := response.GetNextPageToken() - results := response.GetPathMetadatas() - return &internal.PageResponse[*string, *v2.PathMetadata]{ - Next: next, - Results: results, - Done: next == zeroValue, - } - } - pager := internal.NewCursorPager( - c.caller, - prepareCall, - readPageResponse, - ) - return pager.GetPage(ctx, request.PageToken) -} - -// Fetches an object from your environment using the objectPath path parameter. -func (c *Client) GetObject( - ctx context.Context, - // The path of the object to fetch. - objectPath string, - request *v2.GetObjectRequest, - opts ...option.RequestOption, -) (io.Reader, error) { - response, err := c.WithRawResponse.GetObject( - ctx, - objectPath, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// Uploads an object. The object must be 1 GiB or smaller. -func (c *Client) UploadObject( - ctx context.Context, - // Path of the Object that is to be uploaded. - objectPath string, - request io.Reader, - opts ...option.RequestOption, -) (*v2.PathMetadata, error) { - response, err := c.WithRawResponse.UploadObject( - ctx, - objectPath, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// Deletes an object from your environment given the objectPath path parameter. -func (c *Client) DeleteObject( - ctx context.Context, - // The path of the object to delete. - objectPath string, - opts ...option.RequestOption, -) error { - _, err := c.WithRawResponse.DeleteObject( - ctx, - objectPath, - opts..., - ) - if err != nil { - return err - } - return nil -} - -// Returns metadata for a specified object path. Use this to fetch metadata such as object size (size_bytes), its expiry time (expiry_time), or its latest update timestamp (last_updated_at). -func (c *Client) GetObjectMetadata( - ctx context.Context, - // The path of the object to query. - objectPath string, - opts ...option.RequestOption, -) error { - _, err := c.WithRawResponse.GetObjectMetadata( - ctx, - objectPath, - opts..., - ) - if err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/objects/doc.go b/vendor/github.com/anduril/lattice-sdk-go/v2/objects/doc.go deleted file mode 100644 index 2182f92..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/objects/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -// API to manipulate and interrogate object data on the local node, as well as list objects from the Lattice mesh. -package objects diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/objects/raw_client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/objects/raw_client.go deleted file mode 100644 index 0ef7cb4..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/objects/raw_client.go +++ /dev/null @@ -1,304 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package objects - -import ( - bytes "bytes" - context "context" - v2 "github.com/anduril/lattice-sdk-go/v2" - core "github.com/anduril/lattice-sdk-go/v2/core" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - option "github.com/anduril/lattice-sdk-go/v2/option" - io "io" - http "net/http" -) - -type RawClient struct { - baseURL string - caller *internal.Caller - header http.Header -} - -func NewRawClient(options *core.RequestOptions) *RawClient { - return &RawClient{ - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} - -func (r *RawClient) GetObject( - ctx context.Context, - // The path of the object to fetch. - objectPath string, - request *v2.GetObjectRequest, - opts ...option.RequestOption, -) (*core.Response[io.Reader], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/objects/%v", - objectPath, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - if request.AcceptEncoding != nil { - headers.Add("Accept-Encoding", string(*request.AcceptEncoding)) - } - - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - 500: func(apiError *core.APIError) error { - return &v2.InternalServerError{ - APIError: apiError, - } - }, - } - response := bytes.NewBuffer(nil) - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodGet, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Response: response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[io.Reader]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) UploadObject( - ctx context.Context, - // Path of the Object that is to be uploaded. - objectPath string, - request io.Reader, - opts ...option.RequestOption, -) (*core.Response[*v2.PathMetadata], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/objects/%v", - objectPath, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 413: func(apiError *core.APIError) error { - return &v2.ContentTooLargeError{ - APIError: apiError, - } - }, - 500: func(apiError *core.APIError) error { - return &v2.InternalServerError{ - APIError: apiError, - } - }, - 507: func(apiError *core.APIError) error { - return &v2.InsufficientStorageError{ - APIError: apiError, - } - }, - } - var response *v2.PathMetadata - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPost, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.PathMetadata]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) DeleteObject( - ctx context.Context, - // The path of the object to delete. - objectPath string, - opts ...option.RequestOption, -) (*core.Response[any], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/objects/%v", - objectPath, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - 500: func(apiError *core.APIError) error { - return &v2.InternalServerError{ - APIError: apiError, - } - }, - } - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodDelete, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[any]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: nil, - }, nil -} - -func (r *RawClient) GetObjectMetadata( - ctx context.Context, - // The path of the object to query. - objectPath string, - opts ...option.RequestOption, -) (*core.Response[any], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/objects/%v", - objectPath, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 500: func(apiError *core.APIError) error { - return &v2.InternalServerError{ - APIError: apiError, - } - }, - } - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodHead, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[any]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: nil, - }, nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/option/request_option.go b/vendor/github.com/anduril/lattice-sdk-go/v2/option/request_option.go deleted file mode 100644 index 6825eca..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/option/request_option.go +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package option - -import ( - core "github.com/anduril/lattice-sdk-go/v2/core" - http "net/http" - url "net/url" -) - -// RequestOption adapts the behavior of an individual request. -type RequestOption = core.RequestOption - -// WithBaseURL sets the base URL, overriding the default -// environment, if any. -func WithBaseURL(baseURL string) *core.BaseURLOption { - return &core.BaseURLOption{ - BaseURL: baseURL, - } -} - -// WithHTTPClient uses the given HTTPClient to issue the request. -func WithHTTPClient(httpClient core.HTTPClient) *core.HTTPClientOption { - return &core.HTTPClientOption{ - HTTPClient: httpClient, - } -} - -// WithHTTPHeader adds the given http.Header to the request. -func WithHTTPHeader(httpHeader http.Header) *core.HTTPHeaderOption { - return &core.HTTPHeaderOption{ - // Clone the headers so they can't be modified after the option call. - HTTPHeader: httpHeader.Clone(), - } -} - -// WithBodyProperties adds the given body properties to the request. -func WithBodyProperties(bodyProperties map[string]interface{}) *core.BodyPropertiesOption { - copiedBodyProperties := make(map[string]interface{}, len(bodyProperties)) - for key, value := range bodyProperties { - copiedBodyProperties[key] = value - } - return &core.BodyPropertiesOption{ - BodyProperties: copiedBodyProperties, - } -} - -// WithQueryParameters adds the given query parameters to the request. -func WithQueryParameters(queryParameters url.Values) *core.QueryParametersOption { - copiedQueryParameters := make(url.Values, len(queryParameters)) - for key, values := range queryParameters { - copiedQueryParameters[key] = values - } - return &core.QueryParametersOption{ - QueryParameters: copiedQueryParameters, - } -} - -// WithMaxAttempts configures the maximum number of retry attempts. -func WithMaxAttempts(attempts uint) *core.MaxAttemptsOption { - return &core.MaxAttemptsOption{ - MaxAttempts: attempts, - } -} - -// WithToken sets the 'Authorization: Bearer ' request header. -func WithToken(token string) *core.TokenOption { - return &core.TokenOption{ - Token: token, - } -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/pointer.go b/vendor/github.com/anduril/lattice-sdk-go/v2/pointer.go deleted file mode 100644 index 1559cc4..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/pointer.go +++ /dev/null @@ -1,132 +0,0 @@ -package Lattice - -import ( - "time" - - "github.com/google/uuid" -) - -// Bool returns a pointer to the given bool value. -func Bool(b bool) *bool { - return &b -} - -// Byte returns a pointer to the given byte value. -func Byte(b byte) *byte { - return &b -} - -// Complex64 returns a pointer to the given complex64 value. -func Complex64(c complex64) *complex64 { - return &c -} - -// Complex128 returns a pointer to the given complex128 value. -func Complex128(c complex128) *complex128 { - return &c -} - -// Float32 returns a pointer to the given float32 value. -func Float32(f float32) *float32 { - return &f -} - -// Float64 returns a pointer to the given float64 value. -func Float64(f float64) *float64 { - return &f -} - -// Int returns a pointer to the given int value. -func Int(i int) *int { - return &i -} - -// Int8 returns a pointer to the given int8 value. -func Int8(i int8) *int8 { - return &i -} - -// Int16 returns a pointer to the given int16 value. -func Int16(i int16) *int16 { - return &i -} - -// Int32 returns a pointer to the given int32 value. -func Int32(i int32) *int32 { - return &i -} - -// Int64 returns a pointer to the given int64 value. -func Int64(i int64) *int64 { - return &i -} - -// Rune returns a pointer to the given rune value. -func Rune(r rune) *rune { - return &r -} - -// String returns a pointer to the given string value. -func String(s string) *string { - return &s -} - -// Uint returns a pointer to the given uint value. -func Uint(u uint) *uint { - return &u -} - -// Uint8 returns a pointer to the given uint8 value. -func Uint8(u uint8) *uint8 { - return &u -} - -// Uint16 returns a pointer to the given uint16 value. -func Uint16(u uint16) *uint16 { - return &u -} - -// Uint32 returns a pointer to the given uint32 value. -func Uint32(u uint32) *uint32 { - return &u -} - -// Uint64 returns a pointer to the given uint64 value. -func Uint64(u uint64) *uint64 { - return &u -} - -// Uintptr returns a pointer to the given uintptr value. -func Uintptr(u uintptr) *uintptr { - return &u -} - -// UUID returns a pointer to the given uuid.UUID value. -func UUID(u uuid.UUID) *uuid.UUID { - return &u -} - -// Time returns a pointer to the given time.Time value. -func Time(t time.Time) *time.Time { - return &t -} - -// MustParseDate attempts to parse the given string as a -// date time.Time, and panics upon failure. -func MustParseDate(date string) time.Time { - t, err := time.Parse("2006-01-02", date) - if err != nil { - panic(err) - } - return t -} - -// MustParseDateTime attempts to parse the given string as a -// datetime time.Time, and panics upon failure. -func MustParseDateTime(datetime string) time.Time { - t, err := time.Parse(time.RFC3339, datetime) - if err != nil { - panic(err) - } - return t -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks.go b/vendor/github.com/anduril/lattice-sdk-go/v2/tasks.go deleted file mode 100644 index 6fccd00..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks.go +++ /dev/null @@ -1,1574 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package Lattice - -import ( - json "encoding/json" - fmt "fmt" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - time "time" -) - -type TaskCreation struct { - // If non-empty, will set the requested Task ID, otherwise will generate a new random - // GUID. Will reject if supplied Task ID does not match [A-Za-z0-9_-.]{5,36}. - TaskID *string `json:"taskId,omitempty" url:"-"` - // Human readable display name for this Task, should be short (<100 chars). - DisplayName *string `json:"displayName,omitempty" url:"-"` - // Longer, free form human readable description of this Task. - Description *string `json:"description,omitempty" url:"-"` - // Full set of task parameters. - Specification *GoogleProtobufAny `json:"specification,omitempty" url:"-"` - Author *Principal `json:"author,omitempty" url:"-"` - // Any relationships associated with this Task, such as a parent Task or an assignee - // this Task is designated to for execution. - Relations *Relations `json:"relations,omitempty" url:"-"` - // If set, then the service will not trigger execution of this task on an agent. Useful - // for when ingesting tasks from an external system that is triggering execution of tasks - // on agents. - IsExecutedElsewhere *bool `json:"isExecutedElsewhere,omitempty" url:"-"` - // Indicates an initial set of entities that can be used to execute an entity aware - // task. For example, an entity Objective, an entity Keep In Zone, etc. - InitialEntities []*TaskEntity `json:"initialEntities,omitempty" url:"-"` -} - -type AgentListener struct { - // Selector criteria to determine which Agent Tasks the agent receives - AgentSelector *EntityIDsSelector `json:"agentSelector,omitempty" url:"-"` -} - -type TaskQuery struct { - // If set, returns results starting from the given pageToken. - PageToken *string `json:"pageToken,omitempty" url:"-"` - // If present matches Tasks with this parent Task ID. - // Note: this is mutually exclusive with all other query parameters, i.e., either provide parent Task ID, or - // any of the remaining parameters, but not both. - ParentTaskID *string `json:"parentTaskId,omitempty" url:"-"` - StatusFilter *TaskQueryStatusFilter `json:"statusFilter,omitempty" url:"-"` - // If provided, only provides Tasks updated within the time range. - UpdateTimeRange *TaskQueryUpdateTimeRange `json:"updateTimeRange,omitempty" url:"-"` -} - -type AgentRequest struct { - ExecuteRequest *ExecuteRequest `json:"executeRequest,omitempty" url:"executeRequest,omitempty"` - CancelRequest *CancelRequest `json:"cancelRequest,omitempty" url:"cancelRequest,omitempty"` - CompleteRequest *CompleteRequest `json:"completeRequest,omitempty" url:"completeRequest,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *AgentRequest) GetExecuteRequest() *ExecuteRequest { - if a == nil { - return nil - } - return a.ExecuteRequest -} - -func (a *AgentRequest) GetCancelRequest() *CancelRequest { - if a == nil { - return nil - } - return a.CancelRequest -} - -func (a *AgentRequest) GetCompleteRequest() *CompleteRequest { - if a == nil { - return nil - } - return a.CompleteRequest -} - -func (a *AgentRequest) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *AgentRequest) UnmarshalJSON(data []byte) error { - type unmarshaler AgentRequest - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = AgentRequest(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *AgentRequest) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// Allocation contains a list of agents allocated to a Task. -type Allocation struct { - // Agents actively being utilized in a Task. - ActiveAgents []*Agent `json:"activeAgents,omitempty" url:"activeAgents,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *Allocation) GetActiveAgents() []*Agent { - if a == nil { - return nil - } - return a.ActiveAgents -} - -func (a *Allocation) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *Allocation) UnmarshalJSON(data []byte) error { - type unmarshaler Allocation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = Allocation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *Allocation) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// Request to Cancel a Task. -type CancelRequest struct { - // ID of the Task to cancel. - TaskID *string `json:"taskId,omitempty" url:"taskId,omitempty"` - // The assignee of the Task. Useful for agent routing where an endpoint owns multiple agents, - // - // especially onBehalfOf assignees. - Assignee *Principal `json:"assignee,omitempty" url:"assignee,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *CancelRequest) GetTaskID() *string { - if c == nil { - return nil - } - return c.TaskID -} - -func (c *CancelRequest) GetAssignee() *Principal { - if c == nil { - return nil - } - return c.Assignee -} - -func (c *CancelRequest) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *CancelRequest) UnmarshalJSON(data []byte) error { - type unmarshaler CancelRequest - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = CancelRequest(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *CancelRequest) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// Request to Complete a Task. -type CompleteRequest struct { - // ID of the task to complete. - TaskID *string `json:"taskId,omitempty" url:"taskId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *CompleteRequest) GetTaskID() *string { - if c == nil { - return nil - } - return c.TaskID -} - -func (c *CompleteRequest) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *CompleteRequest) UnmarshalJSON(data []byte) error { - type unmarshaler CompleteRequest - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = CompleteRequest(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *CompleteRequest) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -type EntityIDsSelector struct { - // Receive tasks as an assignee for one or more of the supplied entity ids. - EntityIDs []string `json:"entityIds,omitempty" url:"entityIds,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *EntityIDsSelector) GetEntityIDs() []string { - if e == nil { - return nil - } - return e.EntityIDs -} - -func (e *EntityIDsSelector) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *EntityIDsSelector) UnmarshalJSON(data []byte) error { - type unmarshaler EntityIDsSelector - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = EntityIDsSelector(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *EntityIDsSelector) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -// Request to execute a Task. -type ExecuteRequest struct { - // Task to execute. - Task *Task `json:"task,omitempty" url:"task,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *ExecuteRequest) GetTask() *Task { - if e == nil { - return nil - } - return e.Task -} - -func (e *ExecuteRequest) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *ExecuteRequest) UnmarshalJSON(data []byte) error { - type unmarshaler ExecuteRequest - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = ExecuteRequest(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *ExecuteRequest) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -// Owner designates the entity responsible for writes of Task data. -type Owner struct { - // Entity ID of the owner. - EntityID *string `json:"entityId,omitempty" url:"entityId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *Owner) GetEntityID() *string { - if o == nil { - return nil - } - return o.EntityID -} - -func (o *Owner) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *Owner) UnmarshalJSON(data []byte) error { - type unmarshaler Owner - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *o = Owner(value) - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *Owner) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -// A Principal is an entity that has authority over this Task. -type Principal struct { - System *System `json:"system,omitempty" url:"system,omitempty"` - User *User `json:"user,omitempty" url:"user,omitempty"` - Team *Team `json:"team,omitempty" url:"team,omitempty"` - // The Principal _this_ Principal is acting on behalf of. - // - // Likely only populated once in the nesting (i.e. the "on_behalf_of" Principal would not have another "on_behalf_of" in most cases). - OnBehalfOf *Principal `json:"onBehalfOf,omitempty" url:"onBehalfOf,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *Principal) GetSystem() *System { - if p == nil { - return nil - } - return p.System -} - -func (p *Principal) GetUser() *User { - if p == nil { - return nil - } - return p.User -} - -func (p *Principal) GetTeam() *Team { - if p == nil { - return nil - } - return p.Team -} - -func (p *Principal) GetOnBehalfOf() *Principal { - if p == nil { - return nil - } - return p.OnBehalfOf -} - -func (p *Principal) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *Principal) UnmarshalJSON(data []byte) error { - type unmarshaler Principal - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = Principal(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *Principal) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// Relations describes the relationships of this Task, such as assignment, or if the Task has any parents. -type Relations struct { - // Who or what, if anyone, this Task is currently assigned to. - Assignee *Principal `json:"assignee,omitempty" url:"assignee,omitempty"` - // If this Task is a "sub-Task", what is its parent, none if empty. - ParentTaskID *string `json:"parentTaskId,omitempty" url:"parentTaskId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *Relations) GetAssignee() *Principal { - if r == nil { - return nil - } - return r.Assignee -} - -func (r *Relations) GetParentTaskID() *string { - if r == nil { - return nil - } - return r.ParentTaskID -} - -func (r *Relations) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *Relations) UnmarshalJSON(data []byte) error { - type unmarshaler Relations - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *r = Relations(value) - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *Relations) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// Any metadata associated with the replication of a Task. -type Replication struct { - // Time by which this Task should be assumed to be stale. - StaleTime *time.Time `json:"staleTime,omitempty" url:"staleTime,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *Replication) GetStaleTime() *time.Time { - if r == nil { - return nil - } - return r.StaleTime -} - -func (r *Replication) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *Replication) UnmarshalJSON(data []byte) error { - type embed Replication - var unmarshaler = struct { - embed - StaleTime *internal.DateTime `json:"staleTime,omitempty"` - }{ - embed: embed(*r), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *r = Replication(unmarshaler.embed) - r.StaleTime = unmarshaler.StaleTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *Replication) MarshalJSON() ([]byte, error) { - type embed Replication - var marshaler = struct { - embed - StaleTime *internal.DateTime `json:"staleTime,omitempty"` - }{ - embed: embed(*r), - StaleTime: internal.NewOptionalDateTime(r.StaleTime), - } - return json.Marshal(marshaler) -} - -func (r *Replication) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// System Principal representing some autonomous system. -type System struct { - // Name of the service associated with this System. - ServiceName *string `json:"serviceName,omitempty" url:"serviceName,omitempty"` - // The Entity ID of the System. - EntityID *string `json:"entityId,omitempty" url:"entityId,omitempty"` - // Whether the System Principal (for example, an Asset) can own scheduling. - // - // This means we bypass manager-owned scheduling and defer to the system - // Principal to handle scheduling and give us status updates for the Task. - // Regardless of the value defined by the client, the Task Manager will - // determine and set this value appropriately. - ManagesOwnScheduling *bool `json:"managesOwnScheduling,omitempty" url:"managesOwnScheduling,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *System) GetServiceName() *string { - if s == nil { - return nil - } - return s.ServiceName -} - -func (s *System) GetEntityID() *string { - if s == nil { - return nil - } - return s.EntityID -} - -func (s *System) GetManagesOwnScheduling() *bool { - if s == nil { - return nil - } - return s.ManagesOwnScheduling -} - -func (s *System) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *System) UnmarshalJSON(data []byte) error { - type unmarshaler System - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = System(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *System) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// A Task is something an agent can be asked to do. -type Task struct { - // Version of this Task. - Version *TaskVersion `json:"version,omitempty" url:"version,omitempty"` - // DEPRECATED: Human readable display name for this Task, should be short (<100 chars). - DisplayName *string `json:"displayName,omitempty" url:"displayName,omitempty"` - // Full Task parameterization. - Specification *GoogleProtobufAny `json:"specification,omitempty" url:"specification,omitempty"` - // Records who created this Task. This field will not change after the Task has been created. - CreatedBy *Principal `json:"createdBy,omitempty" url:"createdBy,omitempty"` - // Records who updated this Task last. - LastUpdatedBy *Principal `json:"lastUpdatedBy,omitempty" url:"lastUpdatedBy,omitempty"` - // Records the time of last update. - LastUpdateTime *time.Time `json:"lastUpdateTime,omitempty" url:"lastUpdateTime,omitempty"` - // The status of this Task. - Status *TaskStatus `json:"status,omitempty" url:"status,omitempty"` - // If the Task has been scheduled to execute, what time it should execute at. - ScheduledTime *time.Time `json:"scheduledTime,omitempty" url:"scheduledTime,omitempty"` - // Any related Tasks associated with this, typically includes an assignee for this Task and/or a parent. - Relations *Relations `json:"relations,omitempty" url:"relations,omitempty"` - // Longer, free form human readable description of this Task - Description *string `json:"description,omitempty" url:"description,omitempty"` - // If set, execution of this Task is managed elsewhere, not by Task Manager. - // - // In other words, Task manager will not attempt to update the assigned agent with execution instructions. - IsExecutedElsewhere *bool `json:"isExecutedElsewhere,omitempty" url:"isExecutedElsewhere,omitempty"` - // Time of Task creation. - CreateTime *time.Time `json:"createTime,omitempty" url:"createTime,omitempty"` - // If populated, designates this to be a replicated Task. - Replication *Replication `json:"replication,omitempty" url:"replication,omitempty"` - // If populated, indicates an initial set of entities that can be used to execute an entity aware task - // - // For example, an entity Objective, an entity Keep In Zone, etc. - // These will not be updated during execution. If a taskable agent needs continuous updates on the entities from the - // COP, can call entity-manager, or use an AlternateId escape hatch. - InitialEntities []*TaskEntity `json:"initialEntities,omitempty" url:"initialEntities,omitempty"` - // The networked owner of this Task. It is used to ensure that linear writes occur on the node responsible - // - // for replication of task data to other nodes running Task Manager. - Owner *Owner `json:"owner,omitempty" url:"owner,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *Task) GetVersion() *TaskVersion { - if t == nil { - return nil - } - return t.Version -} - -func (t *Task) GetDisplayName() *string { - if t == nil { - return nil - } - return t.DisplayName -} - -func (t *Task) GetSpecification() *GoogleProtobufAny { - if t == nil { - return nil - } - return t.Specification -} - -func (t *Task) GetCreatedBy() *Principal { - if t == nil { - return nil - } - return t.CreatedBy -} - -func (t *Task) GetLastUpdatedBy() *Principal { - if t == nil { - return nil - } - return t.LastUpdatedBy -} - -func (t *Task) GetLastUpdateTime() *time.Time { - if t == nil { - return nil - } - return t.LastUpdateTime -} - -func (t *Task) GetStatus() *TaskStatus { - if t == nil { - return nil - } - return t.Status -} - -func (t *Task) GetScheduledTime() *time.Time { - if t == nil { - return nil - } - return t.ScheduledTime -} - -func (t *Task) GetRelations() *Relations { - if t == nil { - return nil - } - return t.Relations -} - -func (t *Task) GetDescription() *string { - if t == nil { - return nil - } - return t.Description -} - -func (t *Task) GetIsExecutedElsewhere() *bool { - if t == nil { - return nil - } - return t.IsExecutedElsewhere -} - -func (t *Task) GetCreateTime() *time.Time { - if t == nil { - return nil - } - return t.CreateTime -} - -func (t *Task) GetReplication() *Replication { - if t == nil { - return nil - } - return t.Replication -} - -func (t *Task) GetInitialEntities() []*TaskEntity { - if t == nil { - return nil - } - return t.InitialEntities -} - -func (t *Task) GetOwner() *Owner { - if t == nil { - return nil - } - return t.Owner -} - -func (t *Task) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *Task) UnmarshalJSON(data []byte) error { - type embed Task - var unmarshaler = struct { - embed - LastUpdateTime *internal.DateTime `json:"lastUpdateTime,omitempty"` - ScheduledTime *internal.DateTime `json:"scheduledTime,omitempty"` - CreateTime *internal.DateTime `json:"createTime,omitempty"` - }{ - embed: embed(*t), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *t = Task(unmarshaler.embed) - t.LastUpdateTime = unmarshaler.LastUpdateTime.TimePtr() - t.ScheduledTime = unmarshaler.ScheduledTime.TimePtr() - t.CreateTime = unmarshaler.CreateTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *Task) MarshalJSON() ([]byte, error) { - type embed Task - var marshaler = struct { - embed - LastUpdateTime *internal.DateTime `json:"lastUpdateTime,omitempty"` - ScheduledTime *internal.DateTime `json:"scheduledTime,omitempty"` - CreateTime *internal.DateTime `json:"createTime,omitempty"` - }{ - embed: embed(*t), - LastUpdateTime: internal.NewOptionalDateTime(t.LastUpdateTime), - ScheduledTime: internal.NewOptionalDateTime(t.ScheduledTime), - CreateTime: internal.NewOptionalDateTime(t.CreateTime), - } - return json.Marshal(marshaler) -} - -func (t *Task) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Wrapper of an entity passed in Tasking, used to hold an additional information, and as a future extension point. -type TaskEntity struct { - // The wrapped entity-manager entity. - Entity *Entity `json:"entity,omitempty" url:"entity,omitempty"` - // Indicates that this entity was generated from a snapshot of a live entity. - Snapshot *bool `json:"snapshot,omitempty" url:"snapshot,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskEntity) GetEntity() *Entity { - if t == nil { - return nil - } - return t.Entity -} - -func (t *TaskEntity) GetSnapshot() *bool { - if t == nil { - return nil - } - return t.Snapshot -} - -func (t *TaskEntity) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskEntity) UnmarshalJSON(data []byte) error { - type unmarshaler TaskEntity - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskEntity(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskEntity) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// TaskError contains an error code and message typically associated to a Task. -type TaskError struct { - // Error code for Task error. - Code *TaskErrorCode `json:"code,omitempty" url:"code,omitempty"` - // Descriptive human-readable string regarding this error. - Message *string `json:"message,omitempty" url:"message,omitempty"` - // Any additional details regarding this error. - ErrorDetails *GoogleProtobufAny `json:"errorDetails,omitempty" url:"errorDetails,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskError) GetCode() *TaskErrorCode { - if t == nil { - return nil - } - return t.Code -} - -func (t *TaskError) GetMessage() *string { - if t == nil { - return nil - } - return t.Message -} - -func (t *TaskError) GetErrorDetails() *GoogleProtobufAny { - if t == nil { - return nil - } - return t.ErrorDetails -} - -func (t *TaskError) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskError) UnmarshalJSON(data []byte) error { - type unmarshaler TaskError - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskError(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskError) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Error code for Task error. -type TaskErrorCode string - -const ( - TaskErrorCodeErrorCodeInvalid TaskErrorCode = "ERROR_CODE_INVALID" - TaskErrorCodeErrorCodeCancelled TaskErrorCode = "ERROR_CODE_CANCELLED" - TaskErrorCodeErrorCodeRejected TaskErrorCode = "ERROR_CODE_REJECTED" - TaskErrorCodeErrorCodeTimeout TaskErrorCode = "ERROR_CODE_TIMEOUT" - TaskErrorCodeErrorCodeFailed TaskErrorCode = "ERROR_CODE_FAILED" -) - -func NewTaskErrorCodeFromString(s string) (TaskErrorCode, error) { - switch s { - case "ERROR_CODE_INVALID": - return TaskErrorCodeErrorCodeInvalid, nil - case "ERROR_CODE_CANCELLED": - return TaskErrorCodeErrorCodeCancelled, nil - case "ERROR_CODE_REJECTED": - return TaskErrorCodeErrorCodeRejected, nil - case "ERROR_CODE_TIMEOUT": - return TaskErrorCodeErrorCodeTimeout, nil - case "ERROR_CODE_FAILED": - return TaskErrorCodeErrorCodeFailed, nil - } - var t TaskErrorCode - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (t TaskErrorCode) Ptr() *TaskErrorCode { - return &t -} - -type TaskQueryResults struct { - Tasks []*Task `json:"tasks,omitempty" url:"tasks,omitempty"` - // Incomplete results can be detected by a non-empty nextPageToken field in the query results. In order to retrieve - // the next page, perform the exact same request as previously and append a pageToken field with the value of - // nextPageToken from the previous page. A new nextPageToken is provided on the following pages until all the - // results are retrieved. - NextPageToken *string `json:"nextPageToken,omitempty" url:"nextPageToken,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskQueryResults) GetTasks() []*Task { - if t == nil { - return nil - } - return t.Tasks -} - -func (t *TaskQueryResults) GetNextPageToken() *string { - if t == nil { - return nil - } - return t.NextPageToken -} - -func (t *TaskQueryResults) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskQueryResults) UnmarshalJSON(data []byte) error { - type unmarshaler TaskQueryResults - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskQueryResults(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskQueryResults) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// TaskStatus is contains information regarding the status of a Task at any given time. Can include related information -// -// such as any progress towards Task completion, or any associated results if Task completed. -type TaskStatus struct { - // Status of the Task. - Status *TaskStatusStatus `json:"status,omitempty" url:"status,omitempty"` - // Any errors associated with the Task. - TaskError *TaskError `json:"taskError,omitempty" url:"taskError,omitempty"` - // Any incremental progress on the Task, should be from the tasks/v* /progress folder. - Progress *GoogleProtobufAny `json:"progress,omitempty" url:"progress,omitempty"` - // Any final result of the Task, should be from tasks/v* /result folder. - Result *GoogleProtobufAny `json:"result,omitempty" url:"result,omitempty"` - // Time the Task began execution, may not be known even for executing Tasks. - StartTime *time.Time `json:"startTime,omitempty" url:"startTime,omitempty"` - // Any estimate for how the Task will progress, should be from tasks/v* /estimates folder. - Estimate *GoogleProtobufAny `json:"estimate,omitempty" url:"estimate,omitempty"` - // Any allocated agents of the Task. - Allocation *Allocation `json:"allocation,omitempty" url:"allocation,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskStatus) GetStatus() *TaskStatusStatus { - if t == nil { - return nil - } - return t.Status -} - -func (t *TaskStatus) GetTaskError() *TaskError { - if t == nil { - return nil - } - return t.TaskError -} - -func (t *TaskStatus) GetProgress() *GoogleProtobufAny { - if t == nil { - return nil - } - return t.Progress -} - -func (t *TaskStatus) GetResult() *GoogleProtobufAny { - if t == nil { - return nil - } - return t.Result -} - -func (t *TaskStatus) GetStartTime() *time.Time { - if t == nil { - return nil - } - return t.StartTime -} - -func (t *TaskStatus) GetEstimate() *GoogleProtobufAny { - if t == nil { - return nil - } - return t.Estimate -} - -func (t *TaskStatus) GetAllocation() *Allocation { - if t == nil { - return nil - } - return t.Allocation -} - -func (t *TaskStatus) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskStatus) UnmarshalJSON(data []byte) error { - type embed TaskStatus - var unmarshaler = struct { - embed - StartTime *internal.DateTime `json:"startTime,omitempty"` - }{ - embed: embed(*t), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *t = TaskStatus(unmarshaler.embed) - t.StartTime = unmarshaler.StartTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskStatus) MarshalJSON() ([]byte, error) { - type embed TaskStatus - var marshaler = struct { - embed - StartTime *internal.DateTime `json:"startTime,omitempty"` - }{ - embed: embed(*t), - StartTime: internal.NewOptionalDateTime(t.StartTime), - } - return json.Marshal(marshaler) -} - -func (t *TaskStatus) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Status of the Task. -type TaskStatusStatus string - -const ( - TaskStatusStatusStatusInvalid TaskStatusStatus = "STATUS_INVALID" - TaskStatusStatusStatusCreated TaskStatusStatus = "STATUS_CREATED" - TaskStatusStatusStatusScheduledInManager TaskStatusStatus = "STATUS_SCHEDULED_IN_MANAGER" - TaskStatusStatusStatusSent TaskStatusStatus = "STATUS_SENT" - TaskStatusStatusStatusMachineReceipt TaskStatusStatus = "STATUS_MACHINE_RECEIPT" - TaskStatusStatusStatusAck TaskStatusStatus = "STATUS_ACK" - TaskStatusStatusStatusWilco TaskStatusStatus = "STATUS_WILCO" - TaskStatusStatusStatusExecuting TaskStatusStatus = "STATUS_EXECUTING" - TaskStatusStatusStatusWaitingForUpdate TaskStatusStatus = "STATUS_WAITING_FOR_UPDATE" - TaskStatusStatusStatusDoneOk TaskStatusStatus = "STATUS_DONE_OK" - TaskStatusStatusStatusDoneNotOk TaskStatusStatus = "STATUS_DONE_NOT_OK" - TaskStatusStatusStatusReplaced TaskStatusStatus = "STATUS_REPLACED" - TaskStatusStatusStatusCancelRequested TaskStatusStatus = "STATUS_CANCEL_REQUESTED" - TaskStatusStatusStatusCompleteRequested TaskStatusStatus = "STATUS_COMPLETE_REQUESTED" - TaskStatusStatusStatusVersionRejected TaskStatusStatus = "STATUS_VERSION_REJECTED" -) - -func NewTaskStatusStatusFromString(s string) (TaskStatusStatus, error) { - switch s { - case "STATUS_INVALID": - return TaskStatusStatusStatusInvalid, nil - case "STATUS_CREATED": - return TaskStatusStatusStatusCreated, nil - case "STATUS_SCHEDULED_IN_MANAGER": - return TaskStatusStatusStatusScheduledInManager, nil - case "STATUS_SENT": - return TaskStatusStatusStatusSent, nil - case "STATUS_MACHINE_RECEIPT": - return TaskStatusStatusStatusMachineReceipt, nil - case "STATUS_ACK": - return TaskStatusStatusStatusAck, nil - case "STATUS_WILCO": - return TaskStatusStatusStatusWilco, nil - case "STATUS_EXECUTING": - return TaskStatusStatusStatusExecuting, nil - case "STATUS_WAITING_FOR_UPDATE": - return TaskStatusStatusStatusWaitingForUpdate, nil - case "STATUS_DONE_OK": - return TaskStatusStatusStatusDoneOk, nil - case "STATUS_DONE_NOT_OK": - return TaskStatusStatusStatusDoneNotOk, nil - case "STATUS_REPLACED": - return TaskStatusStatusStatusReplaced, nil - case "STATUS_CANCEL_REQUESTED": - return TaskStatusStatusStatusCancelRequested, nil - case "STATUS_COMPLETE_REQUESTED": - return TaskStatusStatusStatusCompleteRequested, nil - case "STATUS_VERSION_REJECTED": - return TaskStatusStatusStatusVersionRejected, nil - } - var t TaskStatusStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (t TaskStatusStatus) Ptr() *TaskStatusStatus { - return &t -} - -// Version of a Task. -type TaskVersion struct { - // The unique ID for this Task. - TaskID *string `json:"taskId,omitempty" url:"taskId,omitempty"` - // Increments on definition (i.e. not TaskStatus) change. 0 is unset, starts at 1 on creation. - DefinitionVersion *int `json:"definitionVersion,omitempty" url:"definitionVersion,omitempty"` - // Increments on changes to TaskStatus. 0 is unset, starts at 1 on creation. - StatusVersion *int `json:"statusVersion,omitempty" url:"statusVersion,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskVersion) GetTaskID() *string { - if t == nil { - return nil - } - return t.TaskID -} - -func (t *TaskVersion) GetDefinitionVersion() *int { - if t == nil { - return nil - } - return t.DefinitionVersion -} - -func (t *TaskVersion) GetStatusVersion() *int { - if t == nil { - return nil - } - return t.StatusVersion -} - -func (t *TaskVersion) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskVersion) UnmarshalJSON(data []byte) error { - type unmarshaler TaskVersion - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskVersion(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskVersion) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// A User Principal representing a human. -type User struct { - // The User ID associated with this User. - UserID *string `json:"userId,omitempty" url:"userId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (u *User) GetUserID() *string { - if u == nil { - return nil - } - return u.UserID -} - -func (u *User) GetExtraProperties() map[string]interface{} { - return u.extraProperties -} - -func (u *User) UnmarshalJSON(data []byte) error { - type unmarshaler User - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *u = User(value) - extraProperties, err := internal.ExtractExtraProperties(data, *u) - if err != nil { - return err - } - u.extraProperties = extraProperties - u.rawJSON = json.RawMessage(data) - return nil -} - -func (u *User) String() string { - if len(u.rawJSON) > 0 { - if value, err := internal.StringifyJSON(u.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(u); err == nil { - return value - } - return fmt.Sprintf("%#v", u) -} - -type TaskQueryStatusFilter struct { - // Status of the Task to filter by, inclusive. - Status *TaskQueryStatusFilterStatus `json:"status,omitempty" url:"status,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskQueryStatusFilter) GetStatus() *TaskQueryStatusFilterStatus { - if t == nil { - return nil - } - return t.Status -} - -func (t *TaskQueryStatusFilter) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskQueryStatusFilter) UnmarshalJSON(data []byte) error { - type unmarshaler TaskQueryStatusFilter - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskQueryStatusFilter(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskQueryStatusFilter) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Status of the Task to filter by, inclusive. -type TaskQueryStatusFilterStatus string - -const ( - TaskQueryStatusFilterStatusStatusInvalid TaskQueryStatusFilterStatus = "STATUS_INVALID" - TaskQueryStatusFilterStatusStatusCreated TaskQueryStatusFilterStatus = "STATUS_CREATED" - TaskQueryStatusFilterStatusStatusScheduledInManager TaskQueryStatusFilterStatus = "STATUS_SCHEDULED_IN_MANAGER" - TaskQueryStatusFilterStatusStatusSent TaskQueryStatusFilterStatus = "STATUS_SENT" - TaskQueryStatusFilterStatusStatusMachineReceipt TaskQueryStatusFilterStatus = "STATUS_MACHINE_RECEIPT" - TaskQueryStatusFilterStatusStatusAck TaskQueryStatusFilterStatus = "STATUS_ACK" - TaskQueryStatusFilterStatusStatusWilco TaskQueryStatusFilterStatus = "STATUS_WILCO" - TaskQueryStatusFilterStatusStatusExecuting TaskQueryStatusFilterStatus = "STATUS_EXECUTING" - TaskQueryStatusFilterStatusStatusWaitingForUpdate TaskQueryStatusFilterStatus = "STATUS_WAITING_FOR_UPDATE" - TaskQueryStatusFilterStatusStatusDoneOk TaskQueryStatusFilterStatus = "STATUS_DONE_OK" - TaskQueryStatusFilterStatusStatusDoneNotOk TaskQueryStatusFilterStatus = "STATUS_DONE_NOT_OK" - TaskQueryStatusFilterStatusStatusReplaced TaskQueryStatusFilterStatus = "STATUS_REPLACED" - TaskQueryStatusFilterStatusStatusCancelRequested TaskQueryStatusFilterStatus = "STATUS_CANCEL_REQUESTED" - TaskQueryStatusFilterStatusStatusCompleteRequested TaskQueryStatusFilterStatus = "STATUS_COMPLETE_REQUESTED" - TaskQueryStatusFilterStatusStatusVersionRejected TaskQueryStatusFilterStatus = "STATUS_VERSION_REJECTED" -) - -func NewTaskQueryStatusFilterStatusFromString(s string) (TaskQueryStatusFilterStatus, error) { - switch s { - case "STATUS_INVALID": - return TaskQueryStatusFilterStatusStatusInvalid, nil - case "STATUS_CREATED": - return TaskQueryStatusFilterStatusStatusCreated, nil - case "STATUS_SCHEDULED_IN_MANAGER": - return TaskQueryStatusFilterStatusStatusScheduledInManager, nil - case "STATUS_SENT": - return TaskQueryStatusFilterStatusStatusSent, nil - case "STATUS_MACHINE_RECEIPT": - return TaskQueryStatusFilterStatusStatusMachineReceipt, nil - case "STATUS_ACK": - return TaskQueryStatusFilterStatusStatusAck, nil - case "STATUS_WILCO": - return TaskQueryStatusFilterStatusStatusWilco, nil - case "STATUS_EXECUTING": - return TaskQueryStatusFilterStatusStatusExecuting, nil - case "STATUS_WAITING_FOR_UPDATE": - return TaskQueryStatusFilterStatusStatusWaitingForUpdate, nil - case "STATUS_DONE_OK": - return TaskQueryStatusFilterStatusStatusDoneOk, nil - case "STATUS_DONE_NOT_OK": - return TaskQueryStatusFilterStatusStatusDoneNotOk, nil - case "STATUS_REPLACED": - return TaskQueryStatusFilterStatusStatusReplaced, nil - case "STATUS_CANCEL_REQUESTED": - return TaskQueryStatusFilterStatusStatusCancelRequested, nil - case "STATUS_COMPLETE_REQUESTED": - return TaskQueryStatusFilterStatusStatusCompleteRequested, nil - case "STATUS_VERSION_REJECTED": - return TaskQueryStatusFilterStatusStatusVersionRejected, nil - } - var t TaskQueryStatusFilterStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (t TaskQueryStatusFilterStatus) Ptr() *TaskQueryStatusFilterStatus { - return &t -} - -// If provided, only provides Tasks updated within the time range. -type TaskQueryUpdateTimeRange struct { - // If provided, returns Tasks only updated after this time. - StartTime *string `json:"startTime,omitempty" url:"startTime,omitempty"` - // If provided, returns Tasks only updated before this time. - EndTime *string `json:"endTime,omitempty" url:"endTime,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskQueryUpdateTimeRange) GetStartTime() *string { - if t == nil { - return nil - } - return t.StartTime -} - -func (t *TaskQueryUpdateTimeRange) GetEndTime() *string { - if t == nil { - return nil - } - return t.EndTime -} - -func (t *TaskQueryUpdateTimeRange) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskQueryUpdateTimeRange) UnmarshalJSON(data []byte) error { - type unmarshaler TaskQueryUpdateTimeRange - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskQueryUpdateTimeRange(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskQueryUpdateTimeRange) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -type TaskStatusUpdate struct { - // The status version of the task to update. This version number increments to indicate the task's - // current stage in its status lifecycle. Specifically, whenever a task's status updates, the status - // version increments by one. Any status updates received with a lower status version number than what - // is known are considered stale and ignored. - StatusVersion *int `json:"statusVersion,omitempty" url:"-"` - // The new status of the task. - NewStatus *TaskStatus `json:"newStatus,omitempty" url:"-"` - Author *Principal `json:"author,omitempty" url:"-"` -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/client.go deleted file mode 100644 index 10ce67b..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/client.go +++ /dev/null @@ -1,126 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package tasks - -import ( - context "context" - v2 "github.com/anduril/lattice-sdk-go/v2" - core "github.com/anduril/lattice-sdk-go/v2/core" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - option "github.com/anduril/lattice-sdk-go/v2/option" - http "net/http" -) - -type Client struct { - WithRawResponse *RawClient - - baseURL string - caller *internal.Caller - header http.Header -} - -func NewClient(opts ...option.RequestOption) *Client { - options := core.NewRequestOptions(opts...) - return &Client{ - WithRawResponse: NewRawClient(options), - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} - -// Submit a request to create a task and schedule it for delivery. Tasks, once delivered, will -// be asynchronously updated by their destined agent. -func (c *Client) CreateTask( - ctx context.Context, - request *v2.TaskCreation, - opts ...option.RequestOption, -) (*v2.Task, error) { - response, err := c.WithRawResponse.CreateTask( - ctx, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -func (c *Client) GetTask( - ctx context.Context, - // ID of task to return - taskID string, - opts ...option.RequestOption, -) (*v2.Task, error) { - response, err := c.WithRawResponse.GetTask( - ctx, - taskID, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// Update the status of a task. -func (c *Client) UpdateTaskStatus( - ctx context.Context, - // ID of task to update status of - taskID string, - request *v2.TaskStatusUpdate, - opts ...option.RequestOption, -) (*v2.Task, error) { - response, err := c.WithRawResponse.UpdateTaskStatus( - ctx, - taskID, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// Query for tasks by a specified search criteria. -func (c *Client) QueryTasks( - ctx context.Context, - request *v2.TaskQuery, - opts ...option.RequestOption, -) (*v2.TaskQueryResults, error) { - response, err := c.WithRawResponse.QueryTasks( - ctx, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} - -// This is a long polling API that will block until a new task is ready for delivery. If no new task is -// available then the server will hold on to your request for up to 5 minutes, after that 5 minute timeout -// period you will be expected to reinitiate a new request. -func (c *Client) ListenAsAgent( - ctx context.Context, - request *v2.AgentListener, - opts ...option.RequestOption, -) (*v2.AgentRequest, error) { - response, err := c.WithRawResponse.ListenAsAgent( - ctx, - request, - opts..., - ) - if err != nil { - return nil, err - } - return response.Body, nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/doc.go b/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/doc.go deleted file mode 100644 index ea74e51..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -// The Tasks API -package tasks diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/raw_client.go b/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/raw_client.go deleted file mode 100644 index 75d15f8..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/tasks/raw_client.go +++ /dev/null @@ -1,328 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package tasks - -import ( - context "context" - v2 "github.com/anduril/lattice-sdk-go/v2" - core "github.com/anduril/lattice-sdk-go/v2/core" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - option "github.com/anduril/lattice-sdk-go/v2/option" - http "net/http" -) - -type RawClient struct { - baseURL string - caller *internal.Caller - header http.Header -} - -func NewRawClient(options *core.RequestOptions) *RawClient { - return &RawClient{ - baseURL: options.BaseURL, - caller: internal.NewCaller( - &internal.CallerParams{ - Client: options.HTTPClient, - MaxAttempts: options.MaxAttempts, - }, - ), - header: options.ToHeader(), - } -} - -func (r *RawClient) CreateTask( - ctx context.Context, - request *v2.TaskCreation, - opts ...option.RequestOption, -) (*core.Response[*v2.Task], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/tasks" - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - } - var response *v2.Task - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPost, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Task]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) GetTask( - ctx context.Context, - // ID of task to return - taskID string, - opts ...option.RequestOption, -) (*core.Response[*v2.Task], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/tasks/%v", - taskID, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - } - var response *v2.Task - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodGet, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Task]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) UpdateTaskStatus( - ctx context.Context, - // ID of task to update status of - taskID string, - request *v2.TaskStatusUpdate, - opts ...option.RequestOption, -) (*core.Response[*v2.Task], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := internal.EncodeURL( - baseURL+"/api/v1/tasks/%v/status", - taskID, - ) - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - } - var response *v2.Task - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPut, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.Task]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) QueryTasks( - ctx context.Context, - request *v2.TaskQuery, - opts ...option.RequestOption, -) (*core.Response[*v2.TaskQueryResults], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/tasks/query" - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - 404: func(apiError *core.APIError) error { - return &v2.NotFoundError{ - APIError: apiError, - } - }, - } - var response *v2.TaskQueryResults - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPost, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.TaskQueryResults]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} - -func (r *RawClient) ListenAsAgent( - ctx context.Context, - request *v2.AgentListener, - opts ...option.RequestOption, -) (*core.Response[*v2.AgentRequest], error) { - options := core.NewRequestOptions(opts...) - baseURL := internal.ResolveBaseURL( - options.BaseURL, - r.baseURL, - "https://example.developer.anduril.com", - ) - endpointURL := baseURL + "/api/v1/agent/listen" - headers := internal.MergeHeaders( - r.header.Clone(), - options.ToHeader(), - ) - headers.Add("Content-Type", "application/json") - errorCodes := internal.ErrorCodes{ - 400: func(apiError *core.APIError) error { - return &v2.BadRequestError{ - APIError: apiError, - } - }, - 401: func(apiError *core.APIError) error { - return &v2.UnauthorizedError{ - APIError: apiError, - } - }, - } - var response *v2.AgentRequest - raw, err := r.caller.Call( - ctx, - &internal.CallParams{ - URL: endpointURL, - Method: http.MethodPost, - Headers: headers, - MaxAttempts: options.MaxAttempts, - BodyProperties: options.BodyProperties, - QueryParameters: options.QueryParameters, - Client: options.HTTPClient, - Request: request, - Response: &response, - ErrorDecoder: internal.NewErrorDecoder(errorCodes), - }, - ) - if err != nil { - return nil, err - } - return &core.Response[*v2.AgentRequest]{ - StatusCode: raw.StatusCode, - Header: raw.Header, - Body: response, - }, nil -} diff --git a/vendor/github.com/anduril/lattice-sdk-go/v2/types.go b/vendor/github.com/anduril/lattice-sdk-go/v2/types.go deleted file mode 100644 index a020796..0000000 --- a/vendor/github.com/anduril/lattice-sdk-go/v2/types.go +++ /dev/null @@ -1,9551 +0,0 @@ -// Code generated by Fern. DO NOT EDIT. - -package Lattice - -import ( - json "encoding/json" - fmt "fmt" - internal "github.com/anduril/lattice-sdk-go/v2/internal" - time "time" -) - -type AcmDetails struct { - AcmType *AcmDetailsAcmType `json:"acmType,omitempty" url:"acmType,omitempty"` - // Used for loosely typed associations, such as assignment to a specific fires unit. - // - // Limit to 150 characters. - AcmDescription *string `json:"acmDescription,omitempty" url:"acmDescription,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *AcmDetails) GetAcmType() *AcmDetailsAcmType { - if a == nil { - return nil - } - return a.AcmType -} - -func (a *AcmDetails) GetAcmDescription() *string { - if a == nil { - return nil - } - return a.AcmDescription -} - -func (a *AcmDetails) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *AcmDetails) UnmarshalJSON(data []byte) error { - type unmarshaler AcmDetails - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = AcmDetails(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *AcmDetails) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -type AcmDetailsAcmType string - -const ( - AcmDetailsAcmTypeAcmDetailTypeInvalid AcmDetailsAcmType = "ACM_DETAIL_TYPE_INVALID" - AcmDetailsAcmTypeAcmDetailTypeLandingZone AcmDetailsAcmType = "ACM_DETAIL_TYPE_LANDING_ZONE" -) - -func NewAcmDetailsAcmTypeFromString(s string) (AcmDetailsAcmType, error) { - switch s { - case "ACM_DETAIL_TYPE_INVALID": - return AcmDetailsAcmTypeAcmDetailTypeInvalid, nil - case "ACM_DETAIL_TYPE_LANDING_ZONE": - return AcmDetailsAcmTypeAcmDetailTypeLandingZone, nil - } - var t AcmDetailsAcmType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (a AcmDetailsAcmType) Ptr() *AcmDetailsAcmType { - return &a -} - -// A target relationship is the inverse of TrackedBy; a one-way relation -// -// from sensor to target, indicating track(s) currently prioritized by a robot. -type ActiveTarget struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *ActiveTarget) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *ActiveTarget) UnmarshalJSON(data []byte) error { - type unmarshaler ActiveTarget - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = ActiveTarget(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *ActiveTarget) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// Represents an Agent in the COP. -type Agent struct { - // Entity ID of the agent. - EntityID *string `json:"entityId,omitempty" url:"entityId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *Agent) GetEntityID() *string { - if a == nil { - return nil - } - return a.EntityID -} - -func (a *Agent) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *Agent) UnmarshalJSON(data []byte) error { - type unmarshaler Agent - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = Agent(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *Agent) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// An alert informs operators of critical events related to system performance and mission -// -// execution. An alert is produced as a result of one or more alert conditions. -type Alert struct { - // Short, machine-readable code that describes this alert. This code is intended to provide systems off-asset - // - // with a lookup key to retrieve more detailed information about the alert. - AlertCode *string `json:"alertCode,omitempty" url:"alertCode,omitempty"` - // Human-readable description of this alert. The description is intended for display in the UI for human - // - // understanding and should not be used for machine processing. If the description is fixed and the vehicle controller - // provides no dynamic substitutions, then prefer lookup based on alert_code. - Description *string `json:"description,omitempty" url:"description,omitempty"` - // Alert level (Warning, Caution, or Advisory). - Level *AlertLevel `json:"level,omitempty" url:"level,omitempty"` - // Time at which this alert was activated. - ActivatedTime *time.Time `json:"activatedTime,omitempty" url:"activatedTime,omitempty"` - // Set of conditions which have activated this alert. - ActiveConditions []*AlertCondition `json:"activeConditions,omitempty" url:"activeConditions,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *Alert) GetAlertCode() *string { - if a == nil { - return nil - } - return a.AlertCode -} - -func (a *Alert) GetDescription() *string { - if a == nil { - return nil - } - return a.Description -} - -func (a *Alert) GetLevel() *AlertLevel { - if a == nil { - return nil - } - return a.Level -} - -func (a *Alert) GetActivatedTime() *time.Time { - if a == nil { - return nil - } - return a.ActivatedTime -} - -func (a *Alert) GetActiveConditions() []*AlertCondition { - if a == nil { - return nil - } - return a.ActiveConditions -} - -func (a *Alert) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *Alert) UnmarshalJSON(data []byte) error { - type embed Alert - var unmarshaler = struct { - embed - ActivatedTime *internal.DateTime `json:"activatedTime,omitempty"` - }{ - embed: embed(*a), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *a = Alert(unmarshaler.embed) - a.ActivatedTime = unmarshaler.ActivatedTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *Alert) MarshalJSON() ([]byte, error) { - type embed Alert - var marshaler = struct { - embed - ActivatedTime *internal.DateTime `json:"activatedTime,omitempty"` - }{ - embed: embed(*a), - ActivatedTime: internal.NewOptionalDateTime(a.ActivatedTime), - } - return json.Marshal(marshaler) -} - -func (a *Alert) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// A condition which may trigger an alert. -type AlertCondition struct { - // Short, machine-readable code that describes this condition. This code is intended to provide systems off-asset - // - // with a lookup key to retrieve more detailed information about the condition. - ConditionCode *string `json:"conditionCode,omitempty" url:"conditionCode,omitempty"` - // Human-readable description of this condition. The description is intended for display in the UI for human - // - // understanding and should not be used for machine processing. If the description is fixed and the vehicle controller - // provides no dynamic substitutions, then prefer lookup based on condition_code. - Description *string `json:"description,omitempty" url:"description,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *AlertCondition) GetConditionCode() *string { - if a == nil { - return nil - } - return a.ConditionCode -} - -func (a *AlertCondition) GetDescription() *string { - if a == nil { - return nil - } - return a.Description -} - -func (a *AlertCondition) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *AlertCondition) UnmarshalJSON(data []byte) error { - type unmarshaler AlertCondition - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = AlertCondition(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *AlertCondition) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// Alert level (Warning, Caution, or Advisory). -type AlertLevel string - -const ( - AlertLevelAlertLevelInvalid AlertLevel = "ALERT_LEVEL_INVALID" - AlertLevelAlertLevelAdvisory AlertLevel = "ALERT_LEVEL_ADVISORY" - AlertLevelAlertLevelCaution AlertLevel = "ALERT_LEVEL_CAUTION" - AlertLevelAlertLevelWarning AlertLevel = "ALERT_LEVEL_WARNING" -) - -func NewAlertLevelFromString(s string) (AlertLevel, error) { - switch s { - case "ALERT_LEVEL_INVALID": - return AlertLevelAlertLevelInvalid, nil - case "ALERT_LEVEL_ADVISORY": - return AlertLevelAlertLevelAdvisory, nil - case "ALERT_LEVEL_CAUTION": - return AlertLevelAlertLevelCaution, nil - case "ALERT_LEVEL_WARNING": - return AlertLevelAlertLevelWarning, nil - } - var t AlertLevel - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (a AlertLevel) Ptr() *AlertLevel { - return &a -} - -// Available for any Entities with alternate ids in other systems. -type Aliases struct { - AlternateIDs []*AlternateID `json:"alternateIds,omitempty" url:"alternateIds,omitempty"` - // The best available version of the entity's display name. - Name *string `json:"name,omitempty" url:"name,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *Aliases) GetAlternateIDs() []*AlternateID { - if a == nil { - return nil - } - return a.AlternateIDs -} - -func (a *Aliases) GetName() *string { - if a == nil { - return nil - } - return a.Name -} - -func (a *Aliases) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *Aliases) UnmarshalJSON(data []byte) error { - type unmarshaler Aliases - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = Aliases(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *Aliases) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// An alternate id for an Entity. -type AlternateID struct { - ID *string `json:"id,omitempty" url:"id,omitempty"` - Type *AlternateIDType `json:"type,omitempty" url:"type,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *AlternateID) GetID() *string { - if a == nil { - return nil - } - return a.ID -} - -func (a *AlternateID) GetType() *AlternateIDType { - if a == nil { - return nil - } - return a.Type -} - -func (a *AlternateID) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *AlternateID) UnmarshalJSON(data []byte) error { - type unmarshaler AlternateID - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = AlternateID(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *AlternateID) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -type AlternateIDType string - -const ( - AlternateIDTypeAltIDTypeInvalid AlternateIDType = "ALT_ID_TYPE_INVALID" - AlternateIDTypeAltIDTypeTrackID2 AlternateIDType = "ALT_ID_TYPE_TRACK_ID_2" - AlternateIDTypeAltIDTypeTrackID1 AlternateIDType = "ALT_ID_TYPE_TRACK_ID_1" - AlternateIDTypeAltIDTypeSpiID AlternateIDType = "ALT_ID_TYPE_SPI_ID" - AlternateIDTypeAltIDTypeNitfFileTitle AlternateIDType = "ALT_ID_TYPE_NITF_FILE_TITLE" - AlternateIDTypeAltIDTypeTrackRepoAlertID AlternateIDType = "ALT_ID_TYPE_TRACK_REPO_ALERT_ID" - AlternateIDTypeAltIDTypeAssetID AlternateIDType = "ALT_ID_TYPE_ASSET_ID" - AlternateIDTypeAltIDTypeLink16TrackNumber AlternateIDType = "ALT_ID_TYPE_LINK16_TRACK_NUMBER" - AlternateIDTypeAltIDTypeLink16Ju AlternateIDType = "ALT_ID_TYPE_LINK16_JU" - AlternateIDTypeAltIDTypeNcctMessageID AlternateIDType = "ALT_ID_TYPE_NCCT_MESSAGE_ID" - AlternateIDTypeAltIDTypeCallsign AlternateIDType = "ALT_ID_TYPE_CALLSIGN" - AlternateIDTypeAltIDTypeMmsiID AlternateIDType = "ALT_ID_TYPE_MMSI_ID" - AlternateIDTypeAltIDTypeVmfUrn AlternateIDType = "ALT_ID_TYPE_VMF_URN" - AlternateIDTypeAltIDTypeImoID AlternateIDType = "ALT_ID_TYPE_IMO_ID" - AlternateIDTypeAltIDTypeVmfTargetNumber AlternateIDType = "ALT_ID_TYPE_VMF_TARGET_NUMBER" - AlternateIDTypeAltIDTypeSerialNumber AlternateIDType = "ALT_ID_TYPE_SERIAL_NUMBER" - AlternateIDTypeAltIDTypeRegistrationID AlternateIDType = "ALT_ID_TYPE_REGISTRATION_ID" - AlternateIDTypeAltIDTypeIbsGid AlternateIDType = "ALT_ID_TYPE_IBS_GID" - AlternateIDTypeAltIDTypeDodaac AlternateIDType = "ALT_ID_TYPE_DODAAC" - AlternateIDTypeAltIDTypeUic AlternateIDType = "ALT_ID_TYPE_UIC" - AlternateIDTypeAltIDTypeNoradCatID AlternateIDType = "ALT_ID_TYPE_NORAD_CAT_ID" - AlternateIDTypeAltIDTypeUnoosaName AlternateIDType = "ALT_ID_TYPE_UNOOSA_NAME" - AlternateIDTypeAltIDTypeUnoosaID AlternateIDType = "ALT_ID_TYPE_UNOOSA_ID" -) - -func NewAlternateIDTypeFromString(s string) (AlternateIDType, error) { - switch s { - case "ALT_ID_TYPE_INVALID": - return AlternateIDTypeAltIDTypeInvalid, nil - case "ALT_ID_TYPE_TRACK_ID_2": - return AlternateIDTypeAltIDTypeTrackID2, nil - case "ALT_ID_TYPE_TRACK_ID_1": - return AlternateIDTypeAltIDTypeTrackID1, nil - case "ALT_ID_TYPE_SPI_ID": - return AlternateIDTypeAltIDTypeSpiID, nil - case "ALT_ID_TYPE_NITF_FILE_TITLE": - return AlternateIDTypeAltIDTypeNitfFileTitle, nil - case "ALT_ID_TYPE_TRACK_REPO_ALERT_ID": - return AlternateIDTypeAltIDTypeTrackRepoAlertID, nil - case "ALT_ID_TYPE_ASSET_ID": - return AlternateIDTypeAltIDTypeAssetID, nil - case "ALT_ID_TYPE_LINK16_TRACK_NUMBER": - return AlternateIDTypeAltIDTypeLink16TrackNumber, nil - case "ALT_ID_TYPE_LINK16_JU": - return AlternateIDTypeAltIDTypeLink16Ju, nil - case "ALT_ID_TYPE_NCCT_MESSAGE_ID": - return AlternateIDTypeAltIDTypeNcctMessageID, nil - case "ALT_ID_TYPE_CALLSIGN": - return AlternateIDTypeAltIDTypeCallsign, nil - case "ALT_ID_TYPE_MMSI_ID": - return AlternateIDTypeAltIDTypeMmsiID, nil - case "ALT_ID_TYPE_VMF_URN": - return AlternateIDTypeAltIDTypeVmfUrn, nil - case "ALT_ID_TYPE_IMO_ID": - return AlternateIDTypeAltIDTypeImoID, nil - case "ALT_ID_TYPE_VMF_TARGET_NUMBER": - return AlternateIDTypeAltIDTypeVmfTargetNumber, nil - case "ALT_ID_TYPE_SERIAL_NUMBER": - return AlternateIDTypeAltIDTypeSerialNumber, nil - case "ALT_ID_TYPE_REGISTRATION_ID": - return AlternateIDTypeAltIDTypeRegistrationID, nil - case "ALT_ID_TYPE_IBS_GID": - return AlternateIDTypeAltIDTypeIbsGid, nil - case "ALT_ID_TYPE_DODAAC": - return AlternateIDTypeAltIDTypeDodaac, nil - case "ALT_ID_TYPE_UIC": - return AlternateIDTypeAltIDTypeUic, nil - case "ALT_ID_TYPE_NORAD_CAT_ID": - return AlternateIDTypeAltIDTypeNoradCatID, nil - case "ALT_ID_TYPE_UNOOSA_NAME": - return AlternateIDTypeAltIDTypeUnoosaName, nil - case "ALT_ID_TYPE_UNOOSA_ID": - return AlternateIDTypeAltIDTypeUnoosaID, nil - } - var t AlternateIDType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (a AlternateIDType) Ptr() *AlternateIDType { - return &a -} - -// The direction from which the signal is received -type AngleOfArrival struct { - // Origin (LLA) and attitude (relative to ENU) of a ray pointing towards the detection. The attitude represents a - // - // forward-left-up (FLU) frame where the x-axis (1, 0, 0) is pointing towards the target. - RelativePose *Pose `json:"relativePose,omitempty" url:"relativePose,omitempty"` - // Bearing/elevation covariance matrix where bearing is defined in radians CCW+ about the z-axis from the x-axis of FLU frame - // - // and elevation is positive down from the FL/XY plane. - // mxx = bearing variance in rad^2 - // mxy = bearing/elevation covariance in rad^2 - // myy = elevation variance in rad^2 - BearingElevationCovarianceRad2 *TMat2 `json:"bearingElevationCovarianceRad2,omitempty" url:"bearingElevationCovarianceRad2,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (a *AngleOfArrival) GetRelativePose() *Pose { - if a == nil { - return nil - } - return a.RelativePose -} - -func (a *AngleOfArrival) GetBearingElevationCovarianceRad2() *TMat2 { - if a == nil { - return nil - } - return a.BearingElevationCovarianceRad2 -} - -func (a *AngleOfArrival) GetExtraProperties() map[string]interface{} { - return a.extraProperties -} - -func (a *AngleOfArrival) UnmarshalJSON(data []byte) error { - type unmarshaler AngleOfArrival - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *a = AngleOfArrival(value) - extraProperties, err := internal.ExtractExtraProperties(data, *a) - if err != nil { - return err - } - a.extraProperties = extraProperties - a.rawJSON = json.RawMessage(data) - return nil -} - -func (a *AngleOfArrival) String() string { - if len(a.rawJSON) > 0 { - if value, err := internal.StringifyJSON(a.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(a); err == nil { - return value - } - return fmt.Sprintf("%#v", a) -} - -// Describes the bandwidth of a signal -type Bandwidth struct { - BandwidthHz *float64 `json:"bandwidthHz,omitempty" url:"bandwidthHz,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (b *Bandwidth) GetBandwidthHz() *float64 { - if b == nil { - return nil - } - return b.BandwidthHz -} - -func (b *Bandwidth) GetExtraProperties() map[string]interface{} { - return b.extraProperties -} - -func (b *Bandwidth) UnmarshalJSON(data []byte) error { - type unmarshaler Bandwidth - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *b = Bandwidth(value) - extraProperties, err := internal.ExtractExtraProperties(data, *b) - if err != nil { - return err - } - b.extraProperties = extraProperties - b.rawJSON = json.RawMessage(data) - return nil -} - -func (b *Bandwidth) String() string { - if len(b.rawJSON) > 0 { - if value, err := internal.StringifyJSON(b.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(b); err == nil { - return value - } - return fmt.Sprintf("%#v", b) -} - -// A component that describes the min and max bandwidths of a sensor -type BandwidthRange struct { - MinimumBandwidth *Bandwidth `json:"minimumBandwidth,omitempty" url:"minimumBandwidth,omitempty"` - MaximumBandwidth *Bandwidth `json:"maximumBandwidth,omitempty" url:"maximumBandwidth,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (b *BandwidthRange) GetMinimumBandwidth() *Bandwidth { - if b == nil { - return nil - } - return b.MinimumBandwidth -} - -func (b *BandwidthRange) GetMaximumBandwidth() *Bandwidth { - if b == nil { - return nil - } - return b.MaximumBandwidth -} - -func (b *BandwidthRange) GetExtraProperties() map[string]interface{} { - return b.extraProperties -} - -func (b *BandwidthRange) UnmarshalJSON(data []byte) error { - type unmarshaler BandwidthRange - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *b = BandwidthRange(value) - extraProperties, err := internal.ExtractExtraProperties(data, *b) - if err != nil { - return err - } - b.extraProperties = extraProperties - b.rawJSON = json.RawMessage(data) - return nil -} - -func (b *BandwidthRange) String() string { - if len(b.rawJSON) > 0 { - if value, err := internal.StringifyJSON(b.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(b); err == nil { - return value - } - return fmt.Sprintf("%#v", b) -} - -// A component that describes an entity's security classification levels. -type Classification struct { - // The default classification information which should be assumed to apply to everything in - // - // the entity unless a specific field level classification is present. - Default *ClassificationInformation `json:"default,omitempty" url:"default,omitempty"` - // The set of individual field classification information which should always precedence - // - // over the default classification information. - Fields []*FieldClassificationInformation `json:"fields,omitempty" url:"fields,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *Classification) GetDefault() *ClassificationInformation { - if c == nil { - return nil - } - return c.Default -} - -func (c *Classification) GetFields() []*FieldClassificationInformation { - if c == nil { - return nil - } - return c.Fields -} - -func (c *Classification) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *Classification) UnmarshalJSON(data []byte) error { - type unmarshaler Classification - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = Classification(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *Classification) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// Represents all of the necessary information required to generate a summarized -// -// classification marking. -// -// > example: A summarized classification marking of "TOPSECRET//NOFORN//FISA" -// would be defined as: { "level": 5, "caveats": [ "NOFORN, "FISA" ] } -type ClassificationInformation struct { - // Classification level to be applied to the information in question. - Level *ClassificationInformationLevel `json:"level,omitempty" url:"level,omitempty"` - // Caveats that may further restrict how the information can be disseminated. - Caveats []string `json:"caveats,omitempty" url:"caveats,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *ClassificationInformation) GetLevel() *ClassificationInformationLevel { - if c == nil { - return nil - } - return c.Level -} - -func (c *ClassificationInformation) GetCaveats() []string { - if c == nil { - return nil - } - return c.Caveats -} - -func (c *ClassificationInformation) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *ClassificationInformation) UnmarshalJSON(data []byte) error { - type unmarshaler ClassificationInformation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = ClassificationInformation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *ClassificationInformation) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// Classification level to be applied to the information in question. -type ClassificationInformationLevel string - -const ( - ClassificationInformationLevelClassificationLevelsInvalid ClassificationInformationLevel = "CLASSIFICATION_LEVELS_INVALID" - ClassificationInformationLevelClassificationLevelsUnclassified ClassificationInformationLevel = "CLASSIFICATION_LEVELS_UNCLASSIFIED" - ClassificationInformationLevelClassificationLevelsControlledUnclassified ClassificationInformationLevel = "CLASSIFICATION_LEVELS_CONTROLLED_UNCLASSIFIED" - ClassificationInformationLevelClassificationLevelsConfidential ClassificationInformationLevel = "CLASSIFICATION_LEVELS_CONFIDENTIAL" - ClassificationInformationLevelClassificationLevelsSecret ClassificationInformationLevel = "CLASSIFICATION_LEVELS_SECRET" - ClassificationInformationLevelClassificationLevelsTopSecret ClassificationInformationLevel = "CLASSIFICATION_LEVELS_TOP_SECRET" -) - -func NewClassificationInformationLevelFromString(s string) (ClassificationInformationLevel, error) { - switch s { - case "CLASSIFICATION_LEVELS_INVALID": - return ClassificationInformationLevelClassificationLevelsInvalid, nil - case "CLASSIFICATION_LEVELS_UNCLASSIFIED": - return ClassificationInformationLevelClassificationLevelsUnclassified, nil - case "CLASSIFICATION_LEVELS_CONTROLLED_UNCLASSIFIED": - return ClassificationInformationLevelClassificationLevelsControlledUnclassified, nil - case "CLASSIFICATION_LEVELS_CONFIDENTIAL": - return ClassificationInformationLevelClassificationLevelsConfidential, nil - case "CLASSIFICATION_LEVELS_SECRET": - return ClassificationInformationLevelClassificationLevelsSecret, nil - case "CLASSIFICATION_LEVELS_TOP_SECRET": - return ClassificationInformationLevelClassificationLevelsTopSecret, nil - } - var t ClassificationInformationLevel - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (c ClassificationInformationLevel) Ptr() *ClassificationInformationLevel { - return &c -} - -type Color struct { - // The amount of red in the color as a value in the interval [0, 1]. - Red *float64 `json:"red,omitempty" url:"red,omitempty"` - // The amount of green in the color as a value in the interval [0, 1]. - Green *float64 `json:"green,omitempty" url:"green,omitempty"` - // The amount of blue in the color as a value in the interval [0, 1]. - Blue *float64 `json:"blue,omitempty" url:"blue,omitempty"` - // The fraction of this color that should be applied to the pixel. That is, - // - // the final pixel color is defined by the equation: - // - // `pixel color = alpha * (this color) + (1.0 - alpha) * (background color)` - // - // This means that a value of 1.0 corresponds to a solid color, whereas - // a value of 0.0 corresponds to a completely transparent color. This - // uses a wrapper message rather than a simple float scalar so that it is - // possible to distinguish between a default value and the value being unset. - // If omitted, this color object is rendered as a solid color - // (as if the alpha value had been explicitly given a value of 1.0). - Alpha *float64 `json:"alpha,omitempty" url:"alpha,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *Color) GetRed() *float64 { - if c == nil { - return nil - } - return c.Red -} - -func (c *Color) GetGreen() *float64 { - if c == nil { - return nil - } - return c.Green -} - -func (c *Color) GetBlue() *float64 { - if c == nil { - return nil - } - return c.Blue -} - -func (c *Color) GetAlpha() *float64 { - if c == nil { - return nil - } - return c.Alpha -} - -func (c *Color) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *Color) UnmarshalJSON(data []byte) error { - type unmarshaler Color - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = Color(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *Color) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// Health of an individual component. -type ComponentHealth struct { - // Consistent internal ID for this component. - ID *string `json:"id,omitempty" url:"id,omitempty"` - // Display name for this component. - Name *string `json:"name,omitempty" url:"name,omitempty"` - // Health for this component. - Health *ComponentHealthHealth `json:"health,omitempty" url:"health,omitempty"` - // Human-readable describing the component state. These messages should be understandable by end users. - Messages []*ComponentMessage `json:"messages,omitempty" url:"messages,omitempty"` - // The last update time for this specific component. - // - // If this timestamp is unset, the data is assumed to be most recent - UpdateTime *time.Time `json:"updateTime,omitempty" url:"updateTime,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *ComponentHealth) GetID() *string { - if c == nil { - return nil - } - return c.ID -} - -func (c *ComponentHealth) GetName() *string { - if c == nil { - return nil - } - return c.Name -} - -func (c *ComponentHealth) GetHealth() *ComponentHealthHealth { - if c == nil { - return nil - } - return c.Health -} - -func (c *ComponentHealth) GetMessages() []*ComponentMessage { - if c == nil { - return nil - } - return c.Messages -} - -func (c *ComponentHealth) GetUpdateTime() *time.Time { - if c == nil { - return nil - } - return c.UpdateTime -} - -func (c *ComponentHealth) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *ComponentHealth) UnmarshalJSON(data []byte) error { - type embed ComponentHealth - var unmarshaler = struct { - embed - UpdateTime *internal.DateTime `json:"updateTime,omitempty"` - }{ - embed: embed(*c), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *c = ComponentHealth(unmarshaler.embed) - c.UpdateTime = unmarshaler.UpdateTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *ComponentHealth) MarshalJSON() ([]byte, error) { - type embed ComponentHealth - var marshaler = struct { - embed - UpdateTime *internal.DateTime `json:"updateTime,omitempty"` - }{ - embed: embed(*c), - UpdateTime: internal.NewOptionalDateTime(c.UpdateTime), - } - return json.Marshal(marshaler) -} - -func (c *ComponentHealth) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// Health for this component. -type ComponentHealthHealth string - -const ( - ComponentHealthHealthHealthStatusInvalid ComponentHealthHealth = "HEALTH_STATUS_INVALID" - ComponentHealthHealthHealthStatusHealthy ComponentHealthHealth = "HEALTH_STATUS_HEALTHY" - ComponentHealthHealthHealthStatusWarn ComponentHealthHealth = "HEALTH_STATUS_WARN" - ComponentHealthHealthHealthStatusFail ComponentHealthHealth = "HEALTH_STATUS_FAIL" - ComponentHealthHealthHealthStatusOffline ComponentHealthHealth = "HEALTH_STATUS_OFFLINE" - ComponentHealthHealthHealthStatusNotReady ComponentHealthHealth = "HEALTH_STATUS_NOT_READY" -) - -func NewComponentHealthHealthFromString(s string) (ComponentHealthHealth, error) { - switch s { - case "HEALTH_STATUS_INVALID": - return ComponentHealthHealthHealthStatusInvalid, nil - case "HEALTH_STATUS_HEALTHY": - return ComponentHealthHealthHealthStatusHealthy, nil - case "HEALTH_STATUS_WARN": - return ComponentHealthHealthHealthStatusWarn, nil - case "HEALTH_STATUS_FAIL": - return ComponentHealthHealthHealthStatusFail, nil - case "HEALTH_STATUS_OFFLINE": - return ComponentHealthHealthHealthStatusOffline, nil - case "HEALTH_STATUS_NOT_READY": - return ComponentHealthHealthHealthStatusNotReady, nil - } - var t ComponentHealthHealth - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (c ComponentHealthHealth) Ptr() *ComponentHealthHealth { - return &c -} - -// A message describing the component's health status. -type ComponentMessage struct { - // The status associated with this message. - Status *ComponentMessageStatus `json:"status,omitempty" url:"status,omitempty"` - // The human-readable content of the message. - Message *string `json:"message,omitempty" url:"message,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *ComponentMessage) GetStatus() *ComponentMessageStatus { - if c == nil { - return nil - } - return c.Status -} - -func (c *ComponentMessage) GetMessage() *string { - if c == nil { - return nil - } - return c.Message -} - -func (c *ComponentMessage) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *ComponentMessage) UnmarshalJSON(data []byte) error { - type unmarshaler ComponentMessage - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = ComponentMessage(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *ComponentMessage) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// The status associated with this message. -type ComponentMessageStatus string - -const ( - ComponentMessageStatusHealthStatusInvalid ComponentMessageStatus = "HEALTH_STATUS_INVALID" - ComponentMessageStatusHealthStatusHealthy ComponentMessageStatus = "HEALTH_STATUS_HEALTHY" - ComponentMessageStatusHealthStatusWarn ComponentMessageStatus = "HEALTH_STATUS_WARN" - ComponentMessageStatusHealthStatusFail ComponentMessageStatus = "HEALTH_STATUS_FAIL" - ComponentMessageStatusHealthStatusOffline ComponentMessageStatus = "HEALTH_STATUS_OFFLINE" - ComponentMessageStatusHealthStatusNotReady ComponentMessageStatus = "HEALTH_STATUS_NOT_READY" -) - -func NewComponentMessageStatusFromString(s string) (ComponentMessageStatus, error) { - switch s { - case "HEALTH_STATUS_INVALID": - return ComponentMessageStatusHealthStatusInvalid, nil - case "HEALTH_STATUS_HEALTHY": - return ComponentMessageStatusHealthStatusHealthy, nil - case "HEALTH_STATUS_WARN": - return ComponentMessageStatusHealthStatusWarn, nil - case "HEALTH_STATUS_FAIL": - return ComponentMessageStatusHealthStatusFail, nil - case "HEALTH_STATUS_OFFLINE": - return ComponentMessageStatusHealthStatusOffline, nil - case "HEALTH_STATUS_NOT_READY": - return ComponentMessageStatusHealthStatusNotReady, nil - } - var t ComponentMessageStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (c ComponentMessageStatus) Ptr() *ComponentMessageStatus { - return &c -} - -// Determines the type of control area being represented by the geo-entity, -// -// in which an asset can, or cannot, operate. -type ControlAreaDetails struct { - Type *ControlAreaDetailsType `json:"type,omitempty" url:"type,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *ControlAreaDetails) GetType() *ControlAreaDetailsType { - if c == nil { - return nil - } - return c.Type -} - -func (c *ControlAreaDetails) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *ControlAreaDetails) UnmarshalJSON(data []byte) error { - type unmarshaler ControlAreaDetails - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = ControlAreaDetails(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *ControlAreaDetails) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -type ControlAreaDetailsType string - -const ( - ControlAreaDetailsTypeControlAreaTypeInvalid ControlAreaDetailsType = "CONTROL_AREA_TYPE_INVALID" - ControlAreaDetailsTypeControlAreaTypeKeepInZone ControlAreaDetailsType = "CONTROL_AREA_TYPE_KEEP_IN_ZONE" - ControlAreaDetailsTypeControlAreaTypeKeepOutZone ControlAreaDetailsType = "CONTROL_AREA_TYPE_KEEP_OUT_ZONE" - ControlAreaDetailsTypeControlAreaTypeDitchZone ControlAreaDetailsType = "CONTROL_AREA_TYPE_DITCH_ZONE" - ControlAreaDetailsTypeControlAreaTypeLoiterZone ControlAreaDetailsType = "CONTROL_AREA_TYPE_LOITER_ZONE" -) - -func NewControlAreaDetailsTypeFromString(s string) (ControlAreaDetailsType, error) { - switch s { - case "CONTROL_AREA_TYPE_INVALID": - return ControlAreaDetailsTypeControlAreaTypeInvalid, nil - case "CONTROL_AREA_TYPE_KEEP_IN_ZONE": - return ControlAreaDetailsTypeControlAreaTypeKeepInZone, nil - case "CONTROL_AREA_TYPE_KEEP_OUT_ZONE": - return ControlAreaDetailsTypeControlAreaTypeKeepOutZone, nil - case "CONTROL_AREA_TYPE_DITCH_ZONE": - return ControlAreaDetailsTypeControlAreaTypeDitchZone, nil - case "CONTROL_AREA_TYPE_LOITER_ZONE": - return ControlAreaDetailsTypeControlAreaTypeLoiterZone, nil - } - var t ControlAreaDetailsType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (c ControlAreaDetailsType) Ptr() *ControlAreaDetailsType { - return &c -} - -// Available for Entities that are a correlated (N to 1) set of entities. This will be present on -// -// each entity in the set. -type Correlation struct { - // This entity is the primary of a correlation meaning that it serves as the representative - // - // entity of the correlation set. - Primary *PrimaryCorrelation `json:"primary,omitempty" url:"primary,omitempty"` - // This entity is a secondary of a correlation meaning that it will be represented by the - // - // primary of the correlation set. - Secondary *SecondaryCorrelation `json:"secondary,omitempty" url:"secondary,omitempty"` - // If present, this entity is a part of a correlation set. - Membership *CorrelationMembership `json:"membership,omitempty" url:"membership,omitempty"` - // If present, this entity was explicitly decorrelated from one or more entities. - // - // An entity can be both correlated and decorrelated as long as they are disjoint sets. - // An example would be if a user in the UI decides that two tracks are not actually the - // same despite an automatic correlator having correlated them. The user would then - // decorrelate the two tracks and this decorrelation would be preserved preventing the - // correlator from re-correlating them at a later time. - Decorrelation *Decorrelation `json:"decorrelation,omitempty" url:"decorrelation,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *Correlation) GetPrimary() *PrimaryCorrelation { - if c == nil { - return nil - } - return c.Primary -} - -func (c *Correlation) GetSecondary() *SecondaryCorrelation { - if c == nil { - return nil - } - return c.Secondary -} - -func (c *Correlation) GetMembership() *CorrelationMembership { - if c == nil { - return nil - } - return c.Membership -} - -func (c *Correlation) GetDecorrelation() *Decorrelation { - if c == nil { - return nil - } - return c.Decorrelation -} - -func (c *Correlation) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *Correlation) UnmarshalJSON(data []byte) error { - type unmarshaler Correlation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = Correlation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *Correlation) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -type CorrelationMembership struct { - // The ID of the correlation set this entity belongs to. - CorrelationSetID *string `json:"correlationSetId,omitempty" url:"correlationSetId,omitempty"` - // This entity is the primary of a correlation set meaning that it serves as the representative - // - // entity of the correlation set. - Primary *PrimaryMembership `json:"primary,omitempty" url:"primary,omitempty"` - // This entity is not the primary of the correlation set. Note that there may not - // - // be a primary at all. - NonPrimary *NonPrimaryMembership `json:"nonPrimary,omitempty" url:"nonPrimary,omitempty"` - // Additional metadata on this correlation. - Metadata *CorrelationMetadata `json:"metadata,omitempty" url:"metadata,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *CorrelationMembership) GetCorrelationSetID() *string { - if c == nil { - return nil - } - return c.CorrelationSetID -} - -func (c *CorrelationMembership) GetPrimary() *PrimaryMembership { - if c == nil { - return nil - } - return c.Primary -} - -func (c *CorrelationMembership) GetNonPrimary() *NonPrimaryMembership { - if c == nil { - return nil - } - return c.NonPrimary -} - -func (c *CorrelationMembership) GetMetadata() *CorrelationMetadata { - if c == nil { - return nil - } - return c.Metadata -} - -func (c *CorrelationMembership) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *CorrelationMembership) UnmarshalJSON(data []byte) error { - type unmarshaler CorrelationMembership - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = CorrelationMembership(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *CorrelationMembership) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -type CorrelationMetadata struct { - // Who or what added this entity to the (de)correlation. - Provenance *Provenance `json:"provenance,omitempty" url:"provenance,omitempty"` - // Indicates how the correlation will be distributed. Because a correlation is composed of - // - // multiple secondaries, each of which may have been correlated with different replication - // modes, the distribution of the correlation is composed of distributions of the individual - // entities within the correlation set. - // For example, if there are two secondary entities A and B correlated against a primary C, - // with A having been correlated globally and B having been correlated locally, then the - // correlation set that is distributed globally than what is known locally in the node. - ReplicationMode *CorrelationMetadataReplicationMode `json:"replicationMode,omitempty" url:"replicationMode,omitempty"` - // What type of (de)correlation was this entity added with. - Type *CorrelationMetadataType `json:"type,omitempty" url:"type,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *CorrelationMetadata) GetProvenance() *Provenance { - if c == nil { - return nil - } - return c.Provenance -} - -func (c *CorrelationMetadata) GetReplicationMode() *CorrelationMetadataReplicationMode { - if c == nil { - return nil - } - return c.ReplicationMode -} - -func (c *CorrelationMetadata) GetType() *CorrelationMetadataType { - if c == nil { - return nil - } - return c.Type -} - -func (c *CorrelationMetadata) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *CorrelationMetadata) UnmarshalJSON(data []byte) error { - type unmarshaler CorrelationMetadata - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = CorrelationMetadata(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *CorrelationMetadata) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -// Indicates how the correlation will be distributed. Because a correlation is composed of -// -// multiple secondaries, each of which may have been correlated with different replication -// modes, the distribution of the correlation is composed of distributions of the individual -// entities within the correlation set. -// For example, if there are two secondary entities A and B correlated against a primary C, -// with A having been correlated globally and B having been correlated locally, then the -// correlation set that is distributed globally than what is known locally in the node. -type CorrelationMetadataReplicationMode string - -const ( - CorrelationMetadataReplicationModeCorrelationReplicationModeInvalid CorrelationMetadataReplicationMode = "CORRELATION_REPLICATION_MODE_INVALID" - CorrelationMetadataReplicationModeCorrelationReplicationModeLocal CorrelationMetadataReplicationMode = "CORRELATION_REPLICATION_MODE_LOCAL" - CorrelationMetadataReplicationModeCorrelationReplicationModeGlobal CorrelationMetadataReplicationMode = "CORRELATION_REPLICATION_MODE_GLOBAL" -) - -func NewCorrelationMetadataReplicationModeFromString(s string) (CorrelationMetadataReplicationMode, error) { - switch s { - case "CORRELATION_REPLICATION_MODE_INVALID": - return CorrelationMetadataReplicationModeCorrelationReplicationModeInvalid, nil - case "CORRELATION_REPLICATION_MODE_LOCAL": - return CorrelationMetadataReplicationModeCorrelationReplicationModeLocal, nil - case "CORRELATION_REPLICATION_MODE_GLOBAL": - return CorrelationMetadataReplicationModeCorrelationReplicationModeGlobal, nil - } - var t CorrelationMetadataReplicationMode - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (c CorrelationMetadataReplicationMode) Ptr() *CorrelationMetadataReplicationMode { - return &c -} - -// What type of (de)correlation was this entity added with. -type CorrelationMetadataType string - -const ( - CorrelationMetadataTypeCorrelationTypeInvalid CorrelationMetadataType = "CORRELATION_TYPE_INVALID" - CorrelationMetadataTypeCorrelationTypeManual CorrelationMetadataType = "CORRELATION_TYPE_MANUAL" - CorrelationMetadataTypeCorrelationTypeAutomated CorrelationMetadataType = "CORRELATION_TYPE_AUTOMATED" -) - -func NewCorrelationMetadataTypeFromString(s string) (CorrelationMetadataType, error) { - switch s { - case "CORRELATION_TYPE_INVALID": - return CorrelationMetadataTypeCorrelationTypeInvalid, nil - case "CORRELATION_TYPE_MANUAL": - return CorrelationMetadataTypeCorrelationTypeManual, nil - case "CORRELATION_TYPE_AUTOMATED": - return CorrelationMetadataTypeCorrelationTypeAutomated, nil - } - var t CorrelationMetadataType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (c CorrelationMetadataType) Ptr() *CorrelationMetadataType { - return &c -} - -type CronWindow struct { - // in UTC, describes when and at what cadence this window starts, in the quartz flavor of cron - // - // examples: - // This schedule is begins at 7:00:00am UTC everyday between Monday and Friday - // 0 0 7 ? * MON-FRI * - // This schedule begins every 5 minutes starting at 12:00:00pm UTC until 8:00:00pm UTC everyday - // 0 0/5 12-20 * * ? * - // This schedule begins at 12:00:00pm UTC on March 2nd 2023 - // 0 0 12 2 3 ? 2023 - CronExpression *string `json:"cronExpression,omitempty" url:"cronExpression,omitempty"` - // describes the duration - DurationMillis *string `json:"durationMillis,omitempty" url:"durationMillis,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (c *CronWindow) GetCronExpression() *string { - if c == nil { - return nil - } - return c.CronExpression -} - -func (c *CronWindow) GetDurationMillis() *string { - if c == nil { - return nil - } - return c.DurationMillis -} - -func (c *CronWindow) GetExtraProperties() map[string]interface{} { - return c.extraProperties -} - -func (c *CronWindow) UnmarshalJSON(data []byte) error { - type unmarshaler CronWindow - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *c = CronWindow(value) - extraProperties, err := internal.ExtractExtraProperties(data, *c) - if err != nil { - return err - } - c.extraProperties = extraProperties - c.rawJSON = json.RawMessage(data) - return nil -} - -func (c *CronWindow) String() string { - if len(c.rawJSON) > 0 { - if value, err := internal.StringifyJSON(c.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(c); err == nil { - return value - } - return fmt.Sprintf("%#v", c) -} - -type DecorrelatedAll struct { - // Metadata about the decorrelation. - Metadata *CorrelationMetadata `json:"metadata,omitempty" url:"metadata,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (d *DecorrelatedAll) GetMetadata() *CorrelationMetadata { - if d == nil { - return nil - } - return d.Metadata -} - -func (d *DecorrelatedAll) GetExtraProperties() map[string]interface{} { - return d.extraProperties -} - -func (d *DecorrelatedAll) UnmarshalJSON(data []byte) error { - type unmarshaler DecorrelatedAll - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *d = DecorrelatedAll(value) - extraProperties, err := internal.ExtractExtraProperties(data, *d) - if err != nil { - return err - } - d.extraProperties = extraProperties - d.rawJSON = json.RawMessage(data) - return nil -} - -func (d *DecorrelatedAll) String() string { - if len(d.rawJSON) > 0 { - if value, err := internal.StringifyJSON(d.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(d); err == nil { - return value - } - return fmt.Sprintf("%#v", d) -} - -type DecorrelatedSingle struct { - // The entity that was decorrelated against. - EntityID *string `json:"entityId,omitempty" url:"entityId,omitempty"` - // Metadata about the decorrelation. - Metadata *CorrelationMetadata `json:"metadata,omitempty" url:"metadata,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (d *DecorrelatedSingle) GetEntityID() *string { - if d == nil { - return nil - } - return d.EntityID -} - -func (d *DecorrelatedSingle) GetMetadata() *CorrelationMetadata { - if d == nil { - return nil - } - return d.Metadata -} - -func (d *DecorrelatedSingle) GetExtraProperties() map[string]interface{} { - return d.extraProperties -} - -func (d *DecorrelatedSingle) UnmarshalJSON(data []byte) error { - type unmarshaler DecorrelatedSingle - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *d = DecorrelatedSingle(value) - extraProperties, err := internal.ExtractExtraProperties(data, *d) - if err != nil { - return err - } - d.extraProperties = extraProperties - d.rawJSON = json.RawMessage(data) - return nil -} - -func (d *DecorrelatedSingle) String() string { - if len(d.rawJSON) > 0 { - if value, err := internal.StringifyJSON(d.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(d); err == nil { - return value - } - return fmt.Sprintf("%#v", d) -} - -type Decorrelation struct { - // This will be specified if this entity was decorrelated against all other entities. - All *DecorrelatedAll `json:"all,omitempty" url:"all,omitempty"` - // A list of decorrelated entities that have been explicitly decorrelated against this entity - // - // which prevents lower precedence correlations from overriding it in the future. - // For example, if an operator in the UI decorrelated tracks A and B, any automated - // correlators would be unable to correlate them since manual decorrelations have - // higher precedence than automatic ones. Precedence is determined by both correlation - // type and replication mode. - DecorrelatedEntities []*DecorrelatedSingle `json:"decorrelatedEntities,omitempty" url:"decorrelatedEntities,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (d *Decorrelation) GetAll() *DecorrelatedAll { - if d == nil { - return nil - } - return d.All -} - -func (d *Decorrelation) GetDecorrelatedEntities() []*DecorrelatedSingle { - if d == nil { - return nil - } - return d.DecorrelatedEntities -} - -func (d *Decorrelation) GetExtraProperties() map[string]interface{} { - return d.extraProperties -} - -func (d *Decorrelation) UnmarshalJSON(data []byte) error { - type unmarshaler Decorrelation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *d = Decorrelation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *d) - if err != nil { - return err - } - d.extraProperties = extraProperties - d.rawJSON = json.RawMessage(data) - return nil -} - -func (d *Decorrelation) String() string { - if len(d.rawJSON) > 0 { - if value, err := internal.StringifyJSON(d.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(d); err == nil { - return value - } - return fmt.Sprintf("%#v", d) -} - -type Dimensions struct { - // Length of the entity in meters - LengthM *float64 `json:"lengthM,omitempty" url:"lengthM,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (d *Dimensions) GetLengthM() *float64 { - if d == nil { - return nil - } - return d.LengthM -} - -func (d *Dimensions) GetExtraProperties() map[string]interface{} { - return d.extraProperties -} - -func (d *Dimensions) UnmarshalJSON(data []byte) error { - type unmarshaler Dimensions - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *d = Dimensions(value) - extraProperties, err := internal.ExtractExtraProperties(data, *d) - if err != nil { - return err - } - d.extraProperties = extraProperties - d.rawJSON = json.RawMessage(data) - return nil -} - -func (d *Dimensions) String() string { - if len(d.rawJSON) > 0 { - if value, err := internal.StringifyJSON(d.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(d); err == nil { - return value - } - return fmt.Sprintf("%#v", d) -} - -// Describes a Echelon group type. Comprised of entities which are members of the -// -// same unit or echelon. Ex: A group of tanks within a armored company or that same company -// as a member of a battalion. -type Echelon struct { - ArmyEchelon *EchelonArmyEchelon `json:"armyEchelon,omitempty" url:"armyEchelon,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *Echelon) GetArmyEchelon() *EchelonArmyEchelon { - if e == nil { - return nil - } - return e.ArmyEchelon -} - -func (e *Echelon) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *Echelon) UnmarshalJSON(data []byte) error { - type unmarshaler Echelon - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = Echelon(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *Echelon) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -type EchelonArmyEchelon string - -const ( - EchelonArmyEchelonArmyEchelonInvalid EchelonArmyEchelon = "ARMY_ECHELON_INVALID" - EchelonArmyEchelonArmyEchelonFireTeam EchelonArmyEchelon = "ARMY_ECHELON_FIRE_TEAM" - EchelonArmyEchelonArmyEchelonSquad EchelonArmyEchelon = "ARMY_ECHELON_SQUAD" - EchelonArmyEchelonArmyEchelonPlatoon EchelonArmyEchelon = "ARMY_ECHELON_PLATOON" - EchelonArmyEchelonArmyEchelonCompany EchelonArmyEchelon = "ARMY_ECHELON_COMPANY" - EchelonArmyEchelonArmyEchelonBattalion EchelonArmyEchelon = "ARMY_ECHELON_BATTALION" - EchelonArmyEchelonArmyEchelonRegiment EchelonArmyEchelon = "ARMY_ECHELON_REGIMENT" - EchelonArmyEchelonArmyEchelonBrigade EchelonArmyEchelon = "ARMY_ECHELON_BRIGADE" - EchelonArmyEchelonArmyEchelonDivision EchelonArmyEchelon = "ARMY_ECHELON_DIVISION" - EchelonArmyEchelonArmyEchelonCorps EchelonArmyEchelon = "ARMY_ECHELON_CORPS" - EchelonArmyEchelonArmyEchelonArmy EchelonArmyEchelon = "ARMY_ECHELON_ARMY" -) - -func NewEchelonArmyEchelonFromString(s string) (EchelonArmyEchelon, error) { - switch s { - case "ARMY_ECHELON_INVALID": - return EchelonArmyEchelonArmyEchelonInvalid, nil - case "ARMY_ECHELON_FIRE_TEAM": - return EchelonArmyEchelonArmyEchelonFireTeam, nil - case "ARMY_ECHELON_SQUAD": - return EchelonArmyEchelonArmyEchelonSquad, nil - case "ARMY_ECHELON_PLATOON": - return EchelonArmyEchelonArmyEchelonPlatoon, nil - case "ARMY_ECHELON_COMPANY": - return EchelonArmyEchelonArmyEchelonCompany, nil - case "ARMY_ECHELON_BATTALION": - return EchelonArmyEchelonArmyEchelonBattalion, nil - case "ARMY_ECHELON_REGIMENT": - return EchelonArmyEchelonArmyEchelonRegiment, nil - case "ARMY_ECHELON_BRIGADE": - return EchelonArmyEchelonArmyEchelonBrigade, nil - case "ARMY_ECHELON_DIVISION": - return EchelonArmyEchelonArmyEchelonDivision, nil - case "ARMY_ECHELON_CORPS": - return EchelonArmyEchelonArmyEchelonCorps, nil - case "ARMY_ECHELON_ARMY": - return EchelonArmyEchelonArmyEchelonArmy, nil - } - var t EchelonArmyEchelon - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (e EchelonArmyEchelon) Ptr() *EchelonArmyEchelon { - return &e -} - -// A representation of a single emitter notation. -type EmitterNotation struct { - EmitterNotation *string `json:"emitterNotation,omitempty" url:"emitterNotation,omitempty"` - // confidence as a percentage that the emitter notation in this component is accurate - Confidence *float64 `json:"confidence,omitempty" url:"confidence,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *EmitterNotation) GetEmitterNotation() *string { - if e == nil { - return nil - } - return e.EmitterNotation -} - -func (e *EmitterNotation) GetConfidence() *float64 { - if e == nil { - return nil - } - return e.Confidence -} - -func (e *EmitterNotation) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *EmitterNotation) UnmarshalJSON(data []byte) error { - type unmarshaler EmitterNotation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = EmitterNotation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *EmitterNotation) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -// The entity object represents a single known object within the Lattice operational environment. It contains -// -// all data associated with the entity, such as its name, ID, and other relevant components. -type Entity struct { - // A Globally Unique Identifier (GUID) for your entity. If this field is empty, the Entity Manager API - // - // automatically generates an ID when it creates the entity. - EntityID *string `json:"entityId,omitempty" url:"entityId,omitempty"` - // A human-readable entity description that's helpful for debugging purposes and human - // - // traceability. If this field is empty, the Entity Manager API generates one for you. - Description *string `json:"description,omitempty" url:"description,omitempty"` - // Indicates the entity is active and should have a lifecycle state of CREATE or UPDATE. - // - // Set this field to true when publishing an entity. - IsLive *bool `json:"isLive,omitempty" url:"isLive,omitempty"` - // The time when the entity was first known to the entity producer. If this field is empty, the Entity Manager API uses the - // - // current timestamp of when the entity is first received. - // For example, when a drone is first powered on, it might report its startup time as the created time. - // The timestamp doesn't change for the lifetime of an entity. - CreatedTime *time.Time `json:"createdTime,omitempty" url:"createdTime,omitempty"` - // Future time that expires an entity and updates the is_live flag. - // - // For entities that are constantly updating, the expiry time also updates. - // In some cases, this may differ from is_live. - // Example: Entities with tasks exported to an external system must remain - // active even after they expire. - // This field is required when publishing a prepopulated entity. - // The expiry time must be in the future, but less than 30 days from the current time. - ExpiryTime *time.Time `json:"expiryTime,omitempty" url:"expiryTime,omitempty"` - // Use noExpiry only when the entity contains information that should be available to other - // - // tasks or integrations beyond its immediate operational context. For example, use noExpiry - // for long-living geographical entities that maintain persistent relevance across multiple - // operations or tasks. - NoExpiry *bool `json:"noExpiry,omitempty" url:"noExpiry,omitempty"` - // Human-readable descriptions of what the entity is currently doing. - Status *Status `json:"status,omitempty" url:"status,omitempty"` - // Geospatial data related to the entity, including its position, kinematics, and orientation. - Location *Location `json:"location,omitempty" url:"location,omitempty"` - // Indicates uncertainty of the entity's position and kinematics. - LocationUncertainty *LocationUncertainty `json:"locationUncertainty,omitempty" url:"locationUncertainty,omitempty"` - // Geospatial representation of the entity, including entities that cover an area rather than a fixed point. - GeoShape *GeoShape `json:"geoShape,omitempty" url:"geoShape,omitempty"` - // Additional details on what the geospatial area or point represents, along with visual display details. - GeoDetails *GeoDetails `json:"geoDetails,omitempty" url:"geoDetails,omitempty"` - // Entity name displayed in the Lattice UI side panel. Also includes identifiers that other systems can use to reference the same entity. - Aliases *Aliases `json:"aliases,omitempty" url:"aliases,omitempty"` - // If this entity is tracked by another entity, this component contains data related to how it's being tracked. - Tracked *Tracked `json:"tracked,omitempty" url:"tracked,omitempty"` - // If this entity has been correlated or decorrelated to another one, this component contains information on the correlation or decorrelation. - Correlation *Correlation `json:"correlation,omitempty" url:"correlation,omitempty"` - // View of the entity. - MilView *MilView `json:"milView,omitempty" url:"milView,omitempty"` - // Ontology defines an entity's categorization in Lattice, and improves data retrieval and integration. Builds a standardized representation of the entity. - Ontology *Ontology `json:"ontology,omitempty" url:"ontology,omitempty"` - // Details an entity's available sensors. - Sensors *Sensors `json:"sensors,omitempty" url:"sensors,omitempty"` - // Details an entity's available payloads. - Payloads *Payloads `json:"payloads,omitempty" url:"payloads,omitempty"` - // Details the entity's power source. - PowerState *PowerState `json:"powerState,omitempty" url:"powerState,omitempty"` - // The primary data source provenance for this entity. - Provenance *Provenance `json:"provenance,omitempty" url:"provenance,omitempty"` - // Provenance of override data. - Overrides *Overrides `json:"overrides,omitempty" url:"overrides,omitempty"` - // Describes an entity's specific characteristics and the operations that can be performed on the entity. - // - // For example, "simulated" informs the operator that the entity is from a simulation, and "deletable" - // informs the operator (and system) that the delete operation is valid against the entity. - Indicators *Indicators `json:"indicators,omitempty" url:"indicators,omitempty"` - // The prioritization associated with an entity, such as if it's a threat or a high-value target. - TargetPriority *TargetPriority `json:"targetPriority,omitempty" url:"targetPriority,omitempty"` - // Describes an entity's signal characteristics, primarily used when an entity is a signal of interest. - Signal *Signal `json:"signal,omitempty" url:"signal,omitempty"` - // A message describing any transponder codes associated with Mode 1, 2, 3, 4, 5, S interrogations. These are related to ADS-B modes. - TransponderCodes *TransponderCodes `json:"transponderCodes,omitempty" url:"transponderCodes,omitempty"` - // Describes an entity's security classification levels at an overall classification level and on a per - // - // field level. - DataClassification *Classification `json:"dataClassification,omitempty" url:"dataClassification,omitempty"` - // A catalog of tasks that can be performed by an entity. - TaskCatalog *TaskCatalog `json:"taskCatalog,omitempty" url:"taskCatalog,omitempty"` - // Media associated with an entity, such as videos, images, or thumbnails. - Media *Media `json:"media,omitempty" url:"media,omitempty"` - // The relationships between this entity and other entities in the common operational picture (COP). - Relationships *Relationships `json:"relationships,omitempty" url:"relationships,omitempty"` - // Visual details associated with the display of an entity in the client. - VisualDetails *VisualDetails `json:"visualDetails,omitempty" url:"visualDetails,omitempty"` - // Physical dimensions of the entity. - Dimensions *Dimensions `json:"dimensions,omitempty" url:"dimensions,omitempty"` - // Additional information about an entity's route. - RouteDetails *RouteDetails `json:"routeDetails,omitempty" url:"routeDetails,omitempty"` - // Schedules associated with this entity. - Schedules *Schedules `json:"schedules,omitempty" url:"schedules,omitempty"` - // Health metrics or connection status reported by the entity. - Health *Health `json:"health,omitempty" url:"health,omitempty"` - // Details for the group associated with this entity. - GroupDetails *GroupDetails `json:"groupDetails,omitempty" url:"groupDetails,omitempty"` - // Contains relevant supply information for the entity, such as fuel. - Supplies *Supplies `json:"supplies,omitempty" url:"supplies,omitempty"` - // Orbit information for space objects. - Orbit *Orbit `json:"orbit,omitempty" url:"orbit,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *Entity) GetEntityID() *string { - if e == nil { - return nil - } - return e.EntityID -} - -func (e *Entity) GetDescription() *string { - if e == nil { - return nil - } - return e.Description -} - -func (e *Entity) GetIsLive() *bool { - if e == nil { - return nil - } - return e.IsLive -} - -func (e *Entity) GetCreatedTime() *time.Time { - if e == nil { - return nil - } - return e.CreatedTime -} - -func (e *Entity) GetExpiryTime() *time.Time { - if e == nil { - return nil - } - return e.ExpiryTime -} - -func (e *Entity) GetNoExpiry() *bool { - if e == nil { - return nil - } - return e.NoExpiry -} - -func (e *Entity) GetStatus() *Status { - if e == nil { - return nil - } - return e.Status -} - -func (e *Entity) GetLocation() *Location { - if e == nil { - return nil - } - return e.Location -} - -func (e *Entity) GetLocationUncertainty() *LocationUncertainty { - if e == nil { - return nil - } - return e.LocationUncertainty -} - -func (e *Entity) GetGeoShape() *GeoShape { - if e == nil { - return nil - } - return e.GeoShape -} - -func (e *Entity) GetGeoDetails() *GeoDetails { - if e == nil { - return nil - } - return e.GeoDetails -} - -func (e *Entity) GetAliases() *Aliases { - if e == nil { - return nil - } - return e.Aliases -} - -func (e *Entity) GetTracked() *Tracked { - if e == nil { - return nil - } - return e.Tracked -} - -func (e *Entity) GetCorrelation() *Correlation { - if e == nil { - return nil - } - return e.Correlation -} - -func (e *Entity) GetMilView() *MilView { - if e == nil { - return nil - } - return e.MilView -} - -func (e *Entity) GetOntology() *Ontology { - if e == nil { - return nil - } - return e.Ontology -} - -func (e *Entity) GetSensors() *Sensors { - if e == nil { - return nil - } - return e.Sensors -} - -func (e *Entity) GetPayloads() *Payloads { - if e == nil { - return nil - } - return e.Payloads -} - -func (e *Entity) GetPowerState() *PowerState { - if e == nil { - return nil - } - return e.PowerState -} - -func (e *Entity) GetProvenance() *Provenance { - if e == nil { - return nil - } - return e.Provenance -} - -func (e *Entity) GetOverrides() *Overrides { - if e == nil { - return nil - } - return e.Overrides -} - -func (e *Entity) GetIndicators() *Indicators { - if e == nil { - return nil - } - return e.Indicators -} - -func (e *Entity) GetTargetPriority() *TargetPriority { - if e == nil { - return nil - } - return e.TargetPriority -} - -func (e *Entity) GetSignal() *Signal { - if e == nil { - return nil - } - return e.Signal -} - -func (e *Entity) GetTransponderCodes() *TransponderCodes { - if e == nil { - return nil - } - return e.TransponderCodes -} - -func (e *Entity) GetDataClassification() *Classification { - if e == nil { - return nil - } - return e.DataClassification -} - -func (e *Entity) GetTaskCatalog() *TaskCatalog { - if e == nil { - return nil - } - return e.TaskCatalog -} - -func (e *Entity) GetMedia() *Media { - if e == nil { - return nil - } - return e.Media -} - -func (e *Entity) GetRelationships() *Relationships { - if e == nil { - return nil - } - return e.Relationships -} - -func (e *Entity) GetVisualDetails() *VisualDetails { - if e == nil { - return nil - } - return e.VisualDetails -} - -func (e *Entity) GetDimensions() *Dimensions { - if e == nil { - return nil - } - return e.Dimensions -} - -func (e *Entity) GetRouteDetails() *RouteDetails { - if e == nil { - return nil - } - return e.RouteDetails -} - -func (e *Entity) GetSchedules() *Schedules { - if e == nil { - return nil - } - return e.Schedules -} - -func (e *Entity) GetHealth() *Health { - if e == nil { - return nil - } - return e.Health -} - -func (e *Entity) GetGroupDetails() *GroupDetails { - if e == nil { - return nil - } - return e.GroupDetails -} - -func (e *Entity) GetSupplies() *Supplies { - if e == nil { - return nil - } - return e.Supplies -} - -func (e *Entity) GetOrbit() *Orbit { - if e == nil { - return nil - } - return e.Orbit -} - -func (e *Entity) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *Entity) UnmarshalJSON(data []byte) error { - type embed Entity - var unmarshaler = struct { - embed - CreatedTime *internal.DateTime `json:"createdTime,omitempty"` - ExpiryTime *internal.DateTime `json:"expiryTime,omitempty"` - }{ - embed: embed(*e), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *e = Entity(unmarshaler.embed) - e.CreatedTime = unmarshaler.CreatedTime.TimePtr() - e.ExpiryTime = unmarshaler.ExpiryTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *Entity) MarshalJSON() ([]byte, error) { - type embed Entity - var marshaler = struct { - embed - CreatedTime *internal.DateTime `json:"createdTime,omitempty"` - ExpiryTime *internal.DateTime `json:"expiryTime,omitempty"` - }{ - embed: embed(*e), - CreatedTime: internal.NewOptionalDateTime(e.CreatedTime), - ExpiryTime: internal.NewOptionalDateTime(e.ExpiryTime), - } - return json.Marshal(marshaler) -} - -func (e *Entity) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -type Enu struct { - E *float64 `json:"e,omitempty" url:"e,omitempty"` - N *float64 `json:"n,omitempty" url:"n,omitempty"` - U *float64 `json:"u,omitempty" url:"u,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *Enu) GetE() *float64 { - if e == nil { - return nil - } - return e.E -} - -func (e *Enu) GetN() *float64 { - if e == nil { - return nil - } - return e.N -} - -func (e *Enu) GetU() *float64 { - if e == nil { - return nil - } - return e.U -} - -func (e *Enu) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *Enu) UnmarshalJSON(data []byte) error { - type unmarshaler Enu - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = Enu(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *Enu) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -// Indicates ellipse characteristics and probability that an entity lies within the defined ellipse. -type ErrorEllipse struct { - // Defines the probability in percentage that an entity lies within the given ellipse: 0-1. - Probability *float64 `json:"probability,omitempty" url:"probability,omitempty"` - // Defines the distance from the center point of the ellipse to the furthest distance on the perimeter in meters. - SemiMajorAxisM *float64 `json:"semiMajorAxisM,omitempty" url:"semiMajorAxisM,omitempty"` - // Defines the distance from the center point of the ellipse to the shortest distance on the perimeter in meters. - SemiMinorAxisM *float64 `json:"semiMinorAxisM,omitempty" url:"semiMinorAxisM,omitempty"` - // The orientation of the semi-major relative to true north in degrees from clockwise: 0-180 due to symmetry across the semi-minor axis. - OrientationD *float64 `json:"orientationD,omitempty" url:"orientationD,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (e *ErrorEllipse) GetProbability() *float64 { - if e == nil { - return nil - } - return e.Probability -} - -func (e *ErrorEllipse) GetSemiMajorAxisM() *float64 { - if e == nil { - return nil - } - return e.SemiMajorAxisM -} - -func (e *ErrorEllipse) GetSemiMinorAxisM() *float64 { - if e == nil { - return nil - } - return e.SemiMinorAxisM -} - -func (e *ErrorEllipse) GetOrientationD() *float64 { - if e == nil { - return nil - } - return e.OrientationD -} - -func (e *ErrorEllipse) GetExtraProperties() map[string]interface{} { - return e.extraProperties -} - -func (e *ErrorEllipse) UnmarshalJSON(data []byte) error { - type unmarshaler ErrorEllipse - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *e = ErrorEllipse(value) - extraProperties, err := internal.ExtractExtraProperties(data, *e) - if err != nil { - return err - } - e.extraProperties = extraProperties - e.rawJSON = json.RawMessage(data) - return nil -} - -func (e *ErrorEllipse) String() string { - if len(e.rawJSON) > 0 { - if value, err := internal.StringifyJSON(e.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(e); err == nil { - return value - } - return fmt.Sprintf("%#v", e) -} - -// A field specific classification information definition. -type FieldClassificationInformation struct { - // Proto field path which is the string representation of a field. - // - // > example: signal.bandwidth_hz would be bandwidth_hz in the signal component - FieldPath *string `json:"fieldPath,omitempty" url:"fieldPath,omitempty"` - // The information which makes up the field level classification marking. - ClassificationInformation *ClassificationInformation `json:"classificationInformation,omitempty" url:"classificationInformation,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (f *FieldClassificationInformation) GetFieldPath() *string { - if f == nil { - return nil - } - return f.FieldPath -} - -func (f *FieldClassificationInformation) GetClassificationInformation() *ClassificationInformation { - if f == nil { - return nil - } - return f.ClassificationInformation -} - -func (f *FieldClassificationInformation) GetExtraProperties() map[string]interface{} { - return f.extraProperties -} - -func (f *FieldClassificationInformation) UnmarshalJSON(data []byte) error { - type unmarshaler FieldClassificationInformation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *f = FieldClassificationInformation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *f) - if err != nil { - return err - } - f.extraProperties = extraProperties - f.rawJSON = json.RawMessage(data) - return nil -} - -func (f *FieldClassificationInformation) String() string { - if len(f.rawJSON) > 0 { - if value, err := internal.StringifyJSON(f.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(f); err == nil { - return value - } - return fmt.Sprintf("%#v", f) -} - -// Sensor Field Of View closely resembling fov.proto SensorFieldOfView. -type FieldOfView struct { - // The Id for one instance of a FieldOfView, persisted across multiple updates to provide continuity during - // - // smoothing. This is relevant for sensors where the dwell schedule is on the order of - // milliseconds, making multiple FOVs a requirement for proper display of search beams. - FovID *int `json:"fovId,omitempty" url:"fovId,omitempty"` - // The Id of the mount the sensor is on. - MountID *string `json:"mountId,omitempty" url:"mountId,omitempty"` - // The field of view the sensor projected onto the ground. - ProjectedFrustum *ProjectedFrustum `json:"projectedFrustum,omitempty" url:"projectedFrustum,omitempty"` - // Center ray of the frustum projected onto the ground. - ProjectedCenterRay *Position `json:"projectedCenterRay,omitempty" url:"projectedCenterRay,omitempty"` - // The origin and direction of the center ray for this sensor relative to the ENU frame. A ray which is aligned with - // - // the positive X axis in the sensor frame will be transformed into the ray along the sensor direction in the ENU - // frame when transformed by the quaternion contained in this pose. - CenterRayPose *Pose `json:"centerRayPose,omitempty" url:"centerRayPose,omitempty"` - // Horizontal field of view in radians. - HorizontalFov *float64 `json:"horizontalFov,omitempty" url:"horizontalFov,omitempty"` - // Vertical field of view in radians. - VerticalFov *float64 `json:"verticalFov,omitempty" url:"verticalFov,omitempty"` - // Sensor range in meters. - Range *float64 `json:"range,omitempty" url:"range,omitempty"` - // The mode that this sensor is currently in, used to display for context in the UI. Some sensors can emit multiple - // - // sensor field of views with different modes, for example a radar can simultaneously search broadly and perform - // tighter bounded tracking. - Mode *FieldOfViewMode `json:"mode,omitempty" url:"mode,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (f *FieldOfView) GetFovID() *int { - if f == nil { - return nil - } - return f.FovID -} - -func (f *FieldOfView) GetMountID() *string { - if f == nil { - return nil - } - return f.MountID -} - -func (f *FieldOfView) GetProjectedFrustum() *ProjectedFrustum { - if f == nil { - return nil - } - return f.ProjectedFrustum -} - -func (f *FieldOfView) GetProjectedCenterRay() *Position { - if f == nil { - return nil - } - return f.ProjectedCenterRay -} - -func (f *FieldOfView) GetCenterRayPose() *Pose { - if f == nil { - return nil - } - return f.CenterRayPose -} - -func (f *FieldOfView) GetHorizontalFov() *float64 { - if f == nil { - return nil - } - return f.HorizontalFov -} - -func (f *FieldOfView) GetVerticalFov() *float64 { - if f == nil { - return nil - } - return f.VerticalFov -} - -func (f *FieldOfView) GetRange() *float64 { - if f == nil { - return nil - } - return f.Range -} - -func (f *FieldOfView) GetMode() *FieldOfViewMode { - if f == nil { - return nil - } - return f.Mode -} - -func (f *FieldOfView) GetExtraProperties() map[string]interface{} { - return f.extraProperties -} - -func (f *FieldOfView) UnmarshalJSON(data []byte) error { - type unmarshaler FieldOfView - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *f = FieldOfView(value) - extraProperties, err := internal.ExtractExtraProperties(data, *f) - if err != nil { - return err - } - f.extraProperties = extraProperties - f.rawJSON = json.RawMessage(data) - return nil -} - -func (f *FieldOfView) String() string { - if len(f.rawJSON) > 0 { - if value, err := internal.StringifyJSON(f.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(f); err == nil { - return value - } - return fmt.Sprintf("%#v", f) -} - -// The mode that this sensor is currently in, used to display for context in the UI. Some sensors can emit multiple -// -// sensor field of views with different modes, for example a radar can simultaneously search broadly and perform -// tighter bounded tracking. -type FieldOfViewMode string - -const ( - FieldOfViewModeSensorModeInvalid FieldOfViewMode = "SENSOR_MODE_INVALID" - FieldOfViewModeSensorModeSearch FieldOfViewMode = "SENSOR_MODE_SEARCH" - FieldOfViewModeSensorModeTrack FieldOfViewMode = "SENSOR_MODE_TRACK" - FieldOfViewModeSensorModeWeaponSupport FieldOfViewMode = "SENSOR_MODE_WEAPON_SUPPORT" - FieldOfViewModeSensorModeAuto FieldOfViewMode = "SENSOR_MODE_AUTO" - FieldOfViewModeSensorModeMute FieldOfViewMode = "SENSOR_MODE_MUTE" -) - -func NewFieldOfViewModeFromString(s string) (FieldOfViewMode, error) { - switch s { - case "SENSOR_MODE_INVALID": - return FieldOfViewModeSensorModeInvalid, nil - case "SENSOR_MODE_SEARCH": - return FieldOfViewModeSensorModeSearch, nil - case "SENSOR_MODE_TRACK": - return FieldOfViewModeSensorModeTrack, nil - case "SENSOR_MODE_WEAPON_SUPPORT": - return FieldOfViewModeSensorModeWeaponSupport, nil - case "SENSOR_MODE_AUTO": - return FieldOfViewModeSensorModeAuto, nil - case "SENSOR_MODE_MUTE": - return FieldOfViewModeSensorModeMute, nil - } - var t FieldOfViewMode - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (f FieldOfViewMode) Ptr() *FieldOfViewMode { - return &f -} - -// A fix of a signal. No extra fields but it is expected that location should be populated when using this report. -type Fixed struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (f *Fixed) GetExtraProperties() map[string]interface{} { - return f.extraProperties -} - -func (f *Fixed) UnmarshalJSON(data []byte) error { - type unmarshaler Fixed - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *f = Fixed(value) - extraProperties, err := internal.ExtractExtraProperties(data, *f) - if err != nil { - return err - } - f.extraProperties = extraProperties - f.rawJSON = json.RawMessage(data) - return nil -} - -func (f *Fixed) String() string { - if len(f.rawJSON) > 0 { - if value, err := internal.StringifyJSON(f.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(f); err == nil { - return value - } - return fmt.Sprintf("%#v", f) -} - -// A component for describing frequency. -type Frequency struct { - // Indicates a frequency of a signal (Hz) with its standard deviation. - FrequencyHz *Measurement `json:"frequencyHz,omitempty" url:"frequencyHz,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (f *Frequency) GetFrequencyHz() *Measurement { - if f == nil { - return nil - } - return f.FrequencyHz -} - -func (f *Frequency) GetExtraProperties() map[string]interface{} { - return f.extraProperties -} - -func (f *Frequency) UnmarshalJSON(data []byte) error { - type unmarshaler Frequency - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *f = Frequency(value) - extraProperties, err := internal.ExtractExtraProperties(data, *f) - if err != nil { - return err - } - f.extraProperties = extraProperties - f.rawJSON = json.RawMessage(data) - return nil -} - -func (f *Frequency) String() string { - if len(f.rawJSON) > 0 { - if value, err := internal.StringifyJSON(f.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(f); err == nil { - return value - } - return fmt.Sprintf("%#v", f) -} - -// A component to represent a frequency range. -type FrequencyRange struct { - // Indicates the lowest measured frequency of a signal (Hz). - MinimumFrequencyHz *Frequency `json:"minimumFrequencyHz,omitempty" url:"minimumFrequencyHz,omitempty"` - // Indicates the maximum measured frequency of a signal (Hz). - MaximumFrequencyHz *Frequency `json:"maximumFrequencyHz,omitempty" url:"maximumFrequencyHz,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (f *FrequencyRange) GetMinimumFrequencyHz() *Frequency { - if f == nil { - return nil - } - return f.MinimumFrequencyHz -} - -func (f *FrequencyRange) GetMaximumFrequencyHz() *Frequency { - if f == nil { - return nil - } - return f.MaximumFrequencyHz -} - -func (f *FrequencyRange) GetExtraProperties() map[string]interface{} { - return f.extraProperties -} - -func (f *FrequencyRange) UnmarshalJSON(data []byte) error { - type unmarshaler FrequencyRange - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *f = FrequencyRange(value) - extraProperties, err := internal.ExtractExtraProperties(data, *f) - if err != nil { - return err - } - f.extraProperties = extraProperties - f.rawJSON = json.RawMessage(data) - return nil -} - -func (f *FrequencyRange) String() string { - if len(f.rawJSON) > 0 { - if value, err := internal.StringifyJSON(f.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(f); err == nil { - return value - } - return fmt.Sprintf("%#v", f) -} - -// Fuel describes an entity's repository of fuels stores including current amount, operational requirements, and maximum authorized capacity -type Fuel struct { - // unique fuel identifier - FuelID *string `json:"fuelId,omitempty" url:"fuelId,omitempty"` - // long form name of the fuel source. - Name *string `json:"name,omitempty" url:"name,omitempty"` - // timestamp the information was reported - ReportedDate *time.Time `json:"reportedDate,omitempty" url:"reportedDate,omitempty"` - // amount of gallons on hand - AmountGallons *int `json:"amountGallons,omitempty" url:"amountGallons,omitempty"` - // how much the asset is allowed to have available (in gallons) - MaxAuthorizedCapacityGallons *int `json:"maxAuthorizedCapacityGallons,omitempty" url:"maxAuthorizedCapacityGallons,omitempty"` - // minimum required for operations (in gallons) - OperationalRequirementGallons *int `json:"operationalRequirementGallons,omitempty" url:"operationalRequirementGallons,omitempty"` - // fuel in a single asset may have different levels of classification - // - // use case: fuel for a SECRET asset while diesel fuel may be UNCLASSIFIED - DataClassification *Classification `json:"dataClassification,omitempty" url:"dataClassification,omitempty"` - // source of information - DataSource *string `json:"dataSource,omitempty" url:"dataSource,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (f *Fuel) GetFuelID() *string { - if f == nil { - return nil - } - return f.FuelID -} - -func (f *Fuel) GetName() *string { - if f == nil { - return nil - } - return f.Name -} - -func (f *Fuel) GetReportedDate() *time.Time { - if f == nil { - return nil - } - return f.ReportedDate -} - -func (f *Fuel) GetAmountGallons() *int { - if f == nil { - return nil - } - return f.AmountGallons -} - -func (f *Fuel) GetMaxAuthorizedCapacityGallons() *int { - if f == nil { - return nil - } - return f.MaxAuthorizedCapacityGallons -} - -func (f *Fuel) GetOperationalRequirementGallons() *int { - if f == nil { - return nil - } - return f.OperationalRequirementGallons -} - -func (f *Fuel) GetDataClassification() *Classification { - if f == nil { - return nil - } - return f.DataClassification -} - -func (f *Fuel) GetDataSource() *string { - if f == nil { - return nil - } - return f.DataSource -} - -func (f *Fuel) GetExtraProperties() map[string]interface{} { - return f.extraProperties -} - -func (f *Fuel) UnmarshalJSON(data []byte) error { - type embed Fuel - var unmarshaler = struct { - embed - ReportedDate *internal.DateTime `json:"reportedDate,omitempty"` - }{ - embed: embed(*f), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *f = Fuel(unmarshaler.embed) - f.ReportedDate = unmarshaler.ReportedDate.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *f) - if err != nil { - return err - } - f.extraProperties = extraProperties - f.rawJSON = json.RawMessage(data) - return nil -} - -func (f *Fuel) MarshalJSON() ([]byte, error) { - type embed Fuel - var marshaler = struct { - embed - ReportedDate *internal.DateTime `json:"reportedDate,omitempty"` - }{ - embed: embed(*f), - ReportedDate: internal.NewOptionalDateTime(f.ReportedDate), - } - return json.Marshal(marshaler) -} - -func (f *Fuel) String() string { - if len(f.rawJSON) > 0 { - if value, err := internal.StringifyJSON(f.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(f); err == nil { - return value - } - return fmt.Sprintf("%#v", f) -} - -// A component that describes a geo-entity. -type GeoDetails struct { - Type *GeoDetailsType `json:"type,omitempty" url:"type,omitempty"` - ControlArea *ControlAreaDetails `json:"controlArea,omitempty" url:"controlArea,omitempty"` - Acm *AcmDetails `json:"acm,omitempty" url:"acm,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoDetails) GetType() *GeoDetailsType { - if g == nil { - return nil - } - return g.Type -} - -func (g *GeoDetails) GetControlArea() *ControlAreaDetails { - if g == nil { - return nil - } - return g.ControlArea -} - -func (g *GeoDetails) GetAcm() *AcmDetails { - if g == nil { - return nil - } - return g.Acm -} - -func (g *GeoDetails) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoDetails) UnmarshalJSON(data []byte) error { - type unmarshaler GeoDetails - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoDetails(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoDetails) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -type GeoDetailsType string - -const ( - GeoDetailsTypeGeoTypeInvalid GeoDetailsType = "GEO_TYPE_INVALID" - GeoDetailsTypeGeoTypeGeneral GeoDetailsType = "GEO_TYPE_GENERAL" - GeoDetailsTypeGeoTypeHazard GeoDetailsType = "GEO_TYPE_HAZARD" - GeoDetailsTypeGeoTypeEmergency GeoDetailsType = "GEO_TYPE_EMERGENCY" - GeoDetailsTypeGeoTypeEngagementZone GeoDetailsType = "GEO_TYPE_ENGAGEMENT_ZONE" - GeoDetailsTypeGeoTypeControlArea GeoDetailsType = "GEO_TYPE_CONTROL_AREA" - GeoDetailsTypeGeoTypeBullseye GeoDetailsType = "GEO_TYPE_BULLSEYE" - GeoDetailsTypeGeoTypeAcm GeoDetailsType = "GEO_TYPE_ACM" -) - -func NewGeoDetailsTypeFromString(s string) (GeoDetailsType, error) { - switch s { - case "GEO_TYPE_INVALID": - return GeoDetailsTypeGeoTypeInvalid, nil - case "GEO_TYPE_GENERAL": - return GeoDetailsTypeGeoTypeGeneral, nil - case "GEO_TYPE_HAZARD": - return GeoDetailsTypeGeoTypeHazard, nil - case "GEO_TYPE_EMERGENCY": - return GeoDetailsTypeGeoTypeEmergency, nil - case "GEO_TYPE_ENGAGEMENT_ZONE": - return GeoDetailsTypeGeoTypeEngagementZone, nil - case "GEO_TYPE_CONTROL_AREA": - return GeoDetailsTypeGeoTypeControlArea, nil - case "GEO_TYPE_BULLSEYE": - return GeoDetailsTypeGeoTypeBullseye, nil - case "GEO_TYPE_ACM": - return GeoDetailsTypeGeoTypeAcm, nil - } - var t GeoDetailsType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (g GeoDetailsType) Ptr() *GeoDetailsType { - return &g -} - -// An ellipse shaped geo-entity. -// -// For a circle, the major and minor axis would be the same values. -// This shape is NOT Geo-JSON compatible. -type GeoEllipse struct { - // Defines the distance from the center point of the ellipse to the furthest distance on the perimeter in meters. - SemiMajorAxisM *float64 `json:"semiMajorAxisM,omitempty" url:"semiMajorAxisM,omitempty"` - // Defines the distance from the center point of the ellipse to the shortest distance on the perimeter in meters. - SemiMinorAxisM *float64 `json:"semiMinorAxisM,omitempty" url:"semiMinorAxisM,omitempty"` - // The orientation of the semi-major relative to true north in degrees from clockwise: 0-180 due to symmetry across the semi-minor axis. - OrientationD *float64 `json:"orientationD,omitempty" url:"orientationD,omitempty"` - // Optional height above entity position to extrude in meters. A non-zero value creates an elliptic cylinder - HeightM *float64 `json:"heightM,omitempty" url:"heightM,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoEllipse) GetSemiMajorAxisM() *float64 { - if g == nil { - return nil - } - return g.SemiMajorAxisM -} - -func (g *GeoEllipse) GetSemiMinorAxisM() *float64 { - if g == nil { - return nil - } - return g.SemiMinorAxisM -} - -func (g *GeoEllipse) GetOrientationD() *float64 { - if g == nil { - return nil - } - return g.OrientationD -} - -func (g *GeoEllipse) GetHeightM() *float64 { - if g == nil { - return nil - } - return g.HeightM -} - -func (g *GeoEllipse) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoEllipse) UnmarshalJSON(data []byte) error { - type unmarshaler GeoEllipse - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoEllipse(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoEllipse) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// An ellipsoid shaped geo-entity. -// -// Principal axis lengths are defined in entity body space -// This shape is NOT Geo-JSON compatible. -type GeoEllipsoid struct { - // Defines the distance from the center point to the surface along the forward axis - ForwardAxisM *float64 `json:"forwardAxisM,omitempty" url:"forwardAxisM,omitempty"` - // Defines the distance from the center point to the surface along the side axis - SideAxisM *float64 `json:"sideAxisM,omitempty" url:"sideAxisM,omitempty"` - // Defines the distance from the center point to the surface along the up axis - UpAxisM *float64 `json:"upAxisM,omitempty" url:"upAxisM,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoEllipsoid) GetForwardAxisM() *float64 { - if g == nil { - return nil - } - return g.ForwardAxisM -} - -func (g *GeoEllipsoid) GetSideAxisM() *float64 { - if g == nil { - return nil - } - return g.SideAxisM -} - -func (g *GeoEllipsoid) GetUpAxisM() *float64 { - if g == nil { - return nil - } - return g.UpAxisM -} - -func (g *GeoEllipsoid) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoEllipsoid) UnmarshalJSON(data []byte) error { - type unmarshaler GeoEllipsoid - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoEllipsoid(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoEllipsoid) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A line shaped geo-entity. -// -// See https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.4 -type GeoLine struct { - Positions []*Position `json:"positions,omitempty" url:"positions,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoLine) GetPositions() []*Position { - if g == nil { - return nil - } - return g.Positions -} - -func (g *GeoLine) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoLine) UnmarshalJSON(data []byte) error { - type unmarshaler GeoLine - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoLine(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoLine) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A point shaped geo-entity. -// -// See https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.2 -type GeoPoint struct { - Position *Position `json:"position,omitempty" url:"position,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoPoint) GetPosition() *Position { - if g == nil { - return nil - } - return g.Position -} - -func (g *GeoPoint) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoPoint) UnmarshalJSON(data []byte) error { - type unmarshaler GeoPoint - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoPoint(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoPoint) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A polygon shaped geo-entity. -// -// See https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.6, only canonical representations accepted -type GeoPolygon struct { - // An array of LinearRings where the first item is the exterior ring and subsequent items are interior rings. - Rings []*LinearRing `json:"rings,omitempty" url:"rings,omitempty"` - // An extension hint that this polygon is a rectangle. When true this implies several things: - // - exactly 1 linear ring with 5 points (starting corner, 3 other corners and start again) - // - each point has the same altitude corresponding with the plane of the rectangle - // - each point has the same height (either all present and equal, or all not present) - IsRectangle *bool `json:"isRectangle,omitempty" url:"isRectangle,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoPolygon) GetRings() []*LinearRing { - if g == nil { - return nil - } - return g.Rings -} - -func (g *GeoPolygon) GetIsRectangle() *bool { - if g == nil { - return nil - } - return g.IsRectangle -} - -func (g *GeoPolygon) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoPolygon) UnmarshalJSON(data []byte) error { - type unmarshaler GeoPolygon - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoPolygon(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoPolygon) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A position in a GeoPolygon with an optional extruded height. -type GeoPolygonPosition struct { - // base position. if no altitude set, its on the ground. - Position *Position `json:"position,omitempty" url:"position,omitempty"` - // optional height above base position to extrude in meters. - // - // for a given polygon, all points should have a height or none of them. - // strictly GeoJSON compatible polygons will not have this set. - HeightM *float64 `json:"heightM,omitempty" url:"heightM,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoPolygonPosition) GetPosition() *Position { - if g == nil { - return nil - } - return g.Position -} - -func (g *GeoPolygonPosition) GetHeightM() *float64 { - if g == nil { - return nil - } - return g.HeightM -} - -func (g *GeoPolygonPosition) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoPolygonPosition) UnmarshalJSON(data []byte) error { - type unmarshaler GeoPolygonPosition - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoPolygonPosition(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoPolygonPosition) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A component that describes the shape of a geo-entity. -type GeoShape struct { - Point *GeoPoint `json:"point,omitempty" url:"point,omitempty"` - Line *GeoLine `json:"line,omitempty" url:"line,omitempty"` - Polygon *GeoPolygon `json:"polygon,omitempty" url:"polygon,omitempty"` - Ellipse *GeoEllipse `json:"ellipse,omitempty" url:"ellipse,omitempty"` - Ellipsoid *GeoEllipsoid `json:"ellipsoid,omitempty" url:"ellipsoid,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GeoShape) GetPoint() *GeoPoint { - if g == nil { - return nil - } - return g.Point -} - -func (g *GeoShape) GetLine() *GeoLine { - if g == nil { - return nil - } - return g.Line -} - -func (g *GeoShape) GetPolygon() *GeoPolygon { - if g == nil { - return nil - } - return g.Polygon -} - -func (g *GeoShape) GetEllipse() *GeoEllipse { - if g == nil { - return nil - } - return g.Ellipse -} - -func (g *GeoShape) GetEllipsoid() *GeoEllipsoid { - if g == nil { - return nil - } - return g.Ellipsoid -} - -func (g *GeoShape) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GeoShape) UnmarshalJSON(data []byte) error { - type unmarshaler GeoShape - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GeoShape(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GeoShape) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// Contains an arbitrary serialized message along with a @type that describes the type of the serialized message. -type GoogleProtobufAny struct { - // The type of the serialized message. - Type *string `json:"@type,omitempty" url:"@type,omitempty"` - - ExtraProperties map[string]interface{} `json:"-" url:"-"` - - rawJSON json.RawMessage -} - -func (g *GoogleProtobufAny) GetType() *string { - if g == nil { - return nil - } - return g.Type -} - -func (g *GoogleProtobufAny) GetExtraProperties() map[string]interface{} { - return g.ExtraProperties -} - -func (g *GoogleProtobufAny) UnmarshalJSON(data []byte) error { - type embed GoogleProtobufAny - var unmarshaler = struct { - embed - }{ - embed: embed(*g), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *g = GoogleProtobufAny(unmarshaler.embed) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.ExtraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GoogleProtobufAny) MarshalJSON() ([]byte, error) { - type embed GoogleProtobufAny - var marshaler = struct { - embed - }{ - embed: embed(*g), - } - return internal.MarshalJSONWithExtraProperties(marshaler, g.ExtraProperties) -} - -func (g *GoogleProtobufAny) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A GroupChild relationship is a uni-directional relationship indicating that (1) this entity -// -// represents an Entity Group and (2) the related entity is a child member of this group. The presence of this -// relationship alone determines that the type of group is an Entity Group. -type GroupChild struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GroupChild) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GroupChild) UnmarshalJSON(data []byte) error { - type unmarshaler GroupChild - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GroupChild(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GroupChild) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// Details related to grouping for this entity -type GroupDetails struct { - Team *Team `json:"team,omitempty" url:"team,omitempty"` - Echelon *Echelon `json:"echelon,omitempty" url:"echelon,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GroupDetails) GetTeam() *Team { - if g == nil { - return nil - } - return g.Team -} - -func (g *GroupDetails) GetEchelon() *Echelon { - if g == nil { - return nil - } - return g.Echelon -} - -func (g *GroupDetails) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GroupDetails) UnmarshalJSON(data []byte) error { - type unmarshaler GroupDetails - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GroupDetails(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GroupDetails) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// A GroupParent relationship is a uni-directional relationship indicating that this entity is a member of -// -// the Entity Group represented by the related entity. The presence of this relationship alone determines that -// the type of group that this entity is a member of is an Entity Group. -type GroupParent struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (g *GroupParent) GetExtraProperties() map[string]interface{} { - return g.extraProperties -} - -func (g *GroupParent) UnmarshalJSON(data []byte) error { - type unmarshaler GroupParent - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *g = GroupParent(value) - extraProperties, err := internal.ExtractExtraProperties(data, *g) - if err != nil { - return err - } - g.extraProperties = extraProperties - g.rawJSON = json.RawMessage(data) - return nil -} - -func (g *GroupParent) String() string { - if len(g.rawJSON) > 0 { - if value, err := internal.StringifyJSON(g.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(g); err == nil { - return value - } - return fmt.Sprintf("%#v", g) -} - -// General health of the entity as reported by the entity. -type Health struct { - // Status indicating whether the entity is able to communicate with Entity Manager. - ConnectionStatus *HealthConnectionStatus `json:"connectionStatus,omitempty" url:"connectionStatus,omitempty"` - // Top-level health status; typically a roll-up of individual component healths. - HealthStatus *HealthHealthStatus `json:"healthStatus,omitempty" url:"healthStatus,omitempty"` - // Health of individual components running on this Entity. - Components []*ComponentHealth `json:"components,omitempty" url:"components,omitempty"` - // The update time for the top-level health information. - // - // If this timestamp is unset, the data is assumed to be most recent - UpdateTime *time.Time `json:"updateTime,omitempty" url:"updateTime,omitempty"` - // Active alerts indicate a critical change in system state sent by the asset - // - // that must be made known to an operator or consumer of the common operating picture. - // Alerts are different from ComponentHealth messages--an active alert does not necessarily - // indicate a component is in an unhealthy state. For example, an asset may trigger - // an active alert based on fuel levels running low. Alerts should be removed from this list when their conditions - // are cleared. In other words, only active alerts should be reported here. - ActiveAlerts []*Alert `json:"activeAlerts,omitempty" url:"activeAlerts,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (h *Health) GetConnectionStatus() *HealthConnectionStatus { - if h == nil { - return nil - } - return h.ConnectionStatus -} - -func (h *Health) GetHealthStatus() *HealthHealthStatus { - if h == nil { - return nil - } - return h.HealthStatus -} - -func (h *Health) GetComponents() []*ComponentHealth { - if h == nil { - return nil - } - return h.Components -} - -func (h *Health) GetUpdateTime() *time.Time { - if h == nil { - return nil - } - return h.UpdateTime -} - -func (h *Health) GetActiveAlerts() []*Alert { - if h == nil { - return nil - } - return h.ActiveAlerts -} - -func (h *Health) GetExtraProperties() map[string]interface{} { - return h.extraProperties -} - -func (h *Health) UnmarshalJSON(data []byte) error { - type embed Health - var unmarshaler = struct { - embed - UpdateTime *internal.DateTime `json:"updateTime,omitempty"` - }{ - embed: embed(*h), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *h = Health(unmarshaler.embed) - h.UpdateTime = unmarshaler.UpdateTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *h) - if err != nil { - return err - } - h.extraProperties = extraProperties - h.rawJSON = json.RawMessage(data) - return nil -} - -func (h *Health) MarshalJSON() ([]byte, error) { - type embed Health - var marshaler = struct { - embed - UpdateTime *internal.DateTime `json:"updateTime,omitempty"` - }{ - embed: embed(*h), - UpdateTime: internal.NewOptionalDateTime(h.UpdateTime), - } - return json.Marshal(marshaler) -} - -func (h *Health) String() string { - if len(h.rawJSON) > 0 { - if value, err := internal.StringifyJSON(h.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(h); err == nil { - return value - } - return fmt.Sprintf("%#v", h) -} - -// Status indicating whether the entity is able to communicate with Entity Manager. -type HealthConnectionStatus string - -const ( - HealthConnectionStatusConnectionStatusInvalid HealthConnectionStatus = "CONNECTION_STATUS_INVALID" - HealthConnectionStatusConnectionStatusOnline HealthConnectionStatus = "CONNECTION_STATUS_ONLINE" - HealthConnectionStatusConnectionStatusOffline HealthConnectionStatus = "CONNECTION_STATUS_OFFLINE" -) - -func NewHealthConnectionStatusFromString(s string) (HealthConnectionStatus, error) { - switch s { - case "CONNECTION_STATUS_INVALID": - return HealthConnectionStatusConnectionStatusInvalid, nil - case "CONNECTION_STATUS_ONLINE": - return HealthConnectionStatusConnectionStatusOnline, nil - case "CONNECTION_STATUS_OFFLINE": - return HealthConnectionStatusConnectionStatusOffline, nil - } - var t HealthConnectionStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (h HealthConnectionStatus) Ptr() *HealthConnectionStatus { - return &h -} - -// Top-level health status; typically a roll-up of individual component healths. -type HealthHealthStatus string - -const ( - HealthHealthStatusHealthStatusInvalid HealthHealthStatus = "HEALTH_STATUS_INVALID" - HealthHealthStatusHealthStatusHealthy HealthHealthStatus = "HEALTH_STATUS_HEALTHY" - HealthHealthStatusHealthStatusWarn HealthHealthStatus = "HEALTH_STATUS_WARN" - HealthHealthStatusHealthStatusFail HealthHealthStatus = "HEALTH_STATUS_FAIL" - HealthHealthStatusHealthStatusOffline HealthHealthStatus = "HEALTH_STATUS_OFFLINE" - HealthHealthStatusHealthStatusNotReady HealthHealthStatus = "HEALTH_STATUS_NOT_READY" -) - -func NewHealthHealthStatusFromString(s string) (HealthHealthStatus, error) { - switch s { - case "HEALTH_STATUS_INVALID": - return HealthHealthStatusHealthStatusInvalid, nil - case "HEALTH_STATUS_HEALTHY": - return HealthHealthStatusHealthStatusHealthy, nil - case "HEALTH_STATUS_WARN": - return HealthHealthStatusHealthStatusWarn, nil - case "HEALTH_STATUS_FAIL": - return HealthHealthStatusHealthStatusFail, nil - case "HEALTH_STATUS_OFFLINE": - return HealthHealthStatusHealthStatusOffline, nil - case "HEALTH_STATUS_NOT_READY": - return HealthHealthStatusHealthStatusNotReady, nil - } - var t HealthHealthStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (h HealthHealthStatus) Ptr() *HealthHealthStatus { - return &h -} - -// Describes whether something is a high value target or not. -type HighValueTarget struct { - // Indicates whether the target matches any description from a high value target list. - IsHighValueTarget *bool `json:"isHighValueTarget,omitempty" url:"isHighValueTarget,omitempty"` - // The priority associated with the target. If the target's description appears on multiple high value target lists, - // - // the priority will be a reflection of the highest priority of all of those list's target description. - // - // A lower value indicates the target is of a higher priority, with 1 being the highest possible priority. A value of - // 0 indicates there is no priority associated with this target. - TargetPriority *int `json:"targetPriority,omitempty" url:"targetPriority,omitempty"` - // All of the high value target descriptions that the target matches against. - TargetMatches []*HighValueTargetMatch `json:"targetMatches,omitempty" url:"targetMatches,omitempty"` - // Indicates whether the target is a 'High Payoff Target'. Targets can be one or both of high value and high payoff. - IsHighPayoffTarget *bool `json:"isHighPayoffTarget,omitempty" url:"isHighPayoffTarget,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (h *HighValueTarget) GetIsHighValueTarget() *bool { - if h == nil { - return nil - } - return h.IsHighValueTarget -} - -func (h *HighValueTarget) GetTargetPriority() *int { - if h == nil { - return nil - } - return h.TargetPriority -} - -func (h *HighValueTarget) GetTargetMatches() []*HighValueTargetMatch { - if h == nil { - return nil - } - return h.TargetMatches -} - -func (h *HighValueTarget) GetIsHighPayoffTarget() *bool { - if h == nil { - return nil - } - return h.IsHighPayoffTarget -} - -func (h *HighValueTarget) GetExtraProperties() map[string]interface{} { - return h.extraProperties -} - -func (h *HighValueTarget) UnmarshalJSON(data []byte) error { - type unmarshaler HighValueTarget - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *h = HighValueTarget(value) - extraProperties, err := internal.ExtractExtraProperties(data, *h) - if err != nil { - return err - } - h.extraProperties = extraProperties - h.rawJSON = json.RawMessage(data) - return nil -} - -func (h *HighValueTarget) String() string { - if len(h.rawJSON) > 0 { - if value, err := internal.StringifyJSON(h.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(h); err == nil { - return value - } - return fmt.Sprintf("%#v", h) -} - -type HighValueTargetMatch struct { - // The ID of the high value target list that matches the target description. - HighValueTargetListID *string `json:"highValueTargetListId,omitempty" url:"highValueTargetListId,omitempty"` - // The ID of the specific high value target description within a high value target list that was matched against. - // - // The ID is considered to be a globally unique identifier across all high value target IDs. - HighValueTargetDescriptionID *string `json:"highValueTargetDescriptionId,omitempty" url:"highValueTargetDescriptionId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (h *HighValueTargetMatch) GetHighValueTargetListID() *string { - if h == nil { - return nil - } - return h.HighValueTargetListID -} - -func (h *HighValueTargetMatch) GetHighValueTargetDescriptionID() *string { - if h == nil { - return nil - } - return h.HighValueTargetDescriptionID -} - -func (h *HighValueTargetMatch) GetExtraProperties() map[string]interface{} { - return h.extraProperties -} - -func (h *HighValueTargetMatch) UnmarshalJSON(data []byte) error { - type unmarshaler HighValueTargetMatch - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *h = HighValueTargetMatch(value) - extraProperties, err := internal.ExtractExtraProperties(data, *h) - if err != nil { - return err - } - h.extraProperties = extraProperties - h.rawJSON = json.RawMessage(data) - return nil -} - -func (h *HighValueTargetMatch) String() string { - if len(h.rawJSON) > 0 { - if value, err := internal.StringifyJSON(h.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(h); err == nil { - return value - } - return fmt.Sprintf("%#v", h) -} - -// Indicators to describe entity to consumers. -type Indicators struct { - Simulated *bool `json:"simulated,omitempty" url:"simulated,omitempty"` - Exercise *bool `json:"exercise,omitempty" url:"exercise,omitempty"` - Emergency *bool `json:"emergency,omitempty" url:"emergency,omitempty"` - C2 *bool `json:"c2,omitempty" url:"c2,omitempty"` - // Indicates the Entity should be egressed to external sources. - // - // Integrations choose how the egressing happens (e.g. if an Entity needs fuzzing). - Egressable *bool `json:"egressable,omitempty" url:"egressable,omitempty"` - // A signal of arbitrary importance such that the entity should be globally marked for all users - Starred *bool `json:"starred,omitempty" url:"starred,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (i *Indicators) GetSimulated() *bool { - if i == nil { - return nil - } - return i.Simulated -} - -func (i *Indicators) GetExercise() *bool { - if i == nil { - return nil - } - return i.Exercise -} - -func (i *Indicators) GetEmergency() *bool { - if i == nil { - return nil - } - return i.Emergency -} - -func (i *Indicators) GetC2() *bool { - if i == nil { - return nil - } - return i.C2 -} - -func (i *Indicators) GetEgressable() *bool { - if i == nil { - return nil - } - return i.Egressable -} - -func (i *Indicators) GetStarred() *bool { - if i == nil { - return nil - } - return i.Starred -} - -func (i *Indicators) GetExtraProperties() map[string]interface{} { - return i.extraProperties -} - -func (i *Indicators) UnmarshalJSON(data []byte) error { - type unmarshaler Indicators - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *i = Indicators(value) - extraProperties, err := internal.ExtractExtraProperties(data, *i) - if err != nil { - return err - } - i.extraProperties = extraProperties - i.rawJSON = json.RawMessage(data) - return nil -} - -func (i *Indicators) String() string { - if len(i.rawJSON) > 0 { - if value, err := internal.StringifyJSON(i.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(i); err == nil { - return value - } - return fmt.Sprintf("%#v", i) -} - -// A line of bearing of a signal. -type LineOfBearing struct { - // The direction pointing from this entity to the detection - AngleOfArrival *AngleOfArrival `json:"angleOfArrival,omitempty" url:"angleOfArrival,omitempty"` - // The estimated distance of the detection - RangeEstimateM *Measurement `json:"rangeEstimateM,omitempty" url:"rangeEstimateM,omitempty"` - // The maximum distance of the detection - MaxRangeM *Measurement `json:"maxRangeM,omitempty" url:"maxRangeM,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (l *LineOfBearing) GetAngleOfArrival() *AngleOfArrival { - if l == nil { - return nil - } - return l.AngleOfArrival -} - -func (l *LineOfBearing) GetRangeEstimateM() *Measurement { - if l == nil { - return nil - } - return l.RangeEstimateM -} - -func (l *LineOfBearing) GetMaxRangeM() *Measurement { - if l == nil { - return nil - } - return l.MaxRangeM -} - -func (l *LineOfBearing) GetExtraProperties() map[string]interface{} { - return l.extraProperties -} - -func (l *LineOfBearing) UnmarshalJSON(data []byte) error { - type unmarshaler LineOfBearing - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *l = LineOfBearing(value) - extraProperties, err := internal.ExtractExtraProperties(data, *l) - if err != nil { - return err - } - l.extraProperties = extraProperties - l.rawJSON = json.RawMessage(data) - return nil -} - -func (l *LineOfBearing) String() string { - if len(l.rawJSON) > 0 { - if value, err := internal.StringifyJSON(l.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(l); err == nil { - return value - } - return fmt.Sprintf("%#v", l) -} - -// A closed ring of points. The first and last point must be the same. -type LinearRing struct { - Positions []*GeoPolygonPosition `json:"positions,omitempty" url:"positions,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (l *LinearRing) GetPositions() []*GeoPolygonPosition { - if l == nil { - return nil - } - return l.Positions -} - -func (l *LinearRing) GetExtraProperties() map[string]interface{} { - return l.extraProperties -} - -func (l *LinearRing) UnmarshalJSON(data []byte) error { - type unmarshaler LinearRing - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *l = LinearRing(value) - extraProperties, err := internal.ExtractExtraProperties(data, *l) - if err != nil { - return err - } - l.extraProperties = extraProperties - l.rawJSON = json.RawMessage(data) - return nil -} - -func (l *LinearRing) String() string { - if len(l.rawJSON) > 0 { - if value, err := internal.StringifyJSON(l.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(l); err == nil { - return value - } - return fmt.Sprintf("%#v", l) -} - -type Lla struct { - Lon *float64 `json:"lon,omitempty" url:"lon,omitempty"` - Lat *float64 `json:"lat,omitempty" url:"lat,omitempty"` - Alt *float64 `json:"alt,omitempty" url:"alt,omitempty"` - Is2D *bool `json:"is2d,omitempty" url:"is2d,omitempty"` - // Meaning of alt. - // - // altitude in meters above either WGS84 or EGM96, use altitude_reference to - // determine what zero means. - AltitudeReference *LlaAltitudeReference `json:"altitudeReference,omitempty" url:"altitudeReference,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (l *Lla) GetLon() *float64 { - if l == nil { - return nil - } - return l.Lon -} - -func (l *Lla) GetLat() *float64 { - if l == nil { - return nil - } - return l.Lat -} - -func (l *Lla) GetAlt() *float64 { - if l == nil { - return nil - } - return l.Alt -} - -func (l *Lla) GetIs2D() *bool { - if l == nil { - return nil - } - return l.Is2D -} - -func (l *Lla) GetAltitudeReference() *LlaAltitudeReference { - if l == nil { - return nil - } - return l.AltitudeReference -} - -func (l *Lla) GetExtraProperties() map[string]interface{} { - return l.extraProperties -} - -func (l *Lla) UnmarshalJSON(data []byte) error { - type unmarshaler Lla - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *l = Lla(value) - extraProperties, err := internal.ExtractExtraProperties(data, *l) - if err != nil { - return err - } - l.extraProperties = extraProperties - l.rawJSON = json.RawMessage(data) - return nil -} - -func (l *Lla) String() string { - if len(l.rawJSON) > 0 { - if value, err := internal.StringifyJSON(l.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(l); err == nil { - return value - } - return fmt.Sprintf("%#v", l) -} - -// Meaning of alt. -// -// altitude in meters above either WGS84 or EGM96, use altitude_reference to -// determine what zero means. -type LlaAltitudeReference string - -const ( - LlaAltitudeReferenceAltitudeReferenceInvalid LlaAltitudeReference = "ALTITUDE_REFERENCE_INVALID" - LlaAltitudeReferenceAltitudeReferenceHeightAboveWgs84 LlaAltitudeReference = "ALTITUDE_REFERENCE_HEIGHT_ABOVE_WGS84" - LlaAltitudeReferenceAltitudeReferenceHeightAboveEgm96 LlaAltitudeReference = "ALTITUDE_REFERENCE_HEIGHT_ABOVE_EGM96" - LlaAltitudeReferenceAltitudeReferenceUnknown LlaAltitudeReference = "ALTITUDE_REFERENCE_UNKNOWN" - LlaAltitudeReferenceAltitudeReferenceBarometric LlaAltitudeReference = "ALTITUDE_REFERENCE_BAROMETRIC" - LlaAltitudeReferenceAltitudeReferenceAboveSeaFloor LlaAltitudeReference = "ALTITUDE_REFERENCE_ABOVE_SEA_FLOOR" - LlaAltitudeReferenceAltitudeReferenceBelowSeaSurface LlaAltitudeReference = "ALTITUDE_REFERENCE_BELOW_SEA_SURFACE" -) - -func NewLlaAltitudeReferenceFromString(s string) (LlaAltitudeReference, error) { - switch s { - case "ALTITUDE_REFERENCE_INVALID": - return LlaAltitudeReferenceAltitudeReferenceInvalid, nil - case "ALTITUDE_REFERENCE_HEIGHT_ABOVE_WGS84": - return LlaAltitudeReferenceAltitudeReferenceHeightAboveWgs84, nil - case "ALTITUDE_REFERENCE_HEIGHT_ABOVE_EGM96": - return LlaAltitudeReferenceAltitudeReferenceHeightAboveEgm96, nil - case "ALTITUDE_REFERENCE_UNKNOWN": - return LlaAltitudeReferenceAltitudeReferenceUnknown, nil - case "ALTITUDE_REFERENCE_BAROMETRIC": - return LlaAltitudeReferenceAltitudeReferenceBarometric, nil - case "ALTITUDE_REFERENCE_ABOVE_SEA_FLOOR": - return LlaAltitudeReferenceAltitudeReferenceAboveSeaFloor, nil - case "ALTITUDE_REFERENCE_BELOW_SEA_SURFACE": - return LlaAltitudeReferenceAltitudeReferenceBelowSeaSurface, nil - } - var t LlaAltitudeReference - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (l LlaAltitudeReference) Ptr() *LlaAltitudeReference { - return &l -} - -// Available for Entities that have a single or primary Location. -type Location struct { - // see Position definition for details. - Position *Position `json:"position,omitempty" url:"position,omitempty"` - // Velocity in an ENU reference frame centered on the corresponding position. All units are meters per second. - VelocityEnu *Enu `json:"velocityEnu,omitempty" url:"velocityEnu,omitempty"` - // Speed is the magnitude of velocity_enu vector [sqrt(e^2 + n^2 + u^2)] when present, measured in m/s. - SpeedMps *float64 `json:"speedMps,omitempty" url:"speedMps,omitempty"` - // The entity's acceleration in meters/s^2. - Acceleration *Enu `json:"acceleration,omitempty" url:"acceleration,omitempty"` - // quaternion to translate from entity body frame to it's ENU frame - AttitudeEnu *Quaternion `json:"attitudeEnu,omitempty" url:"attitudeEnu,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (l *Location) GetPosition() *Position { - if l == nil { - return nil - } - return l.Position -} - -func (l *Location) GetVelocityEnu() *Enu { - if l == nil { - return nil - } - return l.VelocityEnu -} - -func (l *Location) GetSpeedMps() *float64 { - if l == nil { - return nil - } - return l.SpeedMps -} - -func (l *Location) GetAcceleration() *Enu { - if l == nil { - return nil - } - return l.Acceleration -} - -func (l *Location) GetAttitudeEnu() *Quaternion { - if l == nil { - return nil - } - return l.AttitudeEnu -} - -func (l *Location) GetExtraProperties() map[string]interface{} { - return l.extraProperties -} - -func (l *Location) UnmarshalJSON(data []byte) error { - type unmarshaler Location - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *l = Location(value) - extraProperties, err := internal.ExtractExtraProperties(data, *l) - if err != nil { - return err - } - l.extraProperties = extraProperties - l.rawJSON = json.RawMessage(data) - return nil -} - -func (l *Location) String() string { - if len(l.rawJSON) > 0 { - if value, err := internal.StringifyJSON(l.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(l); err == nil { - return value - } - return fmt.Sprintf("%#v", l) -} - -// Uncertainty of entity position and velocity, if available. -type LocationUncertainty struct { - // Positional covariance represented by the upper triangle of the covariance matrix. It is valid to populate - // - // only the diagonal of the matrix if the full covariance matrix is unknown. - PositionEnuCov *TMat3 `json:"positionEnuCov,omitempty" url:"positionEnuCov,omitempty"` - // Velocity covariance represented by the upper triangle of the covariance matrix. It is valid to populate - // - // only the diagonal of the matrix if the full covariance matrix is unknown. - VelocityEnuCov *TMat3 `json:"velocityEnuCov,omitempty" url:"velocityEnuCov,omitempty"` - // An ellipse that describes the certainty probability and error boundary for a given geolocation. - PositionErrorEllipse *ErrorEllipse `json:"positionErrorEllipse,omitempty" url:"positionErrorEllipse,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (l *LocationUncertainty) GetPositionEnuCov() *TMat3 { - if l == nil { - return nil - } - return l.PositionEnuCov -} - -func (l *LocationUncertainty) GetVelocityEnuCov() *TMat3 { - if l == nil { - return nil - } - return l.VelocityEnuCov -} - -func (l *LocationUncertainty) GetPositionErrorEllipse() *ErrorEllipse { - if l == nil { - return nil - } - return l.PositionErrorEllipse -} - -func (l *LocationUncertainty) GetExtraProperties() map[string]interface{} { - return l.extraProperties -} - -func (l *LocationUncertainty) UnmarshalJSON(data []byte) error { - type unmarshaler LocationUncertainty - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *l = LocationUncertainty(value) - extraProperties, err := internal.ExtractExtraProperties(data, *l) - if err != nil { - return err - } - l.extraProperties = extraProperties - l.rawJSON = json.RawMessage(data) - return nil -} - -func (l *LocationUncertainty) String() string { - if len(l.rawJSON) > 0 { - if value, err := internal.StringifyJSON(l.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(l); err == nil { - return value - } - return fmt.Sprintf("%#v", l) -} - -type MeanKeplerianElements struct { - // UTC time of validity - Epoch *time.Time `json:"epoch,omitempty" url:"epoch,omitempty"` - // Preferred: semi major axis in kilometers - SemiMajorAxisKm *float64 `json:"semiMajorAxisKm,omitempty" url:"semiMajorAxisKm,omitempty"` - // If using SGP/SGP4, provide the Keplerian Mean Motion in revolutions per day - MeanMotion *float64 `json:"meanMotion,omitempty" url:"meanMotion,omitempty"` - Eccentricity *float64 `json:"eccentricity,omitempty" url:"eccentricity,omitempty"` - // Angle of inclination in deg - InclinationDeg *float64 `json:"inclinationDeg,omitempty" url:"inclinationDeg,omitempty"` - // Right ascension of the ascending node in deg - RaOfAscNodeDeg *float64 `json:"raOfAscNodeDeg,omitempty" url:"raOfAscNodeDeg,omitempty"` - // Argument of pericenter in deg - ArgOfPericenterDeg *float64 `json:"argOfPericenterDeg,omitempty" url:"argOfPericenterDeg,omitempty"` - // Mean anomaly in deg - MeanAnomalyDeg *float64 `json:"meanAnomalyDeg,omitempty" url:"meanAnomalyDeg,omitempty"` - // Optional: gravitational coefficient (Gravitational Constant x central mass) in kg^3 / s^2 - Gm *float64 `json:"gm,omitempty" url:"gm,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *MeanKeplerianElements) GetEpoch() *time.Time { - if m == nil { - return nil - } - return m.Epoch -} - -func (m *MeanKeplerianElements) GetSemiMajorAxisKm() *float64 { - if m == nil { - return nil - } - return m.SemiMajorAxisKm -} - -func (m *MeanKeplerianElements) GetMeanMotion() *float64 { - if m == nil { - return nil - } - return m.MeanMotion -} - -func (m *MeanKeplerianElements) GetEccentricity() *float64 { - if m == nil { - return nil - } - return m.Eccentricity -} - -func (m *MeanKeplerianElements) GetInclinationDeg() *float64 { - if m == nil { - return nil - } - return m.InclinationDeg -} - -func (m *MeanKeplerianElements) GetRaOfAscNodeDeg() *float64 { - if m == nil { - return nil - } - return m.RaOfAscNodeDeg -} - -func (m *MeanKeplerianElements) GetArgOfPericenterDeg() *float64 { - if m == nil { - return nil - } - return m.ArgOfPericenterDeg -} - -func (m *MeanKeplerianElements) GetMeanAnomalyDeg() *float64 { - if m == nil { - return nil - } - return m.MeanAnomalyDeg -} - -func (m *MeanKeplerianElements) GetGm() *float64 { - if m == nil { - return nil - } - return m.Gm -} - -func (m *MeanKeplerianElements) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *MeanKeplerianElements) UnmarshalJSON(data []byte) error { - type embed MeanKeplerianElements - var unmarshaler = struct { - embed - Epoch *internal.DateTime `json:"epoch,omitempty"` - }{ - embed: embed(*m), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *m = MeanKeplerianElements(unmarshaler.embed) - m.Epoch = unmarshaler.Epoch.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *MeanKeplerianElements) MarshalJSON() ([]byte, error) { - type embed MeanKeplerianElements - var marshaler = struct { - embed - Epoch *internal.DateTime `json:"epoch,omitempty"` - }{ - embed: embed(*m), - Epoch: internal.NewOptionalDateTime(m.Epoch), - } - return json.Marshal(marshaler) -} - -func (m *MeanKeplerianElements) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -// A component that describes some measured value with error. -type Measurement struct { - // The value of the measurement. - Value *float64 `json:"value,omitempty" url:"value,omitempty"` - // Estimated one standard deviation in same unit as the value. - Sigma *float64 `json:"sigma,omitempty" url:"sigma,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *Measurement) GetValue() *float64 { - if m == nil { - return nil - } - return m.Value -} - -func (m *Measurement) GetSigma() *float64 { - if m == nil { - return nil - } - return m.Sigma -} - -func (m *Measurement) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *Measurement) UnmarshalJSON(data []byte) error { - type unmarshaler Measurement - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = Measurement(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *Measurement) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -// Media associated with an entity. -type Media struct { - Media []*MediaItem `json:"media,omitempty" url:"media,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *Media) GetMedia() []*MediaItem { - if m == nil { - return nil - } - return m.Media -} - -func (m *Media) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *Media) UnmarshalJSON(data []byte) error { - type unmarshaler Media - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = Media(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *Media) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -type MediaItem struct { - Type *MediaItemType `json:"type,omitempty" url:"type,omitempty"` - // The path, relative to the environment base URL, where media related to an entity can be accessed - RelativePath *string `json:"relativePath,omitempty" url:"relativePath,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *MediaItem) GetType() *MediaItemType { - if m == nil { - return nil - } - return m.Type -} - -func (m *MediaItem) GetRelativePath() *string { - if m == nil { - return nil - } - return m.RelativePath -} - -func (m *MediaItem) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *MediaItem) UnmarshalJSON(data []byte) error { - type unmarshaler MediaItem - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = MediaItem(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *MediaItem) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -type MediaItemType string - -const ( - MediaItemTypeMediaTypeInvalid MediaItemType = "MEDIA_TYPE_INVALID" - MediaItemTypeMediaTypeImage MediaItemType = "MEDIA_TYPE_IMAGE" - MediaItemTypeMediaTypeVideo MediaItemType = "MEDIA_TYPE_VIDEO" -) - -func NewMediaItemTypeFromString(s string) (MediaItemType, error) { - switch s { - case "MEDIA_TYPE_INVALID": - return MediaItemTypeMediaTypeInvalid, nil - case "MEDIA_TYPE_IMAGE": - return MediaItemTypeMediaTypeImage, nil - case "MEDIA_TYPE_VIDEO": - return MediaItemTypeMediaTypeVideo, nil - } - var t MediaItemType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (m MediaItemType) Ptr() *MediaItemType { - return &m -} - -// A MergedFrom relationship is a uni-directional relationship indicating that this entity is a merged entity whose -// -// data has at least partially been merged from the related entity. -type MergedFrom struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *MergedFrom) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *MergedFrom) UnmarshalJSON(data []byte) error { - type unmarshaler MergedFrom - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = MergedFrom(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *MergedFrom) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -// Provides the disposition, environment, and nationality of an Entity. -type MilView struct { - Disposition *MilViewDisposition `json:"disposition,omitempty" url:"disposition,omitempty"` - Environment *MilViewEnvironment `json:"environment,omitempty" url:"environment,omitempty"` - Nationality *MilViewNationality `json:"nationality,omitempty" url:"nationality,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *MilView) GetDisposition() *MilViewDisposition { - if m == nil { - return nil - } - return m.Disposition -} - -func (m *MilView) GetEnvironment() *MilViewEnvironment { - if m == nil { - return nil - } - return m.Environment -} - -func (m *MilView) GetNationality() *MilViewNationality { - if m == nil { - return nil - } - return m.Nationality -} - -func (m *MilView) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *MilView) UnmarshalJSON(data []byte) error { - type unmarshaler MilView - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = MilView(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *MilView) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -type MilViewDisposition string - -const ( - MilViewDispositionDispositionUnknown MilViewDisposition = "DISPOSITION_UNKNOWN" - MilViewDispositionDispositionFriendly MilViewDisposition = "DISPOSITION_FRIENDLY" - MilViewDispositionDispositionHostile MilViewDisposition = "DISPOSITION_HOSTILE" - MilViewDispositionDispositionSuspicious MilViewDisposition = "DISPOSITION_SUSPICIOUS" - MilViewDispositionDispositionAssumedFriendly MilViewDisposition = "DISPOSITION_ASSUMED_FRIENDLY" - MilViewDispositionDispositionNeutral MilViewDisposition = "DISPOSITION_NEUTRAL" - MilViewDispositionDispositionPending MilViewDisposition = "DISPOSITION_PENDING" -) - -func NewMilViewDispositionFromString(s string) (MilViewDisposition, error) { - switch s { - case "DISPOSITION_UNKNOWN": - return MilViewDispositionDispositionUnknown, nil - case "DISPOSITION_FRIENDLY": - return MilViewDispositionDispositionFriendly, nil - case "DISPOSITION_HOSTILE": - return MilViewDispositionDispositionHostile, nil - case "DISPOSITION_SUSPICIOUS": - return MilViewDispositionDispositionSuspicious, nil - case "DISPOSITION_ASSUMED_FRIENDLY": - return MilViewDispositionDispositionAssumedFriendly, nil - case "DISPOSITION_NEUTRAL": - return MilViewDispositionDispositionNeutral, nil - case "DISPOSITION_PENDING": - return MilViewDispositionDispositionPending, nil - } - var t MilViewDisposition - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (m MilViewDisposition) Ptr() *MilViewDisposition { - return &m -} - -type MilViewEnvironment string - -const ( - MilViewEnvironmentEnvironmentUnknown MilViewEnvironment = "ENVIRONMENT_UNKNOWN" - MilViewEnvironmentEnvironmentAir MilViewEnvironment = "ENVIRONMENT_AIR" - MilViewEnvironmentEnvironmentSurface MilViewEnvironment = "ENVIRONMENT_SURFACE" - MilViewEnvironmentEnvironmentSubSurface MilViewEnvironment = "ENVIRONMENT_SUB_SURFACE" - MilViewEnvironmentEnvironmentLand MilViewEnvironment = "ENVIRONMENT_LAND" - MilViewEnvironmentEnvironmentSpace MilViewEnvironment = "ENVIRONMENT_SPACE" -) - -func NewMilViewEnvironmentFromString(s string) (MilViewEnvironment, error) { - switch s { - case "ENVIRONMENT_UNKNOWN": - return MilViewEnvironmentEnvironmentUnknown, nil - case "ENVIRONMENT_AIR": - return MilViewEnvironmentEnvironmentAir, nil - case "ENVIRONMENT_SURFACE": - return MilViewEnvironmentEnvironmentSurface, nil - case "ENVIRONMENT_SUB_SURFACE": - return MilViewEnvironmentEnvironmentSubSurface, nil - case "ENVIRONMENT_LAND": - return MilViewEnvironmentEnvironmentLand, nil - case "ENVIRONMENT_SPACE": - return MilViewEnvironmentEnvironmentSpace, nil - } - var t MilViewEnvironment - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (m MilViewEnvironment) Ptr() *MilViewEnvironment { - return &m -} - -type MilViewNationality string - -const ( - MilViewNationalityNationalityInvalid MilViewNationality = "NATIONALITY_INVALID" - MilViewNationalityNationalityAlbania MilViewNationality = "NATIONALITY_ALBANIA" - MilViewNationalityNationalityAlgeria MilViewNationality = "NATIONALITY_ALGERIA" - MilViewNationalityNationalityArgentina MilViewNationality = "NATIONALITY_ARGENTINA" - MilViewNationalityNationalityArmenia MilViewNationality = "NATIONALITY_ARMENIA" - MilViewNationalityNationalityAustralia MilViewNationality = "NATIONALITY_AUSTRALIA" - MilViewNationalityNationalityAustria MilViewNationality = "NATIONALITY_AUSTRIA" - MilViewNationalityNationalityAzerbaijan MilViewNationality = "NATIONALITY_AZERBAIJAN" - MilViewNationalityNationalityBelarus MilViewNationality = "NATIONALITY_BELARUS" - MilViewNationalityNationalityBelgium MilViewNationality = "NATIONALITY_BELGIUM" - MilViewNationalityNationalityBolivia MilViewNationality = "NATIONALITY_BOLIVIA" - MilViewNationalityNationalityBosniaAndHerzegovina MilViewNationality = "NATIONALITY_BOSNIA_AND_HERZEGOVINA" - MilViewNationalityNationalityBrazil MilViewNationality = "NATIONALITY_BRAZIL" - MilViewNationalityNationalityBulgaria MilViewNationality = "NATIONALITY_BULGARIA" - MilViewNationalityNationalityCambodia MilViewNationality = "NATIONALITY_CAMBODIA" - MilViewNationalityNationalityCanada MilViewNationality = "NATIONALITY_CANADA" - MilViewNationalityNationalityChile MilViewNationality = "NATIONALITY_CHILE" - MilViewNationalityNationalityChina MilViewNationality = "NATIONALITY_CHINA" - MilViewNationalityNationalityColombia MilViewNationality = "NATIONALITY_COLOMBIA" - MilViewNationalityNationalityCroatia MilViewNationality = "NATIONALITY_CROATIA" - MilViewNationalityNationalityCuba MilViewNationality = "NATIONALITY_CUBA" - MilViewNationalityNationalityCyprus MilViewNationality = "NATIONALITY_CYPRUS" - MilViewNationalityNationalityCzechRepublic MilViewNationality = "NATIONALITY_CZECH_REPUBLIC" - MilViewNationalityNationalityDemocraticPeoplesRepublicOfKorea MilViewNationality = "NATIONALITY_DEMOCRATIC_PEOPLES_REPUBLIC_OF_KOREA" - MilViewNationalityNationalityDenmark MilViewNationality = "NATIONALITY_DENMARK" - MilViewNationalityNationalityDominicanRepublic MilViewNationality = "NATIONALITY_DOMINICAN_REPUBLIC" - MilViewNationalityNationalityEcuador MilViewNationality = "NATIONALITY_ECUADOR" - MilViewNationalityNationalityEgypt MilViewNationality = "NATIONALITY_EGYPT" - MilViewNationalityNationalityEstonia MilViewNationality = "NATIONALITY_ESTONIA" - MilViewNationalityNationalityEthiopia MilViewNationality = "NATIONALITY_ETHIOPIA" - MilViewNationalityNationalityFinland MilViewNationality = "NATIONALITY_FINLAND" - MilViewNationalityNationalityFrance MilViewNationality = "NATIONALITY_FRANCE" - MilViewNationalityNationalityGeorgia MilViewNationality = "NATIONALITY_GEORGIA" - MilViewNationalityNationalityGermany MilViewNationality = "NATIONALITY_GERMANY" - MilViewNationalityNationalityGreece MilViewNationality = "NATIONALITY_GREECE" - MilViewNationalityNationalityGuatemala MilViewNationality = "NATIONALITY_GUATEMALA" - MilViewNationalityNationalityGuinea MilViewNationality = "NATIONALITY_GUINEA" - MilViewNationalityNationalityHungary MilViewNationality = "NATIONALITY_HUNGARY" - MilViewNationalityNationalityIceland MilViewNationality = "NATIONALITY_ICELAND" - MilViewNationalityNationalityIndia MilViewNationality = "NATIONALITY_INDIA" - MilViewNationalityNationalityIndonesia MilViewNationality = "NATIONALITY_INDONESIA" - MilViewNationalityNationalityInternationalRedCross MilViewNationality = "NATIONALITY_INTERNATIONAL_RED_CROSS" - MilViewNationalityNationalityIraq MilViewNationality = "NATIONALITY_IRAQ" - MilViewNationalityNationalityIreland MilViewNationality = "NATIONALITY_IRELAND" - MilViewNationalityNationalityIslamicRepublicOfIran MilViewNationality = "NATIONALITY_ISLAMIC_REPUBLIC_OF_IRAN" - MilViewNationalityNationalityIsrael MilViewNationality = "NATIONALITY_ISRAEL" - MilViewNationalityNationalityItaly MilViewNationality = "NATIONALITY_ITALY" - MilViewNationalityNationalityJamaica MilViewNationality = "NATIONALITY_JAMAICA" - MilViewNationalityNationalityJapan MilViewNationality = "NATIONALITY_JAPAN" - MilViewNationalityNationalityJordan MilViewNationality = "NATIONALITY_JORDAN" - MilViewNationalityNationalityKazakhstan MilViewNationality = "NATIONALITY_KAZAKHSTAN" - MilViewNationalityNationalityKuwait MilViewNationality = "NATIONALITY_KUWAIT" - MilViewNationalityNationalityKyrghyzRepublic MilViewNationality = "NATIONALITY_KYRGHYZ_REPUBLIC" - MilViewNationalityNationalityLaoPeoplesDemocraticRepublic MilViewNationality = "NATIONALITY_LAO_PEOPLES_DEMOCRATIC_REPUBLIC" - MilViewNationalityNationalityLatvia MilViewNationality = "NATIONALITY_LATVIA" - MilViewNationalityNationalityLebanon MilViewNationality = "NATIONALITY_LEBANON" - MilViewNationalityNationalityLiberia MilViewNationality = "NATIONALITY_LIBERIA" - MilViewNationalityNationalityLithuania MilViewNationality = "NATIONALITY_LITHUANIA" - MilViewNationalityNationalityLuxembourg MilViewNationality = "NATIONALITY_LUXEMBOURG" - MilViewNationalityNationalityMadagascar MilViewNationality = "NATIONALITY_MADAGASCAR" - MilViewNationalityNationalityMalaysia MilViewNationality = "NATIONALITY_MALAYSIA" - MilViewNationalityNationalityMalta MilViewNationality = "NATIONALITY_MALTA" - MilViewNationalityNationalityMexico MilViewNationality = "NATIONALITY_MEXICO" - MilViewNationalityNationalityMoldova MilViewNationality = "NATIONALITY_MOLDOVA" - MilViewNationalityNationalityMontenegro MilViewNationality = "NATIONALITY_MONTENEGRO" - MilViewNationalityNationalityMorocco MilViewNationality = "NATIONALITY_MOROCCO" - MilViewNationalityNationalityMyanmar MilViewNationality = "NATIONALITY_MYANMAR" - MilViewNationalityNationalityNato MilViewNationality = "NATIONALITY_NATO" - MilViewNationalityNationalityNetherlands MilViewNationality = "NATIONALITY_NETHERLANDS" - MilViewNationalityNationalityNewZealand MilViewNationality = "NATIONALITY_NEW_ZEALAND" - MilViewNationalityNationalityNicaragua MilViewNationality = "NATIONALITY_NICARAGUA" - MilViewNationalityNationalityNigeria MilViewNationality = "NATIONALITY_NIGERIA" - MilViewNationalityNationalityNorway MilViewNationality = "NATIONALITY_NORWAY" - MilViewNationalityNationalityPakistan MilViewNationality = "NATIONALITY_PAKISTAN" - MilViewNationalityNationalityPanama MilViewNationality = "NATIONALITY_PANAMA" - MilViewNationalityNationalityParaguay MilViewNationality = "NATIONALITY_PARAGUAY" - MilViewNationalityNationalityPeru MilViewNationality = "NATIONALITY_PERU" - MilViewNationalityNationalityPhilippines MilViewNationality = "NATIONALITY_PHILIPPINES" - MilViewNationalityNationalityPoland MilViewNationality = "NATIONALITY_POLAND" - MilViewNationalityNationalityPortugal MilViewNationality = "NATIONALITY_PORTUGAL" - MilViewNationalityNationalityRepublicOfKorea MilViewNationality = "NATIONALITY_REPUBLIC_OF_KOREA" - MilViewNationalityNationalityRomania MilViewNationality = "NATIONALITY_ROMANIA" - MilViewNationalityNationalityRussia MilViewNationality = "NATIONALITY_RUSSIA" - MilViewNationalityNationalitySaudiArabia MilViewNationality = "NATIONALITY_SAUDI_ARABIA" - MilViewNationalityNationalitySenegal MilViewNationality = "NATIONALITY_SENEGAL" - MilViewNationalityNationalitySerbia MilViewNationality = "NATIONALITY_SERBIA" - MilViewNationalityNationalitySingapore MilViewNationality = "NATIONALITY_SINGAPORE" - MilViewNationalityNationalitySlovakia MilViewNationality = "NATIONALITY_SLOVAKIA" - MilViewNationalityNationalitySlovenia MilViewNationality = "NATIONALITY_SLOVENIA" - MilViewNationalityNationalitySouthAfrica MilViewNationality = "NATIONALITY_SOUTH_AFRICA" - MilViewNationalityNationalitySpain MilViewNationality = "NATIONALITY_SPAIN" - MilViewNationalityNationalitySudan MilViewNationality = "NATIONALITY_SUDAN" - MilViewNationalityNationalitySweden MilViewNationality = "NATIONALITY_SWEDEN" - MilViewNationalityNationalitySwitzerland MilViewNationality = "NATIONALITY_SWITZERLAND" - MilViewNationalityNationalitySyrianArabRepublic MilViewNationality = "NATIONALITY_SYRIAN_ARAB_REPUBLIC" - MilViewNationalityNationalityTaiwan MilViewNationality = "NATIONALITY_TAIWAN" - MilViewNationalityNationalityTajikistan MilViewNationality = "NATIONALITY_TAJIKISTAN" - MilViewNationalityNationalityThailand MilViewNationality = "NATIONALITY_THAILAND" - MilViewNationalityNationalityTheFormerYugoslavRepublicOfMacedonia MilViewNationality = "NATIONALITY_THE_FORMER_YUGOSLAV_REPUBLIC_OF_MACEDONIA" - MilViewNationalityNationalityTunisia MilViewNationality = "NATIONALITY_TUNISIA" - MilViewNationalityNationalityTurkey MilViewNationality = "NATIONALITY_TURKEY" - MilViewNationalityNationalityTurkmenistan MilViewNationality = "NATIONALITY_TURKMENISTAN" - MilViewNationalityNationalityUganda MilViewNationality = "NATIONALITY_UGANDA" - MilViewNationalityNationalityUkraine MilViewNationality = "NATIONALITY_UKRAINE" - MilViewNationalityNationalityUnitedKingdom MilViewNationality = "NATIONALITY_UNITED_KINGDOM" - MilViewNationalityNationalityUnitedNations MilViewNationality = "NATIONALITY_UNITED_NATIONS" - MilViewNationalityNationalityUnitedRepublicOfTanzania MilViewNationality = "NATIONALITY_UNITED_REPUBLIC_OF_TANZANIA" - MilViewNationalityNationalityUnitedStatesOfAmerica MilViewNationality = "NATIONALITY_UNITED_STATES_OF_AMERICA" - MilViewNationalityNationalityUruguay MilViewNationality = "NATIONALITY_URUGUAY" - MilViewNationalityNationalityUzbekistan MilViewNationality = "NATIONALITY_UZBEKISTAN" - MilViewNationalityNationalityVenezuela MilViewNationality = "NATIONALITY_VENEZUELA" - MilViewNationalityNationalityVietnam MilViewNationality = "NATIONALITY_VIETNAM" - MilViewNationalityNationalityYemen MilViewNationality = "NATIONALITY_YEMEN" - MilViewNationalityNationalityZimbabwe MilViewNationality = "NATIONALITY_ZIMBABWE" -) - -func NewMilViewNationalityFromString(s string) (MilViewNationality, error) { - switch s { - case "NATIONALITY_INVALID": - return MilViewNationalityNationalityInvalid, nil - case "NATIONALITY_ALBANIA": - return MilViewNationalityNationalityAlbania, nil - case "NATIONALITY_ALGERIA": - return MilViewNationalityNationalityAlgeria, nil - case "NATIONALITY_ARGENTINA": - return MilViewNationalityNationalityArgentina, nil - case "NATIONALITY_ARMENIA": - return MilViewNationalityNationalityArmenia, nil - case "NATIONALITY_AUSTRALIA": - return MilViewNationalityNationalityAustralia, nil - case "NATIONALITY_AUSTRIA": - return MilViewNationalityNationalityAustria, nil - case "NATIONALITY_AZERBAIJAN": - return MilViewNationalityNationalityAzerbaijan, nil - case "NATIONALITY_BELARUS": - return MilViewNationalityNationalityBelarus, nil - case "NATIONALITY_BELGIUM": - return MilViewNationalityNationalityBelgium, nil - case "NATIONALITY_BOLIVIA": - return MilViewNationalityNationalityBolivia, nil - case "NATIONALITY_BOSNIA_AND_HERZEGOVINA": - return MilViewNationalityNationalityBosniaAndHerzegovina, nil - case "NATIONALITY_BRAZIL": - return MilViewNationalityNationalityBrazil, nil - case "NATIONALITY_BULGARIA": - return MilViewNationalityNationalityBulgaria, nil - case "NATIONALITY_CAMBODIA": - return MilViewNationalityNationalityCambodia, nil - case "NATIONALITY_CANADA": - return MilViewNationalityNationalityCanada, nil - case "NATIONALITY_CHILE": - return MilViewNationalityNationalityChile, nil - case "NATIONALITY_CHINA": - return MilViewNationalityNationalityChina, nil - case "NATIONALITY_COLOMBIA": - return MilViewNationalityNationalityColombia, nil - case "NATIONALITY_CROATIA": - return MilViewNationalityNationalityCroatia, nil - case "NATIONALITY_CUBA": - return MilViewNationalityNationalityCuba, nil - case "NATIONALITY_CYPRUS": - return MilViewNationalityNationalityCyprus, nil - case "NATIONALITY_CZECH_REPUBLIC": - return MilViewNationalityNationalityCzechRepublic, nil - case "NATIONALITY_DEMOCRATIC_PEOPLES_REPUBLIC_OF_KOREA": - return MilViewNationalityNationalityDemocraticPeoplesRepublicOfKorea, nil - case "NATIONALITY_DENMARK": - return MilViewNationalityNationalityDenmark, nil - case "NATIONALITY_DOMINICAN_REPUBLIC": - return MilViewNationalityNationalityDominicanRepublic, nil - case "NATIONALITY_ECUADOR": - return MilViewNationalityNationalityEcuador, nil - case "NATIONALITY_EGYPT": - return MilViewNationalityNationalityEgypt, nil - case "NATIONALITY_ESTONIA": - return MilViewNationalityNationalityEstonia, nil - case "NATIONALITY_ETHIOPIA": - return MilViewNationalityNationalityEthiopia, nil - case "NATIONALITY_FINLAND": - return MilViewNationalityNationalityFinland, nil - case "NATIONALITY_FRANCE": - return MilViewNationalityNationalityFrance, nil - case "NATIONALITY_GEORGIA": - return MilViewNationalityNationalityGeorgia, nil - case "NATIONALITY_GERMANY": - return MilViewNationalityNationalityGermany, nil - case "NATIONALITY_GREECE": - return MilViewNationalityNationalityGreece, nil - case "NATIONALITY_GUATEMALA": - return MilViewNationalityNationalityGuatemala, nil - case "NATIONALITY_GUINEA": - return MilViewNationalityNationalityGuinea, nil - case "NATIONALITY_HUNGARY": - return MilViewNationalityNationalityHungary, nil - case "NATIONALITY_ICELAND": - return MilViewNationalityNationalityIceland, nil - case "NATIONALITY_INDIA": - return MilViewNationalityNationalityIndia, nil - case "NATIONALITY_INDONESIA": - return MilViewNationalityNationalityIndonesia, nil - case "NATIONALITY_INTERNATIONAL_RED_CROSS": - return MilViewNationalityNationalityInternationalRedCross, nil - case "NATIONALITY_IRAQ": - return MilViewNationalityNationalityIraq, nil - case "NATIONALITY_IRELAND": - return MilViewNationalityNationalityIreland, nil - case "NATIONALITY_ISLAMIC_REPUBLIC_OF_IRAN": - return MilViewNationalityNationalityIslamicRepublicOfIran, nil - case "NATIONALITY_ISRAEL": - return MilViewNationalityNationalityIsrael, nil - case "NATIONALITY_ITALY": - return MilViewNationalityNationalityItaly, nil - case "NATIONALITY_JAMAICA": - return MilViewNationalityNationalityJamaica, nil - case "NATIONALITY_JAPAN": - return MilViewNationalityNationalityJapan, nil - case "NATIONALITY_JORDAN": - return MilViewNationalityNationalityJordan, nil - case "NATIONALITY_KAZAKHSTAN": - return MilViewNationalityNationalityKazakhstan, nil - case "NATIONALITY_KUWAIT": - return MilViewNationalityNationalityKuwait, nil - case "NATIONALITY_KYRGHYZ_REPUBLIC": - return MilViewNationalityNationalityKyrghyzRepublic, nil - case "NATIONALITY_LAO_PEOPLES_DEMOCRATIC_REPUBLIC": - return MilViewNationalityNationalityLaoPeoplesDemocraticRepublic, nil - case "NATIONALITY_LATVIA": - return MilViewNationalityNationalityLatvia, nil - case "NATIONALITY_LEBANON": - return MilViewNationalityNationalityLebanon, nil - case "NATIONALITY_LIBERIA": - return MilViewNationalityNationalityLiberia, nil - case "NATIONALITY_LITHUANIA": - return MilViewNationalityNationalityLithuania, nil - case "NATIONALITY_LUXEMBOURG": - return MilViewNationalityNationalityLuxembourg, nil - case "NATIONALITY_MADAGASCAR": - return MilViewNationalityNationalityMadagascar, nil - case "NATIONALITY_MALAYSIA": - return MilViewNationalityNationalityMalaysia, nil - case "NATIONALITY_MALTA": - return MilViewNationalityNationalityMalta, nil - case "NATIONALITY_MEXICO": - return MilViewNationalityNationalityMexico, nil - case "NATIONALITY_MOLDOVA": - return MilViewNationalityNationalityMoldova, nil - case "NATIONALITY_MONTENEGRO": - return MilViewNationalityNationalityMontenegro, nil - case "NATIONALITY_MOROCCO": - return MilViewNationalityNationalityMorocco, nil - case "NATIONALITY_MYANMAR": - return MilViewNationalityNationalityMyanmar, nil - case "NATIONALITY_NATO": - return MilViewNationalityNationalityNato, nil - case "NATIONALITY_NETHERLANDS": - return MilViewNationalityNationalityNetherlands, nil - case "NATIONALITY_NEW_ZEALAND": - return MilViewNationalityNationalityNewZealand, nil - case "NATIONALITY_NICARAGUA": - return MilViewNationalityNationalityNicaragua, nil - case "NATIONALITY_NIGERIA": - return MilViewNationalityNationalityNigeria, nil - case "NATIONALITY_NORWAY": - return MilViewNationalityNationalityNorway, nil - case "NATIONALITY_PAKISTAN": - return MilViewNationalityNationalityPakistan, nil - case "NATIONALITY_PANAMA": - return MilViewNationalityNationalityPanama, nil - case "NATIONALITY_PARAGUAY": - return MilViewNationalityNationalityParaguay, nil - case "NATIONALITY_PERU": - return MilViewNationalityNationalityPeru, nil - case "NATIONALITY_PHILIPPINES": - return MilViewNationalityNationalityPhilippines, nil - case "NATIONALITY_POLAND": - return MilViewNationalityNationalityPoland, nil - case "NATIONALITY_PORTUGAL": - return MilViewNationalityNationalityPortugal, nil - case "NATIONALITY_REPUBLIC_OF_KOREA": - return MilViewNationalityNationalityRepublicOfKorea, nil - case "NATIONALITY_ROMANIA": - return MilViewNationalityNationalityRomania, nil - case "NATIONALITY_RUSSIA": - return MilViewNationalityNationalityRussia, nil - case "NATIONALITY_SAUDI_ARABIA": - return MilViewNationalityNationalitySaudiArabia, nil - case "NATIONALITY_SENEGAL": - return MilViewNationalityNationalitySenegal, nil - case "NATIONALITY_SERBIA": - return MilViewNationalityNationalitySerbia, nil - case "NATIONALITY_SINGAPORE": - return MilViewNationalityNationalitySingapore, nil - case "NATIONALITY_SLOVAKIA": - return MilViewNationalityNationalitySlovakia, nil - case "NATIONALITY_SLOVENIA": - return MilViewNationalityNationalitySlovenia, nil - case "NATIONALITY_SOUTH_AFRICA": - return MilViewNationalityNationalitySouthAfrica, nil - case "NATIONALITY_SPAIN": - return MilViewNationalityNationalitySpain, nil - case "NATIONALITY_SUDAN": - return MilViewNationalityNationalitySudan, nil - case "NATIONALITY_SWEDEN": - return MilViewNationalityNationalitySweden, nil - case "NATIONALITY_SWITZERLAND": - return MilViewNationalityNationalitySwitzerland, nil - case "NATIONALITY_SYRIAN_ARAB_REPUBLIC": - return MilViewNationalityNationalitySyrianArabRepublic, nil - case "NATIONALITY_TAIWAN": - return MilViewNationalityNationalityTaiwan, nil - case "NATIONALITY_TAJIKISTAN": - return MilViewNationalityNationalityTajikistan, nil - case "NATIONALITY_THAILAND": - return MilViewNationalityNationalityThailand, nil - case "NATIONALITY_THE_FORMER_YUGOSLAV_REPUBLIC_OF_MACEDONIA": - return MilViewNationalityNationalityTheFormerYugoslavRepublicOfMacedonia, nil - case "NATIONALITY_TUNISIA": - return MilViewNationalityNationalityTunisia, nil - case "NATIONALITY_TURKEY": - return MilViewNationalityNationalityTurkey, nil - case "NATIONALITY_TURKMENISTAN": - return MilViewNationalityNationalityTurkmenistan, nil - case "NATIONALITY_UGANDA": - return MilViewNationalityNationalityUganda, nil - case "NATIONALITY_UKRAINE": - return MilViewNationalityNationalityUkraine, nil - case "NATIONALITY_UNITED_KINGDOM": - return MilViewNationalityNationalityUnitedKingdom, nil - case "NATIONALITY_UNITED_NATIONS": - return MilViewNationalityNationalityUnitedNations, nil - case "NATIONALITY_UNITED_REPUBLIC_OF_TANZANIA": - return MilViewNationalityNationalityUnitedRepublicOfTanzania, nil - case "NATIONALITY_UNITED_STATES_OF_AMERICA": - return MilViewNationalityNationalityUnitedStatesOfAmerica, nil - case "NATIONALITY_URUGUAY": - return MilViewNationalityNationalityUruguay, nil - case "NATIONALITY_UZBEKISTAN": - return MilViewNationalityNationalityUzbekistan, nil - case "NATIONALITY_VENEZUELA": - return MilViewNationalityNationalityVenezuela, nil - case "NATIONALITY_VIETNAM": - return MilViewNationalityNationalityVietnam, nil - case "NATIONALITY_YEMEN": - return MilViewNationalityNationalityYemen, nil - case "NATIONALITY_ZIMBABWE": - return MilViewNationalityNationalityZimbabwe, nil - } - var t MilViewNationality - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (m MilViewNationality) Ptr() *MilViewNationality { - return &m -} - -// Describes the Mode 5 transponder interrogation status and codes. -type Mode5 struct { - // The validity of the response from the Mode 5 interrogation. - Mode5InterrogationResponse *Mode5Mode5InterrogationResponse `json:"mode5InterrogationResponse,omitempty" url:"mode5InterrogationResponse,omitempty"` - // The Mode 5 code assigned to military assets. - Mode5 *int `json:"mode5,omitempty" url:"mode5,omitempty"` - // The Mode 5 platform identification code. - Mode5PlatformID *int `json:"mode5PlatformId,omitempty" url:"mode5PlatformId,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *Mode5) GetMode5InterrogationResponse() *Mode5Mode5InterrogationResponse { - if m == nil { - return nil - } - return m.Mode5InterrogationResponse -} - -func (m *Mode5) GetMode5() *int { - if m == nil { - return nil - } - return m.Mode5 -} - -func (m *Mode5) GetMode5PlatformID() *int { - if m == nil { - return nil - } - return m.Mode5PlatformID -} - -func (m *Mode5) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *Mode5) UnmarshalJSON(data []byte) error { - type unmarshaler Mode5 - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = Mode5(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *Mode5) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -// The validity of the response from the Mode 5 interrogation. -type Mode5Mode5InterrogationResponse string - -const ( - Mode5Mode5InterrogationResponseInterrogationResponseInvalid Mode5Mode5InterrogationResponse = "INTERROGATION_RESPONSE_INVALID" - Mode5Mode5InterrogationResponseInterrogationResponseCorrect Mode5Mode5InterrogationResponse = "INTERROGATION_RESPONSE_CORRECT" - Mode5Mode5InterrogationResponseInterrogationResponseIncorrect Mode5Mode5InterrogationResponse = "INTERROGATION_RESPONSE_INCORRECT" - Mode5Mode5InterrogationResponseInterrogationResponseNoResponse Mode5Mode5InterrogationResponse = "INTERROGATION_RESPONSE_NO_RESPONSE" -) - -func NewMode5Mode5InterrogationResponseFromString(s string) (Mode5Mode5InterrogationResponse, error) { - switch s { - case "INTERROGATION_RESPONSE_INVALID": - return Mode5Mode5InterrogationResponseInterrogationResponseInvalid, nil - case "INTERROGATION_RESPONSE_CORRECT": - return Mode5Mode5InterrogationResponseInterrogationResponseCorrect, nil - case "INTERROGATION_RESPONSE_INCORRECT": - return Mode5Mode5InterrogationResponseInterrogationResponseIncorrect, nil - case "INTERROGATION_RESPONSE_NO_RESPONSE": - return Mode5Mode5InterrogationResponseInterrogationResponseNoResponse, nil - } - var t Mode5Mode5InterrogationResponse - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (m Mode5Mode5InterrogationResponse) Ptr() *Mode5Mode5InterrogationResponse { - return &m -} - -// Describes the Mode S codes. -type ModeS struct { - // Mode S identifier which comprises of 8 alphanumeric characters. - ID *string `json:"id,omitempty" url:"id,omitempty"` - // The Mode S ICAO aircraft address. Expected values are between 1 and 16777214 decimal. The Mode S address is - // - // considered unique. - Address *int `json:"address,omitempty" url:"address,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (m *ModeS) GetID() *string { - if m == nil { - return nil - } - return m.ID -} - -func (m *ModeS) GetAddress() *int { - if m == nil { - return nil - } - return m.Address -} - -func (m *ModeS) GetExtraProperties() map[string]interface{} { - return m.extraProperties -} - -func (m *ModeS) UnmarshalJSON(data []byte) error { - type unmarshaler ModeS - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *m = ModeS(value) - extraProperties, err := internal.ExtractExtraProperties(data, *m) - if err != nil { - return err - } - m.extraProperties = extraProperties - m.rawJSON = json.RawMessage(data) - return nil -} - -func (m *ModeS) String() string { - if len(m.rawJSON) > 0 { - if value, err := internal.StringifyJSON(m.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(m); err == nil { - return value - } - return fmt.Sprintf("%#v", m) -} - -type NonPrimaryMembership struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (n *NonPrimaryMembership) GetExtraProperties() map[string]interface{} { - return n.extraProperties -} - -func (n *NonPrimaryMembership) UnmarshalJSON(data []byte) error { - type unmarshaler NonPrimaryMembership - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *n = NonPrimaryMembership(value) - extraProperties, err := internal.ExtractExtraProperties(data, *n) - if err != nil { - return err - } - n.extraProperties = extraProperties - n.rawJSON = json.RawMessage(data) - return nil -} - -func (n *NonPrimaryMembership) String() string { - if len(n.rawJSON) > 0 { - if value, err := internal.StringifyJSON(n.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(n); err == nil { - return value - } - return fmt.Sprintf("%#v", n) -} - -// Ontology of the entity. -type Ontology struct { - // A string that describes the entity's high-level type with natural language. - PlatformType *string `json:"platformType,omitempty" url:"platformType,omitempty"` - // A string that describes the entity's exact model or type. - SpecificType *string `json:"specificType,omitempty" url:"specificType,omitempty"` - // The template used when creating this entity. Specifies minimum required components. - Template *OntologyTemplate `json:"template,omitempty" url:"template,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *Ontology) GetPlatformType() *string { - if o == nil { - return nil - } - return o.PlatformType -} - -func (o *Ontology) GetSpecificType() *string { - if o == nil { - return nil - } - return o.SpecificType -} - -func (o *Ontology) GetTemplate() *OntologyTemplate { - if o == nil { - return nil - } - return o.Template -} - -func (o *Ontology) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *Ontology) UnmarshalJSON(data []byte) error { - type unmarshaler Ontology - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *o = Ontology(value) - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *Ontology) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -// The template used when creating this entity. Specifies minimum required components. -type OntologyTemplate string - -const ( - OntologyTemplateTemplateInvalid OntologyTemplate = "TEMPLATE_INVALID" - OntologyTemplateTemplateTrack OntologyTemplate = "TEMPLATE_TRACK" - OntologyTemplateTemplateSensorPointOfInterest OntologyTemplate = "TEMPLATE_SENSOR_POINT_OF_INTEREST" - OntologyTemplateTemplateAsset OntologyTemplate = "TEMPLATE_ASSET" - OntologyTemplateTemplateGeo OntologyTemplate = "TEMPLATE_GEO" - OntologyTemplateTemplateSignalOfInterest OntologyTemplate = "TEMPLATE_SIGNAL_OF_INTEREST" -) - -func NewOntologyTemplateFromString(s string) (OntologyTemplate, error) { - switch s { - case "TEMPLATE_INVALID": - return OntologyTemplateTemplateInvalid, nil - case "TEMPLATE_TRACK": - return OntologyTemplateTemplateTrack, nil - case "TEMPLATE_SENSOR_POINT_OF_INTEREST": - return OntologyTemplateTemplateSensorPointOfInterest, nil - case "TEMPLATE_ASSET": - return OntologyTemplateTemplateAsset, nil - case "TEMPLATE_GEO": - return OntologyTemplateTemplateGeo, nil - case "TEMPLATE_SIGNAL_OF_INTEREST": - return OntologyTemplateTemplateSignalOfInterest, nil - } - var t OntologyTemplate - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (o OntologyTemplate) Ptr() *OntologyTemplate { - return &o -} - -type Orbit struct { - // Orbit Mean Elements data, analogous to the Orbit Mean Elements Message in CCSDS 502.0-B-3 - OrbitMeanElements *OrbitMeanElements `json:"orbitMeanElements,omitempty" url:"orbitMeanElements,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *Orbit) GetOrbitMeanElements() *OrbitMeanElements { - if o == nil { - return nil - } - return o.OrbitMeanElements -} - -func (o *Orbit) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *Orbit) UnmarshalJSON(data []byte) error { - type unmarshaler Orbit - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *o = Orbit(value) - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *Orbit) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -// Orbit Mean Elements data, analogous to the Orbit Mean Elements Message in CCSDS 502.0-B-3 -type OrbitMeanElements struct { - Metadata *OrbitMeanElementsMetadata `json:"metadata,omitempty" url:"metadata,omitempty"` - MeanKeplerianElements *MeanKeplerianElements `json:"meanKeplerianElements,omitempty" url:"meanKeplerianElements,omitempty"` - TleParameters *TleParameters `json:"tleParameters,omitempty" url:"tleParameters,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *OrbitMeanElements) GetMetadata() *OrbitMeanElementsMetadata { - if o == nil { - return nil - } - return o.Metadata -} - -func (o *OrbitMeanElements) GetMeanKeplerianElements() *MeanKeplerianElements { - if o == nil { - return nil - } - return o.MeanKeplerianElements -} - -func (o *OrbitMeanElements) GetTleParameters() *TleParameters { - if o == nil { - return nil - } - return o.TleParameters -} - -func (o *OrbitMeanElements) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *OrbitMeanElements) UnmarshalJSON(data []byte) error { - type unmarshaler OrbitMeanElements - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *o = OrbitMeanElements(value) - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *OrbitMeanElements) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -type OrbitMeanElementsMetadata struct { - // Creation date/time in UTC - CreationDate *time.Time `json:"creationDate,omitempty" url:"creationDate,omitempty"` - // Creating agency or operator - Originator *string `json:"originator,omitempty" url:"originator,omitempty"` - // ID that uniquely identifies a message from a given originator. - MessageID *string `json:"messageId,omitempty" url:"messageId,omitempty"` - // Reference frame, assumed to be Earth-centered - RefFrame *OrbitMeanElementsMetadataRefFrame `json:"refFrame,omitempty" url:"refFrame,omitempty"` - // Reference frame epoch in UTC - mandatory only if not intrinsic to frame definition - RefFrameEpoch *time.Time `json:"refFrameEpoch,omitempty" url:"refFrameEpoch,omitempty"` - MeanElementTheory *OrbitMeanElementsMetadataMeanElementTheory `json:"meanElementTheory,omitempty" url:"meanElementTheory,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *OrbitMeanElementsMetadata) GetCreationDate() *time.Time { - if o == nil { - return nil - } - return o.CreationDate -} - -func (o *OrbitMeanElementsMetadata) GetOriginator() *string { - if o == nil { - return nil - } - return o.Originator -} - -func (o *OrbitMeanElementsMetadata) GetMessageID() *string { - if o == nil { - return nil - } - return o.MessageID -} - -func (o *OrbitMeanElementsMetadata) GetRefFrame() *OrbitMeanElementsMetadataRefFrame { - if o == nil { - return nil - } - return o.RefFrame -} - -func (o *OrbitMeanElementsMetadata) GetRefFrameEpoch() *time.Time { - if o == nil { - return nil - } - return o.RefFrameEpoch -} - -func (o *OrbitMeanElementsMetadata) GetMeanElementTheory() *OrbitMeanElementsMetadataMeanElementTheory { - if o == nil { - return nil - } - return o.MeanElementTheory -} - -func (o *OrbitMeanElementsMetadata) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *OrbitMeanElementsMetadata) UnmarshalJSON(data []byte) error { - type embed OrbitMeanElementsMetadata - var unmarshaler = struct { - embed - CreationDate *internal.DateTime `json:"creationDate,omitempty"` - RefFrameEpoch *internal.DateTime `json:"refFrameEpoch,omitempty"` - }{ - embed: embed(*o), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *o = OrbitMeanElementsMetadata(unmarshaler.embed) - o.CreationDate = unmarshaler.CreationDate.TimePtr() - o.RefFrameEpoch = unmarshaler.RefFrameEpoch.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *OrbitMeanElementsMetadata) MarshalJSON() ([]byte, error) { - type embed OrbitMeanElementsMetadata - var marshaler = struct { - embed - CreationDate *internal.DateTime `json:"creationDate,omitempty"` - RefFrameEpoch *internal.DateTime `json:"refFrameEpoch,omitempty"` - }{ - embed: embed(*o), - CreationDate: internal.NewOptionalDateTime(o.CreationDate), - RefFrameEpoch: internal.NewOptionalDateTime(o.RefFrameEpoch), - } - return json.Marshal(marshaler) -} - -func (o *OrbitMeanElementsMetadata) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -type OrbitMeanElementsMetadataMeanElementTheory string - -const ( - OrbitMeanElementsMetadataMeanElementTheoryMeanElementTheoryInvalid OrbitMeanElementsMetadataMeanElementTheory = "MEAN_ELEMENT_THEORY_INVALID" - OrbitMeanElementsMetadataMeanElementTheoryMeanElementTheorySgp4 OrbitMeanElementsMetadataMeanElementTheory = "MEAN_ELEMENT_THEORY_SGP4" -) - -func NewOrbitMeanElementsMetadataMeanElementTheoryFromString(s string) (OrbitMeanElementsMetadataMeanElementTheory, error) { - switch s { - case "MEAN_ELEMENT_THEORY_INVALID": - return OrbitMeanElementsMetadataMeanElementTheoryMeanElementTheoryInvalid, nil - case "MEAN_ELEMENT_THEORY_SGP4": - return OrbitMeanElementsMetadataMeanElementTheoryMeanElementTheorySgp4, nil - } - var t OrbitMeanElementsMetadataMeanElementTheory - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (o OrbitMeanElementsMetadataMeanElementTheory) Ptr() *OrbitMeanElementsMetadataMeanElementTheory { - return &o -} - -// Reference frame, assumed to be Earth-centered -type OrbitMeanElementsMetadataRefFrame string - -const ( - OrbitMeanElementsMetadataRefFrameEciReferenceFrameInvalid OrbitMeanElementsMetadataRefFrame = "ECI_REFERENCE_FRAME_INVALID" - OrbitMeanElementsMetadataRefFrameEciReferenceFrameTeme OrbitMeanElementsMetadataRefFrame = "ECI_REFERENCE_FRAME_TEME" -) - -func NewOrbitMeanElementsMetadataRefFrameFromString(s string) (OrbitMeanElementsMetadataRefFrame, error) { - switch s { - case "ECI_REFERENCE_FRAME_INVALID": - return OrbitMeanElementsMetadataRefFrameEciReferenceFrameInvalid, nil - case "ECI_REFERENCE_FRAME_TEME": - return OrbitMeanElementsMetadataRefFrameEciReferenceFrameTeme, nil - } - var t OrbitMeanElementsMetadataRefFrame - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (o OrbitMeanElementsMetadataRefFrame) Ptr() *OrbitMeanElementsMetadataRefFrame { - return &o -} - -// Details about an override. Last write wins. -type Override struct { - // override request id for an override request - RequestID *string `json:"requestId,omitempty" url:"requestId,omitempty"` - // proto field path which is the string representation of a field. - // - // example: correlated.primary_entity_id would be primary_entity_id in correlated component - FieldPath *string `json:"fieldPath,omitempty" url:"fieldPath,omitempty"` - // new field value corresponding to field path. In the shape of an empty entity with only the changed value. - // - // example: entity: { mil_view: { disposition: Disposition_DISPOSITION_HOSTILE } } - MaskedFieldValue *Entity `json:"maskedFieldValue,omitempty" url:"maskedFieldValue,omitempty"` - // status of the override - Status *OverrideStatus `json:"status,omitempty" url:"status,omitempty"` - Provenance *Provenance `json:"provenance,omitempty" url:"provenance,omitempty"` - // The type of the override, defined by the stage of the entity lifecycle that the entity was in when the override - // - // was requested. - Type *OverrideType `json:"type,omitempty" url:"type,omitempty"` - // Timestamp of the override request. The timestamp is generated by the Entity Manager instance that receives the request. - RequestTimestamp *time.Time `json:"requestTimestamp,omitempty" url:"requestTimestamp,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *Override) GetRequestID() *string { - if o == nil { - return nil - } - return o.RequestID -} - -func (o *Override) GetFieldPath() *string { - if o == nil { - return nil - } - return o.FieldPath -} - -func (o *Override) GetMaskedFieldValue() *Entity { - if o == nil { - return nil - } - return o.MaskedFieldValue -} - -func (o *Override) GetStatus() *OverrideStatus { - if o == nil { - return nil - } - return o.Status -} - -func (o *Override) GetProvenance() *Provenance { - if o == nil { - return nil - } - return o.Provenance -} - -func (o *Override) GetType() *OverrideType { - if o == nil { - return nil - } - return o.Type -} - -func (o *Override) GetRequestTimestamp() *time.Time { - if o == nil { - return nil - } - return o.RequestTimestamp -} - -func (o *Override) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *Override) UnmarshalJSON(data []byte) error { - type embed Override - var unmarshaler = struct { - embed - RequestTimestamp *internal.DateTime `json:"requestTimestamp,omitempty"` - }{ - embed: embed(*o), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *o = Override(unmarshaler.embed) - o.RequestTimestamp = unmarshaler.RequestTimestamp.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *Override) MarshalJSON() ([]byte, error) { - type embed Override - var marshaler = struct { - embed - RequestTimestamp *internal.DateTime `json:"requestTimestamp,omitempty"` - }{ - embed: embed(*o), - RequestTimestamp: internal.NewOptionalDateTime(o.RequestTimestamp), - } - return json.Marshal(marshaler) -} - -func (o *Override) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -// status of the override -type OverrideStatus string - -const ( - OverrideStatusOverrideStatusInvalid OverrideStatus = "OVERRIDE_STATUS_INVALID" - OverrideStatusOverrideStatusApplied OverrideStatus = "OVERRIDE_STATUS_APPLIED" - OverrideStatusOverrideStatusPending OverrideStatus = "OVERRIDE_STATUS_PENDING" - OverrideStatusOverrideStatusTimeout OverrideStatus = "OVERRIDE_STATUS_TIMEOUT" - OverrideStatusOverrideStatusRejected OverrideStatus = "OVERRIDE_STATUS_REJECTED" - OverrideStatusOverrideStatusDeletionPending OverrideStatus = "OVERRIDE_STATUS_DELETION_PENDING" -) - -func NewOverrideStatusFromString(s string) (OverrideStatus, error) { - switch s { - case "OVERRIDE_STATUS_INVALID": - return OverrideStatusOverrideStatusInvalid, nil - case "OVERRIDE_STATUS_APPLIED": - return OverrideStatusOverrideStatusApplied, nil - case "OVERRIDE_STATUS_PENDING": - return OverrideStatusOverrideStatusPending, nil - case "OVERRIDE_STATUS_TIMEOUT": - return OverrideStatusOverrideStatusTimeout, nil - case "OVERRIDE_STATUS_REJECTED": - return OverrideStatusOverrideStatusRejected, nil - case "OVERRIDE_STATUS_DELETION_PENDING": - return OverrideStatusOverrideStatusDeletionPending, nil - } - var t OverrideStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (o OverrideStatus) Ptr() *OverrideStatus { - return &o -} - -// The type of the override, defined by the stage of the entity lifecycle that the entity was in when the override -// -// was requested. -type OverrideType string - -const ( - OverrideTypeOverrideTypeInvalid OverrideType = "OVERRIDE_TYPE_INVALID" - OverrideTypeOverrideTypeLive OverrideType = "OVERRIDE_TYPE_LIVE" - OverrideTypeOverrideTypePostExpiry OverrideType = "OVERRIDE_TYPE_POST_EXPIRY" -) - -func NewOverrideTypeFromString(s string) (OverrideType, error) { - switch s { - case "OVERRIDE_TYPE_INVALID": - return OverrideTypeOverrideTypeInvalid, nil - case "OVERRIDE_TYPE_LIVE": - return OverrideTypeOverrideTypeLive, nil - case "OVERRIDE_TYPE_POST_EXPIRY": - return OverrideTypeOverrideTypePostExpiry, nil - } - var t OverrideType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (o OverrideType) Ptr() *OverrideType { - return &o -} - -// Metadata about entity overrides present. -type Overrides struct { - Override []*Override `json:"override,omitempty" url:"override,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (o *Overrides) GetOverride() []*Override { - if o == nil { - return nil - } - return o.Override -} - -func (o *Overrides) GetExtraProperties() map[string]interface{} { - return o.extraProperties -} - -func (o *Overrides) UnmarshalJSON(data []byte) error { - type unmarshaler Overrides - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *o = Overrides(value) - extraProperties, err := internal.ExtractExtraProperties(data, *o) - if err != nil { - return err - } - o.extraProperties = extraProperties - o.rawJSON = json.RawMessage(data) - return nil -} - -func (o *Overrides) String() string { - if len(o.rawJSON) > 0 { - if value, err := internal.StringifyJSON(o.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(o); err == nil { - return value - } - return fmt.Sprintf("%#v", o) -} - -// Individual payload configuration. -type Payload struct { - Config *PayloadConfiguration `json:"config,omitempty" url:"config,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *Payload) GetConfig() *PayloadConfiguration { - if p == nil { - return nil - } - return p.Config -} - -func (p *Payload) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *Payload) UnmarshalJSON(data []byte) error { - type unmarshaler Payload - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = Payload(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *Payload) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type PayloadConfiguration struct { - // Identifying ID for the capability. - // - // This ID may be used multiple times to represent payloads that are the same capability but have different operational states - CapabilityID *string `json:"capabilityId,omitempty" url:"capabilityId,omitempty"` - // The number of payloads currently available in the configuration. - Quantity *int `json:"quantity,omitempty" url:"quantity,omitempty"` - // The target environments the configuration is effective against. - EffectiveEnvironment []PayloadConfigurationEffectiveEnvironmentItem `json:"effectiveEnvironment,omitempty" url:"effectiveEnvironment,omitempty"` - // The operational state of this payload. - PayloadOperationalState *PayloadConfigurationPayloadOperationalState `json:"payloadOperationalState,omitempty" url:"payloadOperationalState,omitempty"` - // A human readable description of the payload - PayloadDescription *string `json:"payloadDescription,omitempty" url:"payloadDescription,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PayloadConfiguration) GetCapabilityID() *string { - if p == nil { - return nil - } - return p.CapabilityID -} - -func (p *PayloadConfiguration) GetQuantity() *int { - if p == nil { - return nil - } - return p.Quantity -} - -func (p *PayloadConfiguration) GetEffectiveEnvironment() []PayloadConfigurationEffectiveEnvironmentItem { - if p == nil { - return nil - } - return p.EffectiveEnvironment -} - -func (p *PayloadConfiguration) GetPayloadOperationalState() *PayloadConfigurationPayloadOperationalState { - if p == nil { - return nil - } - return p.PayloadOperationalState -} - -func (p *PayloadConfiguration) GetPayloadDescription() *string { - if p == nil { - return nil - } - return p.PayloadDescription -} - -func (p *PayloadConfiguration) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PayloadConfiguration) UnmarshalJSON(data []byte) error { - type unmarshaler PayloadConfiguration - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PayloadConfiguration(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PayloadConfiguration) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type PayloadConfigurationEffectiveEnvironmentItem string - -const ( - PayloadConfigurationEffectiveEnvironmentItemEnvironmentUnknown PayloadConfigurationEffectiveEnvironmentItem = "ENVIRONMENT_UNKNOWN" - PayloadConfigurationEffectiveEnvironmentItemEnvironmentAir PayloadConfigurationEffectiveEnvironmentItem = "ENVIRONMENT_AIR" - PayloadConfigurationEffectiveEnvironmentItemEnvironmentSurface PayloadConfigurationEffectiveEnvironmentItem = "ENVIRONMENT_SURFACE" - PayloadConfigurationEffectiveEnvironmentItemEnvironmentSubSurface PayloadConfigurationEffectiveEnvironmentItem = "ENVIRONMENT_SUB_SURFACE" - PayloadConfigurationEffectiveEnvironmentItemEnvironmentLand PayloadConfigurationEffectiveEnvironmentItem = "ENVIRONMENT_LAND" - PayloadConfigurationEffectiveEnvironmentItemEnvironmentSpace PayloadConfigurationEffectiveEnvironmentItem = "ENVIRONMENT_SPACE" -) - -func NewPayloadConfigurationEffectiveEnvironmentItemFromString(s string) (PayloadConfigurationEffectiveEnvironmentItem, error) { - switch s { - case "ENVIRONMENT_UNKNOWN": - return PayloadConfigurationEffectiveEnvironmentItemEnvironmentUnknown, nil - case "ENVIRONMENT_AIR": - return PayloadConfigurationEffectiveEnvironmentItemEnvironmentAir, nil - case "ENVIRONMENT_SURFACE": - return PayloadConfigurationEffectiveEnvironmentItemEnvironmentSurface, nil - case "ENVIRONMENT_SUB_SURFACE": - return PayloadConfigurationEffectiveEnvironmentItemEnvironmentSubSurface, nil - case "ENVIRONMENT_LAND": - return PayloadConfigurationEffectiveEnvironmentItemEnvironmentLand, nil - case "ENVIRONMENT_SPACE": - return PayloadConfigurationEffectiveEnvironmentItemEnvironmentSpace, nil - } - var t PayloadConfigurationEffectiveEnvironmentItem - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (p PayloadConfigurationEffectiveEnvironmentItem) Ptr() *PayloadConfigurationEffectiveEnvironmentItem { - return &p -} - -// The operational state of this payload. -type PayloadConfigurationPayloadOperationalState string - -const ( - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateInvalid PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_INVALID" - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateOff PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_OFF" - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateNonOperational PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_NON_OPERATIONAL" - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateDegraded PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_DEGRADED" - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateOperational PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_OPERATIONAL" - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateOutOfService PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_OUT_OF_SERVICE" - PayloadConfigurationPayloadOperationalStatePayloadOperationalStateUnknown PayloadConfigurationPayloadOperationalState = "PAYLOAD_OPERATIONAL_STATE_UNKNOWN" -) - -func NewPayloadConfigurationPayloadOperationalStateFromString(s string) (PayloadConfigurationPayloadOperationalState, error) { - switch s { - case "PAYLOAD_OPERATIONAL_STATE_INVALID": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateInvalid, nil - case "PAYLOAD_OPERATIONAL_STATE_OFF": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateOff, nil - case "PAYLOAD_OPERATIONAL_STATE_NON_OPERATIONAL": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateNonOperational, nil - case "PAYLOAD_OPERATIONAL_STATE_DEGRADED": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateDegraded, nil - case "PAYLOAD_OPERATIONAL_STATE_OPERATIONAL": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateOperational, nil - case "PAYLOAD_OPERATIONAL_STATE_OUT_OF_SERVICE": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateOutOfService, nil - case "PAYLOAD_OPERATIONAL_STATE_UNKNOWN": - return PayloadConfigurationPayloadOperationalStatePayloadOperationalStateUnknown, nil - } - var t PayloadConfigurationPayloadOperationalState - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (p PayloadConfigurationPayloadOperationalState) Ptr() *PayloadConfigurationPayloadOperationalState { - return &p -} - -// List of payloads available for an entity. -type Payloads struct { - PayloadConfigurations []*Payload `json:"payloadConfigurations,omitempty" url:"payloadConfigurations,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *Payloads) GetPayloadConfigurations() []*Payload { - if p == nil { - return nil - } - return p.PayloadConfigurations -} - -func (p *Payloads) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *Payloads) UnmarshalJSON(data []byte) error { - type unmarshaler Payloads - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = Payloads(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *Payloads) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type Pose struct { - // Geospatial location defined by this Pose. - Pos *Lla `json:"pos,omitempty" url:"pos,omitempty"` - // The quaternion to transform a point in the Pose frame to the ENU frame. The Pose frame could be Body, Turret, - // - // etc and is determined by the context in which this Pose is used. - // The normal convention for defining orientation is to list the frames of transformation, for example - // att_gimbal_to_enu is the quaternion which transforms a point in the gimbal frame to the body frame, but - // in this case we truncate to att_enu because the Pose frame isn't defined. A potentially better name for this - // field would have been att_pose_to_enu. - // - // Implementations of this quaternion should left multiply this quaternion to transform a point from the Pose frame - // to the enu frame. - // - // Point posePt{1,0,0}; - // Rotation attPoseToEnu{}; - // Point = attPoseToEnu*posePt; - // - // This transformed point represents some vector in ENU space that is aligned with the x axis of the attPoseToEnu - // matrix. - // - // An alternative matrix expression is as follows: - // ptEnu = M x ptPose - AttEnu *Quaternion `json:"attEnu,omitempty" url:"attEnu,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *Pose) GetPos() *Lla { - if p == nil { - return nil - } - return p.Pos -} - -func (p *Pose) GetAttEnu() *Quaternion { - if p == nil { - return nil - } - return p.AttEnu -} - -func (p *Pose) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *Pose) UnmarshalJSON(data []byte) error { - type unmarshaler Pose - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = Pose(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *Pose) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// WGS84 position. Position includes four altitude references. -// -// The data model does not currently support Mean Sea Level (MSL) references, -// such as the Earth Gravitational Model 1996 (EGM-96) and the Earth Gravitational Model 2008 (EGM-08). -// If the only altitude reference available to your integration is MSL, convert it to -// Height Above Ellipsoid (HAE) and populate the altitude_hae_meters field. -type Position struct { - // WGS84 geodetic latitude in decimal degrees. - LatitudeDegrees *float64 `json:"latitudeDegrees,omitempty" url:"latitudeDegrees,omitempty"` - // WGS84 longitude in decimal degrees. - LongitudeDegrees *float64 `json:"longitudeDegrees,omitempty" url:"longitudeDegrees,omitempty"` - // altitude as height above ellipsoid (WGS84) in meters. DoubleValue wrapper is used to distinguish optional from - // - // default 0. - AltitudeHaeMeters *float64 `json:"altitudeHaeMeters,omitempty" url:"altitudeHaeMeters,omitempty"` - // Altitude as AGL (Above Ground Level) if the upstream data source has this value set. This value represents the - // - // entity's height above the terrain. This is typically measured with a radar altimeter or by using a terrain tile - // set lookup. If the value is not set from the upstream, this value is not set. - AltitudeAglMeters *float64 `json:"altitudeAglMeters,omitempty" url:"altitudeAglMeters,omitempty"` - // Altitude as ASF (Above Sea Floor) if the upstream data source has this value set. If the value is not set from the upstream, this value is - // - // not set. - AltitudeAsfMeters *float64 `json:"altitudeAsfMeters,omitempty" url:"altitudeAsfMeters,omitempty"` - // The depth of the entity from the surface of the water through sensor measurements based on differential pressure - // - // between the interior and exterior of the vessel. If the value is not set from the upstream, this value is not set. - PressureDepthMeters *float64 `json:"pressureDepthMeters,omitempty" url:"pressureDepthMeters,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *Position) GetLatitudeDegrees() *float64 { - if p == nil { - return nil - } - return p.LatitudeDegrees -} - -func (p *Position) GetLongitudeDegrees() *float64 { - if p == nil { - return nil - } - return p.LongitudeDegrees -} - -func (p *Position) GetAltitudeHaeMeters() *float64 { - if p == nil { - return nil - } - return p.AltitudeHaeMeters -} - -func (p *Position) GetAltitudeAglMeters() *float64 { - if p == nil { - return nil - } - return p.AltitudeAglMeters -} - -func (p *Position) GetAltitudeAsfMeters() *float64 { - if p == nil { - return nil - } - return p.AltitudeAsfMeters -} - -func (p *Position) GetPressureDepthMeters() *float64 { - if p == nil { - return nil - } - return p.PressureDepthMeters -} - -func (p *Position) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *Position) UnmarshalJSON(data []byte) error { - type unmarshaler Position - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = Position(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *Position) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// Represents the power level of a system. -type PowerLevel struct { - // Total power capacity of the system. - Capacity *float64 `json:"capacity,omitempty" url:"capacity,omitempty"` - // Remaining power capacity of the system. - Remaining *float64 `json:"remaining,omitempty" url:"remaining,omitempty"` - // Percent of power remaining. - PercentRemaining *float64 `json:"percentRemaining,omitempty" url:"percentRemaining,omitempty"` - // Voltage of the power source subsystem, as reported by the power source. If the source does not report this value - // - // this field will be null. - Voltage *float64 `json:"voltage,omitempty" url:"voltage,omitempty"` - // Current in amps of the power source subsystem, as reported by the power source. If the source does not - // - // report this value this field will be null. - CurrentAmps *float64 `json:"currentAmps,omitempty" url:"currentAmps,omitempty"` - // Estimated minutes until empty. Calculated with consumption at the moment, as reported by the power source. If the source does not - // - // report this value this field will be null. - RunTimeToEmptyMins *float64 `json:"runTimeToEmptyMins,omitempty" url:"runTimeToEmptyMins,omitempty"` - // Fuel consumption rate in liters per second. - ConsumptionRateLPerS *float64 `json:"consumptionRateLPerS,omitempty" url:"consumptionRateLPerS,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PowerLevel) GetCapacity() *float64 { - if p == nil { - return nil - } - return p.Capacity -} - -func (p *PowerLevel) GetRemaining() *float64 { - if p == nil { - return nil - } - return p.Remaining -} - -func (p *PowerLevel) GetPercentRemaining() *float64 { - if p == nil { - return nil - } - return p.PercentRemaining -} - -func (p *PowerLevel) GetVoltage() *float64 { - if p == nil { - return nil - } - return p.Voltage -} - -func (p *PowerLevel) GetCurrentAmps() *float64 { - if p == nil { - return nil - } - return p.CurrentAmps -} - -func (p *PowerLevel) GetRunTimeToEmptyMins() *float64 { - if p == nil { - return nil - } - return p.RunTimeToEmptyMins -} - -func (p *PowerLevel) GetConsumptionRateLPerS() *float64 { - if p == nil { - return nil - } - return p.ConsumptionRateLPerS -} - -func (p *PowerLevel) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PowerLevel) UnmarshalJSON(data []byte) error { - type unmarshaler PowerLevel - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PowerLevel(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PowerLevel) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// Represents the state of a single power source that is connected to this entity. -type PowerSource struct { - // Status of the power source. - PowerStatus *PowerSourcePowerStatus `json:"powerStatus,omitempty" url:"powerStatus,omitempty"` - // Used to determine the type of power source. - PowerType *PowerSourcePowerType `json:"powerType,omitempty" url:"powerType,omitempty"` - // Power level of the system. If absent, the power level is assumed to be unknown. - PowerLevel *PowerLevel `json:"powerLevel,omitempty" url:"powerLevel,omitempty"` - // Set of human-readable messages with status of the power system. Typically this would be used in an error state - // - // to provide additional error information. This can also be used for informational messages. - Messages []string `json:"messages,omitempty" url:"messages,omitempty"` - // Whether the power source is offloadable. If the value is missing (as opposed to false) then the entity does not - // - // report whether the power source is offloadable. - Offloadable *bool `json:"offloadable,omitempty" url:"offloadable,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PowerSource) GetPowerStatus() *PowerSourcePowerStatus { - if p == nil { - return nil - } - return p.PowerStatus -} - -func (p *PowerSource) GetPowerType() *PowerSourcePowerType { - if p == nil { - return nil - } - return p.PowerType -} - -func (p *PowerSource) GetPowerLevel() *PowerLevel { - if p == nil { - return nil - } - return p.PowerLevel -} - -func (p *PowerSource) GetMessages() []string { - if p == nil { - return nil - } - return p.Messages -} - -func (p *PowerSource) GetOffloadable() *bool { - if p == nil { - return nil - } - return p.Offloadable -} - -func (p *PowerSource) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PowerSource) UnmarshalJSON(data []byte) error { - type unmarshaler PowerSource - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PowerSource(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PowerSource) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// Status of the power source. -type PowerSourcePowerStatus string - -const ( - PowerSourcePowerStatusPowerStatusInvalid PowerSourcePowerStatus = "POWER_STATUS_INVALID" - PowerSourcePowerStatusPowerStatusUnknown PowerSourcePowerStatus = "POWER_STATUS_UNKNOWN" - PowerSourcePowerStatusPowerStatusNotPresent PowerSourcePowerStatus = "POWER_STATUS_NOT_PRESENT" - PowerSourcePowerStatusPowerStatusOperating PowerSourcePowerStatus = "POWER_STATUS_OPERATING" - PowerSourcePowerStatusPowerStatusDisabled PowerSourcePowerStatus = "POWER_STATUS_DISABLED" - PowerSourcePowerStatusPowerStatusError PowerSourcePowerStatus = "POWER_STATUS_ERROR" -) - -func NewPowerSourcePowerStatusFromString(s string) (PowerSourcePowerStatus, error) { - switch s { - case "POWER_STATUS_INVALID": - return PowerSourcePowerStatusPowerStatusInvalid, nil - case "POWER_STATUS_UNKNOWN": - return PowerSourcePowerStatusPowerStatusUnknown, nil - case "POWER_STATUS_NOT_PRESENT": - return PowerSourcePowerStatusPowerStatusNotPresent, nil - case "POWER_STATUS_OPERATING": - return PowerSourcePowerStatusPowerStatusOperating, nil - case "POWER_STATUS_DISABLED": - return PowerSourcePowerStatusPowerStatusDisabled, nil - case "POWER_STATUS_ERROR": - return PowerSourcePowerStatusPowerStatusError, nil - } - var t PowerSourcePowerStatus - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (p PowerSourcePowerStatus) Ptr() *PowerSourcePowerStatus { - return &p -} - -// Used to determine the type of power source. -type PowerSourcePowerType string - -const ( - PowerSourcePowerTypePowerTypeInvalid PowerSourcePowerType = "POWER_TYPE_INVALID" - PowerSourcePowerTypePowerTypeUnknown PowerSourcePowerType = "POWER_TYPE_UNKNOWN" - PowerSourcePowerTypePowerTypeGas PowerSourcePowerType = "POWER_TYPE_GAS" - PowerSourcePowerTypePowerTypeBattery PowerSourcePowerType = "POWER_TYPE_BATTERY" -) - -func NewPowerSourcePowerTypeFromString(s string) (PowerSourcePowerType, error) { - switch s { - case "POWER_TYPE_INVALID": - return PowerSourcePowerTypePowerTypeInvalid, nil - case "POWER_TYPE_UNKNOWN": - return PowerSourcePowerTypePowerTypeUnknown, nil - case "POWER_TYPE_GAS": - return PowerSourcePowerTypePowerTypeGas, nil - case "POWER_TYPE_BATTERY": - return PowerSourcePowerTypePowerTypeBattery, nil - } - var t PowerSourcePowerType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (p PowerSourcePowerType) Ptr() *PowerSourcePowerType { - return &p -} - -// Represents the state of power sources connected to this entity. -type PowerState struct { - // This is a map where the key is a unique id of the power source and the value is additional information about the - // - // power source. - SourceIDToState map[string]*PowerSource `json:"sourceIdToState,omitempty" url:"sourceIdToState,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PowerState) GetSourceIDToState() map[string]*PowerSource { - if p == nil { - return nil - } - return p.SourceIDToState -} - -func (p *PowerState) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PowerState) UnmarshalJSON(data []byte) error { - type unmarshaler PowerState - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PowerState(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PowerState) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type PrimaryCorrelation struct { - // The secondary entity IDs part of this correlation. - SecondaryEntityIDs []string `json:"secondaryEntityIds,omitempty" url:"secondaryEntityIds,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PrimaryCorrelation) GetSecondaryEntityIDs() []string { - if p == nil { - return nil - } - return p.SecondaryEntityIDs -} - -func (p *PrimaryCorrelation) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PrimaryCorrelation) UnmarshalJSON(data []byte) error { - type unmarshaler PrimaryCorrelation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PrimaryCorrelation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PrimaryCorrelation) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type PrimaryMembership struct { - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PrimaryMembership) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PrimaryMembership) UnmarshalJSON(data []byte) error { - type unmarshaler PrimaryMembership - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PrimaryMembership(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PrimaryMembership) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// Represents a frustum in which which all four corner points project onto the ground. All points in this message -// -// are optional, if the projection to the ground fails then they will not be populated. -type ProjectedFrustum struct { - // Upper left point of the frustum. - UpperLeft *Position `json:"upperLeft,omitempty" url:"upperLeft,omitempty"` - // Upper right point of the frustum. - UpperRight *Position `json:"upperRight,omitempty" url:"upperRight,omitempty"` - // Bottom right point of the frustum. - BottomRight *Position `json:"bottomRight,omitempty" url:"bottomRight,omitempty"` - // Bottom left point of the frustum. - BottomLeft *Position `json:"bottomLeft,omitempty" url:"bottomLeft,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *ProjectedFrustum) GetUpperLeft() *Position { - if p == nil { - return nil - } - return p.UpperLeft -} - -func (p *ProjectedFrustum) GetUpperRight() *Position { - if p == nil { - return nil - } - return p.UpperRight -} - -func (p *ProjectedFrustum) GetBottomRight() *Position { - if p == nil { - return nil - } - return p.BottomRight -} - -func (p *ProjectedFrustum) GetBottomLeft() *Position { - if p == nil { - return nil - } - return p.BottomLeft -} - -func (p *ProjectedFrustum) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *ProjectedFrustum) UnmarshalJSON(data []byte) error { - type unmarshaler ProjectedFrustum - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = ProjectedFrustum(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *ProjectedFrustum) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// Data provenance. -type Provenance struct { - // Name of the integration that produced this entity - IntegrationName *string `json:"integrationName,omitempty" url:"integrationName,omitempty"` - // Source data type of this entity. Examples: ADSB, Link16, etc. - DataType *string `json:"dataType,omitempty" url:"dataType,omitempty"` - // An ID that allows an element from a source to be uniquely identified - SourceID *string `json:"sourceId,omitempty" url:"sourceId,omitempty"` - // The time, according to the source system, that the data in the entity was last modified. Generally, this should - // - // be the time that the source-reported time of validity of the data in the entity. This field must be - // updated with every change to the entity or else Entity Manager will discard the update. - SourceUpdateTime *time.Time `json:"sourceUpdateTime,omitempty" url:"sourceUpdateTime,omitempty"` - // Description of the modification source. In the case of a user this is the email address. - SourceDescription *string `json:"sourceDescription,omitempty" url:"sourceDescription,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *Provenance) GetIntegrationName() *string { - if p == nil { - return nil - } - return p.IntegrationName -} - -func (p *Provenance) GetDataType() *string { - if p == nil { - return nil - } - return p.DataType -} - -func (p *Provenance) GetSourceID() *string { - if p == nil { - return nil - } - return p.SourceID -} - -func (p *Provenance) GetSourceUpdateTime() *time.Time { - if p == nil { - return nil - } - return p.SourceUpdateTime -} - -func (p *Provenance) GetSourceDescription() *string { - if p == nil { - return nil - } - return p.SourceDescription -} - -func (p *Provenance) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *Provenance) UnmarshalJSON(data []byte) error { - type embed Provenance - var unmarshaler = struct { - embed - SourceUpdateTime *internal.DateTime `json:"sourceUpdateTime,omitempty"` - }{ - embed: embed(*p), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *p = Provenance(unmarshaler.embed) - p.SourceUpdateTime = unmarshaler.SourceUpdateTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *Provenance) MarshalJSON() ([]byte, error) { - type embed Provenance - var marshaler = struct { - embed - SourceUpdateTime *internal.DateTime `json:"sourceUpdateTime,omitempty"` - }{ - embed: embed(*p), - SourceUpdateTime: internal.NewOptionalDateTime(p.SourceUpdateTime), - } - return json.Marshal(marshaler) -} - -func (p *Provenance) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -// A component that describe the length in time between two pulses -type PulseRepetitionInterval struct { - PulseRepetitionIntervalS *Measurement `json:"pulseRepetitionIntervalS,omitempty" url:"pulseRepetitionIntervalS,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (p *PulseRepetitionInterval) GetPulseRepetitionIntervalS() *Measurement { - if p == nil { - return nil - } - return p.PulseRepetitionIntervalS -} - -func (p *PulseRepetitionInterval) GetExtraProperties() map[string]interface{} { - return p.extraProperties -} - -func (p *PulseRepetitionInterval) UnmarshalJSON(data []byte) error { - type unmarshaler PulseRepetitionInterval - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *p = PulseRepetitionInterval(value) - extraProperties, err := internal.ExtractExtraProperties(data, *p) - if err != nil { - return err - } - p.extraProperties = extraProperties - p.rawJSON = json.RawMessage(data) - return nil -} - -func (p *PulseRepetitionInterval) String() string { - if len(p.rawJSON) > 0 { - if value, err := internal.StringifyJSON(p.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(p); err == nil { - return value - } - return fmt.Sprintf("%#v", p) -} - -type Quaternion struct { - // x, y, z are vector portion, w is scalar - X *float64 `json:"x,omitempty" url:"x,omitempty"` - Y *float64 `json:"y,omitempty" url:"y,omitempty"` - Z *float64 `json:"z,omitempty" url:"z,omitempty"` - W *float64 `json:"w,omitempty" url:"w,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (q *Quaternion) GetX() *float64 { - if q == nil { - return nil - } - return q.X -} - -func (q *Quaternion) GetY() *float64 { - if q == nil { - return nil - } - return q.Y -} - -func (q *Quaternion) GetZ() *float64 { - if q == nil { - return nil - } - return q.Z -} - -func (q *Quaternion) GetW() *float64 { - if q == nil { - return nil - } - return q.W -} - -func (q *Quaternion) GetExtraProperties() map[string]interface{} { - return q.extraProperties -} - -func (q *Quaternion) UnmarshalJSON(data []byte) error { - type unmarshaler Quaternion - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *q = Quaternion(value) - extraProperties, err := internal.ExtractExtraProperties(data, *q) - if err != nil { - return err - } - q.extraProperties = extraProperties - q.rawJSON = json.RawMessage(data) - return nil -} - -func (q *Quaternion) String() string { - if len(q.rawJSON) > 0 { - if value, err := internal.StringifyJSON(q.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(q); err == nil { - return value - } - return fmt.Sprintf("%#v", q) -} - -// Range rings allow visual assessment of map distance at varying zoom levels. -type RangeRings struct { - // The minimum range ring distance, specified in meters. - MinDistanceM *float64 `json:"minDistanceM,omitempty" url:"minDistanceM,omitempty"` - // The maximum range ring distance, specified in meters. - MaxDistanceM *float64 `json:"maxDistanceM,omitempty" url:"maxDistanceM,omitempty"` - // The count of range rings. - RingCount *int `json:"ringCount,omitempty" url:"ringCount,omitempty"` - // The color of range rings, specified in hex string. - RingLineColor *Color `json:"ringLineColor,omitempty" url:"ringLineColor,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *RangeRings) GetMinDistanceM() *float64 { - if r == nil { - return nil - } - return r.MinDistanceM -} - -func (r *RangeRings) GetMaxDistanceM() *float64 { - if r == nil { - return nil - } - return r.MaxDistanceM -} - -func (r *RangeRings) GetRingCount() *int { - if r == nil { - return nil - } - return r.RingCount -} - -func (r *RangeRings) GetRingLineColor() *Color { - if r == nil { - return nil - } - return r.RingLineColor -} - -func (r *RangeRings) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *RangeRings) UnmarshalJSON(data []byte) error { - type unmarshaler RangeRings - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *r = RangeRings(value) - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *RangeRings) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// The relationship component indicates a relationship to another entity. -type Relationship struct { - // The entity ID to which this entity is related. - RelatedEntityID *string `json:"relatedEntityId,omitempty" url:"relatedEntityId,omitempty"` - // A unique identifier for this relationship. Allows removing or updating relationships. - RelationshipID *string `json:"relationshipId,omitempty" url:"relationshipId,omitempty"` - // The relationship type - RelationshipType *RelationshipType `json:"relationshipType,omitempty" url:"relationshipType,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *Relationship) GetRelatedEntityID() *string { - if r == nil { - return nil - } - return r.RelatedEntityID -} - -func (r *Relationship) GetRelationshipID() *string { - if r == nil { - return nil - } - return r.RelationshipID -} - -func (r *Relationship) GetRelationshipType() *RelationshipType { - if r == nil { - return nil - } - return r.RelationshipType -} - -func (r *Relationship) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *Relationship) UnmarshalJSON(data []byte) error { - type unmarshaler Relationship - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *r = Relationship(value) - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *Relationship) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// Determines the type of relationship between this entity and another. -type RelationshipType struct { - TrackedBy *TrackedBy `json:"trackedBy,omitempty" url:"trackedBy,omitempty"` - GroupChild *GroupChild `json:"groupChild,omitempty" url:"groupChild,omitempty"` - GroupParent *GroupParent `json:"groupParent,omitempty" url:"groupParent,omitempty"` - MergedFrom *MergedFrom `json:"mergedFrom,omitempty" url:"mergedFrom,omitempty"` - ActiveTarget *ActiveTarget `json:"activeTarget,omitempty" url:"activeTarget,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *RelationshipType) GetTrackedBy() *TrackedBy { - if r == nil { - return nil - } - return r.TrackedBy -} - -func (r *RelationshipType) GetGroupChild() *GroupChild { - if r == nil { - return nil - } - return r.GroupChild -} - -func (r *RelationshipType) GetGroupParent() *GroupParent { - if r == nil { - return nil - } - return r.GroupParent -} - -func (r *RelationshipType) GetMergedFrom() *MergedFrom { - if r == nil { - return nil - } - return r.MergedFrom -} - -func (r *RelationshipType) GetActiveTarget() *ActiveTarget { - if r == nil { - return nil - } - return r.ActiveTarget -} - -func (r *RelationshipType) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *RelationshipType) UnmarshalJSON(data []byte) error { - type unmarshaler RelationshipType - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *r = RelationshipType(value) - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *RelationshipType) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// The relationships between this entity and other entities in the common operational picture. -type Relationships struct { - Relationships []*Relationship `json:"relationships,omitempty" url:"relationships,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *Relationships) GetRelationships() []*Relationship { - if r == nil { - return nil - } - return r.Relationships -} - -func (r *Relationships) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *Relationships) UnmarshalJSON(data []byte) error { - type unmarshaler Relationships - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *r = Relationships(value) - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *Relationships) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// Represents RF configurations supported on this sensor. -type RfConfiguration struct { - // Frequency ranges that are available for this sensor. - FrequencyRangeHz []*FrequencyRange `json:"frequencyRangeHz,omitempty" url:"frequencyRangeHz,omitempty"` - // Bandwidth ranges that are available for this sensor. - BandwidthRangeHz []*BandwidthRange `json:"bandwidthRangeHz,omitempty" url:"bandwidthRangeHz,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *RfConfiguration) GetFrequencyRangeHz() []*FrequencyRange { - if r == nil { - return nil - } - return r.FrequencyRangeHz -} - -func (r *RfConfiguration) GetBandwidthRangeHz() []*BandwidthRange { - if r == nil { - return nil - } - return r.BandwidthRangeHz -} - -func (r *RfConfiguration) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *RfConfiguration) UnmarshalJSON(data []byte) error { - type unmarshaler RfConfiguration - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *r = RfConfiguration(value) - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *RfConfiguration) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -type RouteDetails struct { - // Free form text giving the name of the entity's destination - DestinationName *string `json:"destinationName,omitempty" url:"destinationName,omitempty"` - // Estimated time of arrival at destination - EstimatedArrivalTime *time.Time `json:"estimatedArrivalTime,omitempty" url:"estimatedArrivalTime,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (r *RouteDetails) GetDestinationName() *string { - if r == nil { - return nil - } - return r.DestinationName -} - -func (r *RouteDetails) GetEstimatedArrivalTime() *time.Time { - if r == nil { - return nil - } - return r.EstimatedArrivalTime -} - -func (r *RouteDetails) GetExtraProperties() map[string]interface{} { - return r.extraProperties -} - -func (r *RouteDetails) UnmarshalJSON(data []byte) error { - type embed RouteDetails - var unmarshaler = struct { - embed - EstimatedArrivalTime *internal.DateTime `json:"estimatedArrivalTime,omitempty"` - }{ - embed: embed(*r), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *r = RouteDetails(unmarshaler.embed) - r.EstimatedArrivalTime = unmarshaler.EstimatedArrivalTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *r) - if err != nil { - return err - } - r.extraProperties = extraProperties - r.rawJSON = json.RawMessage(data) - return nil -} - -func (r *RouteDetails) MarshalJSON() ([]byte, error) { - type embed RouteDetails - var marshaler = struct { - embed - EstimatedArrivalTime *internal.DateTime `json:"estimatedArrivalTime,omitempty"` - }{ - embed: embed(*r), - EstimatedArrivalTime: internal.NewOptionalDateTime(r.EstimatedArrivalTime), - } - return json.Marshal(marshaler) -} - -func (r *RouteDetails) String() string { - if len(r.rawJSON) > 0 { - if value, err := internal.StringifyJSON(r.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(r); err == nil { - return value - } - return fmt.Sprintf("%#v", r) -} - -// A component that describes the scanning characteristics of a signal -type ScanCharacteristics struct { - ScanType *ScanCharacteristicsScanType `json:"scanType,omitempty" url:"scanType,omitempty"` - ScanPeriodS *float64 `json:"scanPeriodS,omitempty" url:"scanPeriodS,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *ScanCharacteristics) GetScanType() *ScanCharacteristicsScanType { - if s == nil { - return nil - } - return s.ScanType -} - -func (s *ScanCharacteristics) GetScanPeriodS() *float64 { - if s == nil { - return nil - } - return s.ScanPeriodS -} - -func (s *ScanCharacteristics) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *ScanCharacteristics) UnmarshalJSON(data []byte) error { - type unmarshaler ScanCharacteristics - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = ScanCharacteristics(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *ScanCharacteristics) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -type ScanCharacteristicsScanType string - -const ( - ScanCharacteristicsScanTypeScanTypeInvalid ScanCharacteristicsScanType = "SCAN_TYPE_INVALID" - ScanCharacteristicsScanTypeScanTypeCircular ScanCharacteristicsScanType = "SCAN_TYPE_CIRCULAR" - ScanCharacteristicsScanTypeScanTypeBidirectionalHorizontalSector ScanCharacteristicsScanType = "SCAN_TYPE_BIDIRECTIONAL_HORIZONTAL_SECTOR" - ScanCharacteristicsScanTypeScanTypeBidirectionalVerticalSector ScanCharacteristicsScanType = "SCAN_TYPE_BIDIRECTIONAL_VERTICAL_SECTOR" - ScanCharacteristicsScanTypeScanTypeNonScanning ScanCharacteristicsScanType = "SCAN_TYPE_NON_SCANNING" - ScanCharacteristicsScanTypeScanTypeIrregular ScanCharacteristicsScanType = "SCAN_TYPE_IRREGULAR" - ScanCharacteristicsScanTypeScanTypeConical ScanCharacteristicsScanType = "SCAN_TYPE_CONICAL" - ScanCharacteristicsScanTypeScanTypeLobeSwitching ScanCharacteristicsScanType = "SCAN_TYPE_LOBE_SWITCHING" - ScanCharacteristicsScanTypeScanTypeRaster ScanCharacteristicsScanType = "SCAN_TYPE_RASTER" - ScanCharacteristicsScanTypeScanTypeCircularVerticalSector ScanCharacteristicsScanType = "SCAN_TYPE_CIRCULAR_VERTICAL_SECTOR" - ScanCharacteristicsScanTypeScanTypeCircularConical ScanCharacteristicsScanType = "SCAN_TYPE_CIRCULAR_CONICAL" - ScanCharacteristicsScanTypeScanTypeSectorConical ScanCharacteristicsScanType = "SCAN_TYPE_SECTOR_CONICAL" - ScanCharacteristicsScanTypeScanTypeAgileBeam ScanCharacteristicsScanType = "SCAN_TYPE_AGILE_BEAM" - ScanCharacteristicsScanTypeScanTypeUnidirectionalVerticalSector ScanCharacteristicsScanType = "SCAN_TYPE_UNIDIRECTIONAL_VERTICAL_SECTOR" - ScanCharacteristicsScanTypeScanTypeUnidirectionalHorizontalSector ScanCharacteristicsScanType = "SCAN_TYPE_UNIDIRECTIONAL_HORIZONTAL_SECTOR" - ScanCharacteristicsScanTypeScanTypeUnidirectionalSector ScanCharacteristicsScanType = "SCAN_TYPE_UNIDIRECTIONAL_SECTOR" - ScanCharacteristicsScanTypeScanTypeBidirectionalSector ScanCharacteristicsScanType = "SCAN_TYPE_BIDIRECTIONAL_SECTOR" -) - -func NewScanCharacteristicsScanTypeFromString(s string) (ScanCharacteristicsScanType, error) { - switch s { - case "SCAN_TYPE_INVALID": - return ScanCharacteristicsScanTypeScanTypeInvalid, nil - case "SCAN_TYPE_CIRCULAR": - return ScanCharacteristicsScanTypeScanTypeCircular, nil - case "SCAN_TYPE_BIDIRECTIONAL_HORIZONTAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeBidirectionalHorizontalSector, nil - case "SCAN_TYPE_BIDIRECTIONAL_VERTICAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeBidirectionalVerticalSector, nil - case "SCAN_TYPE_NON_SCANNING": - return ScanCharacteristicsScanTypeScanTypeNonScanning, nil - case "SCAN_TYPE_IRREGULAR": - return ScanCharacteristicsScanTypeScanTypeIrregular, nil - case "SCAN_TYPE_CONICAL": - return ScanCharacteristicsScanTypeScanTypeConical, nil - case "SCAN_TYPE_LOBE_SWITCHING": - return ScanCharacteristicsScanTypeScanTypeLobeSwitching, nil - case "SCAN_TYPE_RASTER": - return ScanCharacteristicsScanTypeScanTypeRaster, nil - case "SCAN_TYPE_CIRCULAR_VERTICAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeCircularVerticalSector, nil - case "SCAN_TYPE_CIRCULAR_CONICAL": - return ScanCharacteristicsScanTypeScanTypeCircularConical, nil - case "SCAN_TYPE_SECTOR_CONICAL": - return ScanCharacteristicsScanTypeScanTypeSectorConical, nil - case "SCAN_TYPE_AGILE_BEAM": - return ScanCharacteristicsScanTypeScanTypeAgileBeam, nil - case "SCAN_TYPE_UNIDIRECTIONAL_VERTICAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeUnidirectionalVerticalSector, nil - case "SCAN_TYPE_UNIDIRECTIONAL_HORIZONTAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeUnidirectionalHorizontalSector, nil - case "SCAN_TYPE_UNIDIRECTIONAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeUnidirectionalSector, nil - case "SCAN_TYPE_BIDIRECTIONAL_SECTOR": - return ScanCharacteristicsScanTypeScanTypeBidirectionalSector, nil - } - var t ScanCharacteristicsScanType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (s ScanCharacteristicsScanType) Ptr() *ScanCharacteristicsScanType { - return &s -} - -// A Schedule associated with this entity -type Schedule struct { - // expression that represents this schedule's "ON" state - Windows []*CronWindow `json:"windows,omitempty" url:"windows,omitempty"` - // A unique identifier for this schedule. - ScheduleID *string `json:"scheduleId,omitempty" url:"scheduleId,omitempty"` - // The schedule type - ScheduleType *ScheduleScheduleType `json:"scheduleType,omitempty" url:"scheduleType,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Schedule) GetWindows() []*CronWindow { - if s == nil { - return nil - } - return s.Windows -} - -func (s *Schedule) GetScheduleID() *string { - if s == nil { - return nil - } - return s.ScheduleID -} - -func (s *Schedule) GetScheduleType() *ScheduleScheduleType { - if s == nil { - return nil - } - return s.ScheduleType -} - -func (s *Schedule) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Schedule) UnmarshalJSON(data []byte) error { - type unmarshaler Schedule - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = Schedule(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Schedule) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// The schedule type -type ScheduleScheduleType string - -const ( - ScheduleScheduleTypeScheduleTypeInvalid ScheduleScheduleType = "SCHEDULE_TYPE_INVALID" - ScheduleScheduleTypeScheduleTypeZoneEnabled ScheduleScheduleType = "SCHEDULE_TYPE_ZONE_ENABLED" - ScheduleScheduleTypeScheduleTypeZoneTempEnabled ScheduleScheduleType = "SCHEDULE_TYPE_ZONE_TEMP_ENABLED" -) - -func NewScheduleScheduleTypeFromString(s string) (ScheduleScheduleType, error) { - switch s { - case "SCHEDULE_TYPE_INVALID": - return ScheduleScheduleTypeScheduleTypeInvalid, nil - case "SCHEDULE_TYPE_ZONE_ENABLED": - return ScheduleScheduleTypeScheduleTypeZoneEnabled, nil - case "SCHEDULE_TYPE_ZONE_TEMP_ENABLED": - return ScheduleScheduleTypeScheduleTypeZoneTempEnabled, nil - } - var t ScheduleScheduleType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (s ScheduleScheduleType) Ptr() *ScheduleScheduleType { - return &s -} - -// Schedules associated with this entity -type Schedules struct { - Schedules []*Schedule `json:"schedules,omitempty" url:"schedules,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Schedules) GetSchedules() []*Schedule { - if s == nil { - return nil - } - return s.Schedules -} - -func (s *Schedules) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Schedules) UnmarshalJSON(data []byte) error { - type unmarshaler Schedules - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = Schedules(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Schedules) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -type SecondaryCorrelation struct { - // The primary of this correlation. - PrimaryEntityID *string `json:"primaryEntityId,omitempty" url:"primaryEntityId,omitempty"` - // Metadata about the correlation. - Metadata *CorrelationMetadata `json:"metadata,omitempty" url:"metadata,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *SecondaryCorrelation) GetPrimaryEntityID() *string { - if s == nil { - return nil - } - return s.PrimaryEntityID -} - -func (s *SecondaryCorrelation) GetMetadata() *CorrelationMetadata { - if s == nil { - return nil - } - return s.Metadata -} - -func (s *SecondaryCorrelation) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *SecondaryCorrelation) UnmarshalJSON(data []byte) error { - type unmarshaler SecondaryCorrelation - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = SecondaryCorrelation(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *SecondaryCorrelation) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// Individual sensor configuration. -type Sensor struct { - // This generally is used to indicate a specific type at a more detailed granularity. E.g. COMInt or LWIR - SensorID *string `json:"sensorId,omitempty" url:"sensorId,omitempty"` - OperationalState *SensorOperationalState `json:"operationalState,omitempty" url:"operationalState,omitempty"` - // The type of sensor - SensorType *SensorSensorType `json:"sensorType,omitempty" url:"sensorType,omitempty"` - // A human readable description of the sensor - SensorDescription *string `json:"sensorDescription,omitempty" url:"sensorDescription,omitempty"` - // RF configuration details of the sensor - RfConfiguraton *RfConfiguration `json:"rfConfiguraton,omitempty" url:"rfConfiguraton,omitempty"` - // Time of the latest detection from the sensor - LastDetectionTimestamp *time.Time `json:"lastDetectionTimestamp,omitempty" url:"lastDetectionTimestamp,omitempty"` - // Multiple fields of view for a single sensor component - FieldsOfView []*FieldOfView `json:"fieldsOfView,omitempty" url:"fieldsOfView,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Sensor) GetSensorID() *string { - if s == nil { - return nil - } - return s.SensorID -} - -func (s *Sensor) GetOperationalState() *SensorOperationalState { - if s == nil { - return nil - } - return s.OperationalState -} - -func (s *Sensor) GetSensorType() *SensorSensorType { - if s == nil { - return nil - } - return s.SensorType -} - -func (s *Sensor) GetSensorDescription() *string { - if s == nil { - return nil - } - return s.SensorDescription -} - -func (s *Sensor) GetRfConfiguraton() *RfConfiguration { - if s == nil { - return nil - } - return s.RfConfiguraton -} - -func (s *Sensor) GetLastDetectionTimestamp() *time.Time { - if s == nil { - return nil - } - return s.LastDetectionTimestamp -} - -func (s *Sensor) GetFieldsOfView() []*FieldOfView { - if s == nil { - return nil - } - return s.FieldsOfView -} - -func (s *Sensor) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Sensor) UnmarshalJSON(data []byte) error { - type embed Sensor - var unmarshaler = struct { - embed - LastDetectionTimestamp *internal.DateTime `json:"lastDetectionTimestamp,omitempty"` - }{ - embed: embed(*s), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *s = Sensor(unmarshaler.embed) - s.LastDetectionTimestamp = unmarshaler.LastDetectionTimestamp.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Sensor) MarshalJSON() ([]byte, error) { - type embed Sensor - var marshaler = struct { - embed - LastDetectionTimestamp *internal.DateTime `json:"lastDetectionTimestamp,omitempty"` - }{ - embed: embed(*s), - LastDetectionTimestamp: internal.NewOptionalDateTime(s.LastDetectionTimestamp), - } - return json.Marshal(marshaler) -} - -func (s *Sensor) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -type SensorOperationalState string - -const ( - SensorOperationalStateOperationalStateInvalid SensorOperationalState = "OPERATIONAL_STATE_INVALID" - SensorOperationalStateOperationalStateOff SensorOperationalState = "OPERATIONAL_STATE_OFF" - SensorOperationalStateOperationalStateNonOperational SensorOperationalState = "OPERATIONAL_STATE_NON_OPERATIONAL" - SensorOperationalStateOperationalStateDegraded SensorOperationalState = "OPERATIONAL_STATE_DEGRADED" - SensorOperationalStateOperationalStateOperational SensorOperationalState = "OPERATIONAL_STATE_OPERATIONAL" - SensorOperationalStateOperationalStateDenied SensorOperationalState = "OPERATIONAL_STATE_DENIED" -) - -func NewSensorOperationalStateFromString(s string) (SensorOperationalState, error) { - switch s { - case "OPERATIONAL_STATE_INVALID": - return SensorOperationalStateOperationalStateInvalid, nil - case "OPERATIONAL_STATE_OFF": - return SensorOperationalStateOperationalStateOff, nil - case "OPERATIONAL_STATE_NON_OPERATIONAL": - return SensorOperationalStateOperationalStateNonOperational, nil - case "OPERATIONAL_STATE_DEGRADED": - return SensorOperationalStateOperationalStateDegraded, nil - case "OPERATIONAL_STATE_OPERATIONAL": - return SensorOperationalStateOperationalStateOperational, nil - case "OPERATIONAL_STATE_DENIED": - return SensorOperationalStateOperationalStateDenied, nil - } - var t SensorOperationalState - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (s SensorOperationalState) Ptr() *SensorOperationalState { - return &s -} - -// The type of sensor -type SensorSensorType string - -const ( - SensorSensorTypeSensorTypeInvalid SensorSensorType = "SENSOR_TYPE_INVALID" - SensorSensorTypeSensorTypeRadar SensorSensorType = "SENSOR_TYPE_RADAR" - SensorSensorTypeSensorTypeCamera SensorSensorType = "SENSOR_TYPE_CAMERA" - SensorSensorTypeSensorTypeTransponder SensorSensorType = "SENSOR_TYPE_TRANSPONDER" - SensorSensorTypeSensorTypeRf SensorSensorType = "SENSOR_TYPE_RF" - SensorSensorTypeSensorTypeGps SensorSensorType = "SENSOR_TYPE_GPS" - SensorSensorTypeSensorTypePtuPos SensorSensorType = "SENSOR_TYPE_PTU_POS" - SensorSensorTypeSensorTypePerimeter SensorSensorType = "SENSOR_TYPE_PERIMETER" - SensorSensorTypeSensorTypeSonar SensorSensorType = "SENSOR_TYPE_SONAR" -) - -func NewSensorSensorTypeFromString(s string) (SensorSensorType, error) { - switch s { - case "SENSOR_TYPE_INVALID": - return SensorSensorTypeSensorTypeInvalid, nil - case "SENSOR_TYPE_RADAR": - return SensorSensorTypeSensorTypeRadar, nil - case "SENSOR_TYPE_CAMERA": - return SensorSensorTypeSensorTypeCamera, nil - case "SENSOR_TYPE_TRANSPONDER": - return SensorSensorTypeSensorTypeTransponder, nil - case "SENSOR_TYPE_RF": - return SensorSensorTypeSensorTypeRf, nil - case "SENSOR_TYPE_GPS": - return SensorSensorTypeSensorTypeGps, nil - case "SENSOR_TYPE_PTU_POS": - return SensorSensorTypeSensorTypePtuPos, nil - case "SENSOR_TYPE_PERIMETER": - return SensorSensorTypeSensorTypePerimeter, nil - case "SENSOR_TYPE_SONAR": - return SensorSensorTypeSensorTypeSonar, nil - } - var t SensorSensorType - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (s SensorSensorType) Ptr() *SensorSensorType { - return &s -} - -// List of sensors available for an entity. -type Sensors struct { - Sensors []*Sensor `json:"sensors,omitempty" url:"sensors,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Sensors) GetSensors() []*Sensor { - if s == nil { - return nil - } - return s.Sensors -} - -func (s *Sensors) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Sensors) UnmarshalJSON(data []byte) error { - type unmarshaler Sensors - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = Sensors(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Sensors) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// A component that describes an entity's signal characteristics. -type Signal struct { - FrequencyCenter *Frequency `json:"frequencyCenter,omitempty" url:"frequencyCenter,omitempty"` - FrequencyRange *FrequencyRange `json:"frequencyRange,omitempty" url:"frequencyRange,omitempty"` - // Indicates the bandwidth of a signal (Hz). - BandwidthHz *float64 `json:"bandwidthHz,omitempty" url:"bandwidthHz,omitempty"` - // Indicates the signal to noise (SNR) of this signal. - SignalToNoiseRatio *float64 `json:"signalToNoiseRatio,omitempty" url:"signalToNoiseRatio,omitempty"` - LineOfBearing *LineOfBearing `json:"lineOfBearing,omitempty" url:"lineOfBearing,omitempty"` - Fixed *Fixed `json:"fixed,omitempty" url:"fixed,omitempty"` - // Emitter notations associated with this entity. - EmitterNotations []*EmitterNotation `json:"emitterNotations,omitempty" url:"emitterNotations,omitempty"` - // length in time of a single pulse - PulseWidthS *float64 `json:"pulseWidthS,omitempty" url:"pulseWidthS,omitempty"` - // length in time between the start of two pulses - PulseRepetitionInterval *PulseRepetitionInterval `json:"pulseRepetitionInterval,omitempty" url:"pulseRepetitionInterval,omitempty"` - // describes how a signal is observing the environment - ScanCharacteristics *ScanCharacteristics `json:"scanCharacteristics,omitempty" url:"scanCharacteristics,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Signal) GetFrequencyCenter() *Frequency { - if s == nil { - return nil - } - return s.FrequencyCenter -} - -func (s *Signal) GetFrequencyRange() *FrequencyRange { - if s == nil { - return nil - } - return s.FrequencyRange -} - -func (s *Signal) GetBandwidthHz() *float64 { - if s == nil { - return nil - } - return s.BandwidthHz -} - -func (s *Signal) GetSignalToNoiseRatio() *float64 { - if s == nil { - return nil - } - return s.SignalToNoiseRatio -} - -func (s *Signal) GetLineOfBearing() *LineOfBearing { - if s == nil { - return nil - } - return s.LineOfBearing -} - -func (s *Signal) GetFixed() *Fixed { - if s == nil { - return nil - } - return s.Fixed -} - -func (s *Signal) GetEmitterNotations() []*EmitterNotation { - if s == nil { - return nil - } - return s.EmitterNotations -} - -func (s *Signal) GetPulseWidthS() *float64 { - if s == nil { - return nil - } - return s.PulseWidthS -} - -func (s *Signal) GetPulseRepetitionInterval() *PulseRepetitionInterval { - if s == nil { - return nil - } - return s.PulseRepetitionInterval -} - -func (s *Signal) GetScanCharacteristics() *ScanCharacteristics { - if s == nil { - return nil - } - return s.ScanCharacteristics -} - -func (s *Signal) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Signal) UnmarshalJSON(data []byte) error { - type unmarshaler Signal - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = Signal(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Signal) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). -type Status struct { - // The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code]. - Code *int `json:"code,omitempty" url:"code,omitempty"` - // A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client. - Message *string `json:"message,omitempty" url:"message,omitempty"` - // A list of messages that carry the error details. There is a common set of message types for APIs to use. - Details []*GoogleProtobufAny `json:"details,omitempty" url:"details,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Status) GetCode() *int { - if s == nil { - return nil - } - return s.Code -} - -func (s *Status) GetMessage() *string { - if s == nil { - return nil - } - return s.Message -} - -func (s *Status) GetDetails() []*GoogleProtobufAny { - if s == nil { - return nil - } - return s.Details -} - -func (s *Status) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Status) UnmarshalJSON(data []byte) error { - type unmarshaler Status - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = Status(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Status) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// Represents the state of supplies associated with an entity (available but not in condition to use immediately) -type Supplies struct { - Fuel []*Fuel `json:"fuel,omitempty" url:"fuel,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (s *Supplies) GetFuel() []*Fuel { - if s == nil { - return nil - } - return s.Fuel -} - -func (s *Supplies) GetExtraProperties() map[string]interface{} { - return s.extraProperties -} - -func (s *Supplies) UnmarshalJSON(data []byte) error { - type unmarshaler Supplies - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *s = Supplies(value) - extraProperties, err := internal.ExtractExtraProperties(data, *s) - if err != nil { - return err - } - s.extraProperties = extraProperties - s.rawJSON = json.RawMessage(data) - return nil -} - -func (s *Supplies) String() string { - if len(s.rawJSON) > 0 { - if value, err := internal.StringifyJSON(s.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(s); err == nil { - return value - } - return fmt.Sprintf("%#v", s) -} - -// symmetric 2d matrix only representing the upper right triangle, useful for -// -// covariance matrices -type TMat2 struct { - Mxx *float64 `json:"mxx,omitempty" url:"mxx,omitempty"` - Mxy *float64 `json:"mxy,omitempty" url:"mxy,omitempty"` - Myy *float64 `json:"myy,omitempty" url:"myy,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TMat2) GetMxx() *float64 { - if t == nil { - return nil - } - return t.Mxx -} - -func (t *TMat2) GetMxy() *float64 { - if t == nil { - return nil - } - return t.Mxy -} - -func (t *TMat2) GetMyy() *float64 { - if t == nil { - return nil - } - return t.Myy -} - -func (t *TMat2) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TMat2) UnmarshalJSON(data []byte) error { - type unmarshaler TMat2 - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TMat2(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TMat2) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Symmetric 3d matrix only representing the upper right triangle. -type TMat3 struct { - Mxx *float64 `json:"mxx,omitempty" url:"mxx,omitempty"` - Mxy *float64 `json:"mxy,omitempty" url:"mxy,omitempty"` - Mxz *float64 `json:"mxz,omitempty" url:"mxz,omitempty"` - Myy *float64 `json:"myy,omitempty" url:"myy,omitempty"` - Myz *float64 `json:"myz,omitempty" url:"myz,omitempty"` - Mzz *float64 `json:"mzz,omitempty" url:"mzz,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TMat3) GetMxx() *float64 { - if t == nil { - return nil - } - return t.Mxx -} - -func (t *TMat3) GetMxy() *float64 { - if t == nil { - return nil - } - return t.Mxy -} - -func (t *TMat3) GetMxz() *float64 { - if t == nil { - return nil - } - return t.Mxz -} - -func (t *TMat3) GetMyy() *float64 { - if t == nil { - return nil - } - return t.Myy -} - -func (t *TMat3) GetMyz() *float64 { - if t == nil { - return nil - } - return t.Myz -} - -func (t *TMat3) GetMzz() *float64 { - if t == nil { - return nil - } - return t.Mzz -} - -func (t *TMat3) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TMat3) UnmarshalJSON(data []byte) error { - type unmarshaler TMat3 - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TMat3(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TMat3) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// The target prioritization associated with an entity. -type TargetPriority struct { - // Describes the target priority in relation to high value target lists. - HighValueTarget *HighValueTarget `json:"highValueTarget,omitempty" url:"highValueTarget,omitempty"` - // Describes whether the entity should be treated as a threat - Threat *Threat `json:"threat,omitempty" url:"threat,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TargetPriority) GetHighValueTarget() *HighValueTarget { - if t == nil { - return nil - } - return t.HighValueTarget -} - -func (t *TargetPriority) GetThreat() *Threat { - if t == nil { - return nil - } - return t.Threat -} - -func (t *TargetPriority) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TargetPriority) UnmarshalJSON(data []byte) error { - type unmarshaler TargetPriority - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TargetPriority(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TargetPriority) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Catalog of supported tasks. -type TaskCatalog struct { - TaskDefinitions []*TaskDefinition `json:"taskDefinitions,omitempty" url:"taskDefinitions,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskCatalog) GetTaskDefinitions() []*TaskDefinition { - if t == nil { - return nil - } - return t.TaskDefinitions -} - -func (t *TaskCatalog) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskCatalog) UnmarshalJSON(data []byte) error { - type unmarshaler TaskCatalog - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskCatalog(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskCatalog) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Defines a supported task by the task specification URL of its "Any" type. -type TaskDefinition struct { - // Url path must be prefixed with `type.googleapis.com/`. - TaskSpecificationURL *string `json:"taskSpecificationUrl,omitempty" url:"taskSpecificationUrl,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TaskDefinition) GetTaskSpecificationURL() *string { - if t == nil { - return nil - } - return t.TaskSpecificationURL -} - -func (t *TaskDefinition) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TaskDefinition) UnmarshalJSON(data []byte) error { - type unmarshaler TaskDefinition - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TaskDefinition(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TaskDefinition) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Represents a team of agents -type Team struct { - // Entity ID of the team - EntityID *string `json:"entityId,omitempty" url:"entityId,omitempty"` - Members []*Agent `json:"members,omitempty" url:"members,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *Team) GetEntityID() *string { - if t == nil { - return nil - } - return t.EntityID -} - -func (t *Team) GetMembers() []*Agent { - if t == nil { - return nil - } - return t.Members -} - -func (t *Team) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *Team) UnmarshalJSON(data []byte) error { - type unmarshaler Team - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = Team(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *Team) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Describes whether an entity is a threat or not. -type Threat struct { - // Indicates that the entity has been determined to be a threat. - IsThreat *bool `json:"isThreat,omitempty" url:"isThreat,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *Threat) GetIsThreat() *bool { - if t == nil { - return nil - } - return t.IsThreat -} - -func (t *Threat) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *Threat) UnmarshalJSON(data []byte) error { - type unmarshaler Threat - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = Threat(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *Threat) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// The datetime string in ISO 8601 format. -type Timestamp = string - -type TleParameters struct { - // Integer specifying TLE ephemeris type - EphemerisType *int `json:"ephemerisType,omitempty" url:"ephemerisType,omitempty"` - // User-defined free-text message classification/caveats of this TLE - ClassificationType *string `json:"classificationType,omitempty" url:"classificationType,omitempty"` - // Norad catalog number: integer up to nine digits. - NoradCatID *int `json:"noradCatId,omitempty" url:"noradCatId,omitempty"` - ElementSetNo *int `json:"elementSetNo,omitempty" url:"elementSetNo,omitempty"` - // Optional: revolution number - RevAtEpoch *int `json:"revAtEpoch,omitempty" url:"revAtEpoch,omitempty"` - // Drag parameter for SGP-4 in units 1 / Earth radii - Bstar *float64 `json:"bstar,omitempty" url:"bstar,omitempty"` - // Drag parameter for SGP4-XP in units m^2 / kg - Bterm *float64 `json:"bterm,omitempty" url:"bterm,omitempty"` - // First time derivative of mean motion in rev / day^2 - MeanMotionDot *float64 `json:"meanMotionDot,omitempty" url:"meanMotionDot,omitempty"` - // Second time derivative of mean motion in rev / day^3. For use with SGP or PPT3. - MeanMotionDdot *float64 `json:"meanMotionDdot,omitempty" url:"meanMotionDdot,omitempty"` - // Solar radiation pressure coefficient A_gamma / m in m^2 / kg. For use with SGP4-XP. - Agom *float64 `json:"agom,omitempty" url:"agom,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TleParameters) GetEphemerisType() *int { - if t == nil { - return nil - } - return t.EphemerisType -} - -func (t *TleParameters) GetClassificationType() *string { - if t == nil { - return nil - } - return t.ClassificationType -} - -func (t *TleParameters) GetNoradCatID() *int { - if t == nil { - return nil - } - return t.NoradCatID -} - -func (t *TleParameters) GetElementSetNo() *int { - if t == nil { - return nil - } - return t.ElementSetNo -} - -func (t *TleParameters) GetRevAtEpoch() *int { - if t == nil { - return nil - } - return t.RevAtEpoch -} - -func (t *TleParameters) GetBstar() *float64 { - if t == nil { - return nil - } - return t.Bstar -} - -func (t *TleParameters) GetBterm() *float64 { - if t == nil { - return nil - } - return t.Bterm -} - -func (t *TleParameters) GetMeanMotionDot() *float64 { - if t == nil { - return nil - } - return t.MeanMotionDot -} - -func (t *TleParameters) GetMeanMotionDdot() *float64 { - if t == nil { - return nil - } - return t.MeanMotionDdot -} - -func (t *TleParameters) GetAgom() *float64 { - if t == nil { - return nil - } - return t.Agom -} - -func (t *TleParameters) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TleParameters) UnmarshalJSON(data []byte) error { - type unmarshaler TleParameters - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TleParameters(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TleParameters) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Available for Entities that are tracked. -type Tracked struct { - // Quality score, 0-15, nil if none - TrackQualityWrapper *int `json:"trackQualityWrapper,omitempty" url:"trackQualityWrapper,omitempty"` - // Sensor hits aggregation on the tracked entity. - SensorHits *int `json:"sensorHits,omitempty" url:"sensorHits,omitempty"` - // Estimated number of objects or units that are represented by this entity. Known as Strength in certain contexts (Link16) - // - // if UpperBound == LowerBound; (strength = LowerBound) - // If both UpperBound and LowerBound are defined; strength is between LowerBound and UpperBound (represented as string "Strength: 4-5") - // If UpperBound is defined only (LowerBound unset), Strength ≤ UpperBound - // If LowerBound is defined only (UpperBound unset), LowerBound ≤ Strength - // 0 indicates unset. - NumberOfObjects *UInt32Range `json:"numberOfObjects,omitempty" url:"numberOfObjects,omitempty"` - // The radar cross section (RCS) is a measure of how detectable an object is by radar. A large RCS indicates an object is more easily - // - // detected. The unit is “decibels per square meter,” or dBsm - RadarCrossSection *float64 `json:"radarCrossSection,omitempty" url:"radarCrossSection,omitempty"` - // Timestamp of the latest tracking measurement for this entity. - LastMeasurementTime *time.Time `json:"lastMeasurementTime,omitempty" url:"lastMeasurementTime,omitempty"` - // The relative position of a track with respect to the entity that is tracking it. Used for tracks that do not yet have a 3D position. - // - // For this entity (A), being tracked by some entity (B), this LineOfBearing would express a ray from B to A. - LineOfBearing *LineOfBearing `json:"lineOfBearing,omitempty" url:"lineOfBearing,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *Tracked) GetTrackQualityWrapper() *int { - if t == nil { - return nil - } - return t.TrackQualityWrapper -} - -func (t *Tracked) GetSensorHits() *int { - if t == nil { - return nil - } - return t.SensorHits -} - -func (t *Tracked) GetNumberOfObjects() *UInt32Range { - if t == nil { - return nil - } - return t.NumberOfObjects -} - -func (t *Tracked) GetRadarCrossSection() *float64 { - if t == nil { - return nil - } - return t.RadarCrossSection -} - -func (t *Tracked) GetLastMeasurementTime() *time.Time { - if t == nil { - return nil - } - return t.LastMeasurementTime -} - -func (t *Tracked) GetLineOfBearing() *LineOfBearing { - if t == nil { - return nil - } - return t.LineOfBearing -} - -func (t *Tracked) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *Tracked) UnmarshalJSON(data []byte) error { - type embed Tracked - var unmarshaler = struct { - embed - LastMeasurementTime *internal.DateTime `json:"lastMeasurementTime,omitempty"` - }{ - embed: embed(*t), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *t = Tracked(unmarshaler.embed) - t.LastMeasurementTime = unmarshaler.LastMeasurementTime.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *Tracked) MarshalJSON() ([]byte, error) { - type embed Tracked - var marshaler = struct { - embed - LastMeasurementTime *internal.DateTime `json:"lastMeasurementTime,omitempty"` - }{ - embed: embed(*t), - LastMeasurementTime: internal.NewOptionalDateTime(t.LastMeasurementTime), - } - return json.Marshal(marshaler) -} - -func (t *Tracked) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// Describes the relationship between the entity being tracked ("tracked entity") and the entity that is -// -// performing the tracking ("tracking entity"). -type TrackedBy struct { - // Sensor details of the tracking entity's sensors that were active and tracking the tracked entity. This may be - // - // a subset of the total sensors available on the tracking entity. - ActivelyTrackingSensors *Sensors `json:"activelyTrackingSensors,omitempty" url:"activelyTrackingSensors,omitempty"` - // Latest time that any sensor in actively_tracking_sensors detected the tracked entity. - LastMeasurementTimestamp *time.Time `json:"lastMeasurementTimestamp,omitempty" url:"lastMeasurementTimestamp,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TrackedBy) GetActivelyTrackingSensors() *Sensors { - if t == nil { - return nil - } - return t.ActivelyTrackingSensors -} - -func (t *TrackedBy) GetLastMeasurementTimestamp() *time.Time { - if t == nil { - return nil - } - return t.LastMeasurementTimestamp -} - -func (t *TrackedBy) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TrackedBy) UnmarshalJSON(data []byte) error { - type embed TrackedBy - var unmarshaler = struct { - embed - LastMeasurementTimestamp *internal.DateTime `json:"lastMeasurementTimestamp,omitempty"` - }{ - embed: embed(*t), - } - if err := json.Unmarshal(data, &unmarshaler); err != nil { - return err - } - *t = TrackedBy(unmarshaler.embed) - t.LastMeasurementTimestamp = unmarshaler.LastMeasurementTimestamp.TimePtr() - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TrackedBy) MarshalJSON() ([]byte, error) { - type embed TrackedBy - var marshaler = struct { - embed - LastMeasurementTimestamp *internal.DateTime `json:"lastMeasurementTimestamp,omitempty"` - }{ - embed: embed(*t), - LastMeasurementTimestamp: internal.NewOptionalDateTime(t.LastMeasurementTimestamp), - } - return json.Marshal(marshaler) -} - -func (t *TrackedBy) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// A message describing any transponder codes associated with Mode 1, 2, 3, 4, 5, S interrogations. -type TransponderCodes struct { - // The mode 1 code assigned to military assets. - Mode1 *int `json:"mode1,omitempty" url:"mode1,omitempty"` - // The Mode 2 code assigned to military assets. - Mode2 *int `json:"mode2,omitempty" url:"mode2,omitempty"` - // The Mode 3 code assigned by ATC to the asset. - Mode3 *int `json:"mode3,omitempty" url:"mode3,omitempty"` - // The validity of the response from the Mode 4 interrogation. - Mode4InterrogationResponse *TransponderCodesMode4InterrogationResponse `json:"mode4InterrogationResponse,omitempty" url:"mode4InterrogationResponse,omitempty"` - // The Mode 5 transponder codes. - Mode5 *Mode5 `json:"mode5,omitempty" url:"mode5,omitempty"` - // The Mode S transponder codes. - ModeS *ModeS `json:"modeS,omitempty" url:"modeS,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (t *TransponderCodes) GetMode1() *int { - if t == nil { - return nil - } - return t.Mode1 -} - -func (t *TransponderCodes) GetMode2() *int { - if t == nil { - return nil - } - return t.Mode2 -} - -func (t *TransponderCodes) GetMode3() *int { - if t == nil { - return nil - } - return t.Mode3 -} - -func (t *TransponderCodes) GetMode4InterrogationResponse() *TransponderCodesMode4InterrogationResponse { - if t == nil { - return nil - } - return t.Mode4InterrogationResponse -} - -func (t *TransponderCodes) GetMode5() *Mode5 { - if t == nil { - return nil - } - return t.Mode5 -} - -func (t *TransponderCodes) GetModeS() *ModeS { - if t == nil { - return nil - } - return t.ModeS -} - -func (t *TransponderCodes) GetExtraProperties() map[string]interface{} { - return t.extraProperties -} - -func (t *TransponderCodes) UnmarshalJSON(data []byte) error { - type unmarshaler TransponderCodes - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *t = TransponderCodes(value) - extraProperties, err := internal.ExtractExtraProperties(data, *t) - if err != nil { - return err - } - t.extraProperties = extraProperties - t.rawJSON = json.RawMessage(data) - return nil -} - -func (t *TransponderCodes) String() string { - if len(t.rawJSON) > 0 { - if value, err := internal.StringifyJSON(t.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(t); err == nil { - return value - } - return fmt.Sprintf("%#v", t) -} - -// The validity of the response from the Mode 4 interrogation. -type TransponderCodesMode4InterrogationResponse string - -const ( - TransponderCodesMode4InterrogationResponseInterrogationResponseInvalid TransponderCodesMode4InterrogationResponse = "INTERROGATION_RESPONSE_INVALID" - TransponderCodesMode4InterrogationResponseInterrogationResponseCorrect TransponderCodesMode4InterrogationResponse = "INTERROGATION_RESPONSE_CORRECT" - TransponderCodesMode4InterrogationResponseInterrogationResponseIncorrect TransponderCodesMode4InterrogationResponse = "INTERROGATION_RESPONSE_INCORRECT" - TransponderCodesMode4InterrogationResponseInterrogationResponseNoResponse TransponderCodesMode4InterrogationResponse = "INTERROGATION_RESPONSE_NO_RESPONSE" -) - -func NewTransponderCodesMode4InterrogationResponseFromString(s string) (TransponderCodesMode4InterrogationResponse, error) { - switch s { - case "INTERROGATION_RESPONSE_INVALID": - return TransponderCodesMode4InterrogationResponseInterrogationResponseInvalid, nil - case "INTERROGATION_RESPONSE_CORRECT": - return TransponderCodesMode4InterrogationResponseInterrogationResponseCorrect, nil - case "INTERROGATION_RESPONSE_INCORRECT": - return TransponderCodesMode4InterrogationResponseInterrogationResponseIncorrect, nil - case "INTERROGATION_RESPONSE_NO_RESPONSE": - return TransponderCodesMode4InterrogationResponseInterrogationResponseNoResponse, nil - } - var t TransponderCodesMode4InterrogationResponse - return "", fmt.Errorf("%s is not a valid %T", s, t) -} - -func (t TransponderCodesMode4InterrogationResponse) Ptr() *TransponderCodesMode4InterrogationResponse { - return &t -} - -type UInt32Range struct { - LowerBound *int `json:"lowerBound,omitempty" url:"lowerBound,omitempty"` - UpperBound *int `json:"upperBound,omitempty" url:"upperBound,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (u *UInt32Range) GetLowerBound() *int { - if u == nil { - return nil - } - return u.LowerBound -} - -func (u *UInt32Range) GetUpperBound() *int { - if u == nil { - return nil - } - return u.UpperBound -} - -func (u *UInt32Range) GetExtraProperties() map[string]interface{} { - return u.extraProperties -} - -func (u *UInt32Range) UnmarshalJSON(data []byte) error { - type unmarshaler UInt32Range - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *u = UInt32Range(value) - extraProperties, err := internal.ExtractExtraProperties(data, *u) - if err != nil { - return err - } - u.extraProperties = extraProperties - u.rawJSON = json.RawMessage(data) - return nil -} - -func (u *UInt32Range) String() string { - if len(u.rawJSON) > 0 { - if value, err := internal.StringifyJSON(u.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(u); err == nil { - return value - } - return fmt.Sprintf("%#v", u) -} - -// Visual details associated with the display of an entity in the client. -type VisualDetails struct { - // The range rings to display around an entity. - RangeRings *RangeRings `json:"rangeRings,omitempty" url:"rangeRings,omitempty"` - - extraProperties map[string]interface{} - rawJSON json.RawMessage -} - -func (v *VisualDetails) GetRangeRings() *RangeRings { - if v == nil { - return nil - } - return v.RangeRings -} - -func (v *VisualDetails) GetExtraProperties() map[string]interface{} { - return v.extraProperties -} - -func (v *VisualDetails) UnmarshalJSON(data []byte) error { - type unmarshaler VisualDetails - var value unmarshaler - if err := json.Unmarshal(data, &value); err != nil { - return err - } - *v = VisualDetails(value) - extraProperties, err := internal.ExtractExtraProperties(data, *v) - if err != nil { - return err - } - v.extraProperties = extraProperties - v.rawJSON = json.RawMessage(data) - return nil -} - -func (v *VisualDetails) String() string { - if len(v.rawJSON) > 0 { - if value, err := internal.StringifyJSON(v.rawJSON); err == nil { - return value - } - } - if value, err := internal.StringifyJSON(v); err == nil { - return value - } - return fmt.Sprintf("%#v", v) -} diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md deleted file mode 100644 index 7ec5ac7..0000000 --- a/vendor/github.com/google/uuid/CHANGELOG.md +++ /dev/null @@ -1,41 +0,0 @@ -# Changelog - -## [1.6.0](https://github.com/google/uuid/compare/v1.5.0...v1.6.0) (2024-01-16) - - -### Features - -* add Max UUID constant ([#149](https://github.com/google/uuid/issues/149)) ([c58770e](https://github.com/google/uuid/commit/c58770eb495f55fe2ced6284f93c5158a62e53e3)) - - -### Bug Fixes - -* fix typo in version 7 uuid documentation ([#153](https://github.com/google/uuid/issues/153)) ([016b199](https://github.com/google/uuid/commit/016b199544692f745ffc8867b914129ecb47ef06)) -* Monotonicity in UUIDv7 ([#150](https://github.com/google/uuid/issues/150)) ([a2b2b32](https://github.com/google/uuid/commit/a2b2b32373ff0b1a312b7fdf6d38a977099698a6)) - -## [1.5.0](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) (2023-12-12) - - -### Features - -* Validate UUID without creating new UUID ([#141](https://github.com/google/uuid/issues/141)) ([9ee7366](https://github.com/google/uuid/commit/9ee7366e66c9ad96bab89139418a713dc584ae29)) - -## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) - - -### Features - -* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) - -### Fixes - -* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) - -## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) - - -### Bug Fixes - -* Use .EqualFold() to parse urn prefixed UUIDs ([#118](https://github.com/google/uuid/issues/118)) ([574e687](https://github.com/google/uuid/commit/574e6874943741fb99d41764c705173ada5293f0)) - -## Changelog diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md deleted file mode 100644 index a502fdc..0000000 --- a/vendor/github.com/google/uuid/CONTRIBUTING.md +++ /dev/null @@ -1,26 +0,0 @@ -# How to contribute - -We definitely welcome patches and contribution to this project! - -### Tips - -Commits must be formatted according to the [Conventional Commits Specification](https://www.conventionalcommits.org). - -Always try to include a test case! If it is not possible or not necessary, -please explain why in the pull request description. - -### Releasing - -Commits that would precipitate a SemVer change, as described in the Conventional -Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) -to create a release candidate pull request. Once submitted, `release-please` -will create a release. - -For tips on how to work with `release-please`, see its documentation. - -### Legal requirements - -In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://cla.developers.google.com/clas). - -You may have already signed it for other Google projects. diff --git a/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/google/uuid/CONTRIBUTORS deleted file mode 100644 index b4bb97f..0000000 --- a/vendor/github.com/google/uuid/CONTRIBUTORS +++ /dev/null @@ -1,9 +0,0 @@ -Paul Borman -bmatsuo -shawnps -theory -jboverfelt -dsymonds -cd1 -wallclockbuilder -dansouza diff --git a/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/google/uuid/LICENSE deleted file mode 100644 index 5dc6826..0000000 --- a/vendor/github.com/google/uuid/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009,2014 Google Inc. 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/google/uuid/README.md b/vendor/github.com/google/uuid/README.md deleted file mode 100644 index 3e9a618..0000000 --- a/vendor/github.com/google/uuid/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# uuid -The uuid package generates and inspects UUIDs based on -[RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) -and DCE 1.1: Authentication and Security Services. - -This package is based on the github.com/pborman/uuid package (previously named -code.google.com/p/go-uuid). It differs from these earlier packages in that -a UUID is a 16 byte array rather than a byte slice. One loss due to this -change is the ability to represent an invalid UUID (vs a NIL UUID). - -###### Install -```sh -go get github.com/google/uuid -``` - -###### Documentation -[![Go Reference](https://pkg.go.dev/badge/github.com/google/uuid.svg)](https://pkg.go.dev/github.com/google/uuid) - -Full `go doc` style documentation for the package can be viewed online without -installing this package by using the GoDoc site here: -http://pkg.go.dev/github.com/google/uuid diff --git a/vendor/github.com/google/uuid/dce.go b/vendor/github.com/google/uuid/dce.go deleted file mode 100644 index fa820b9..0000000 --- a/vendor/github.com/google/uuid/dce.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "fmt" - "os" -) - -// A Domain represents a Version 2 domain -type Domain byte - -// Domain constants for DCE Security (Version 2) UUIDs. -const ( - Person = Domain(0) - Group = Domain(1) - Org = Domain(2) -) - -// NewDCESecurity returns a DCE Security (Version 2) UUID. -// -// The domain should be one of Person, Group or Org. -// On a POSIX system the id should be the users UID for the Person -// domain and the users GID for the Group. The meaning of id for -// the domain Org or on non-POSIX systems is site defined. -// -// For a given domain/id pair the same token may be returned for up to -// 7 minutes and 10 seconds. -func NewDCESecurity(domain Domain, id uint32) (UUID, error) { - uuid, err := NewUUID() - if err == nil { - uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 - uuid[9] = byte(domain) - binary.BigEndian.PutUint32(uuid[0:], id) - } - return uuid, err -} - -// NewDCEPerson returns a DCE Security (Version 2) UUID in the person -// domain with the id returned by os.Getuid. -// -// NewDCESecurity(Person, uint32(os.Getuid())) -func NewDCEPerson() (UUID, error) { - return NewDCESecurity(Person, uint32(os.Getuid())) -} - -// NewDCEGroup returns a DCE Security (Version 2) UUID in the group -// domain with the id returned by os.Getgid. -// -// NewDCESecurity(Group, uint32(os.Getgid())) -func NewDCEGroup() (UUID, error) { - return NewDCESecurity(Group, uint32(os.Getgid())) -} - -// Domain returns the domain for a Version 2 UUID. Domains are only defined -// for Version 2 UUIDs. -func (uuid UUID) Domain() Domain { - return Domain(uuid[9]) -} - -// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 -// UUIDs. -func (uuid UUID) ID() uint32 { - return binary.BigEndian.Uint32(uuid[0:4]) -} - -func (d Domain) String() string { - switch d { - case Person: - return "Person" - case Group: - return "Group" - case Org: - return "Org" - } - return fmt.Sprintf("Domain%d", int(d)) -} diff --git a/vendor/github.com/google/uuid/doc.go b/vendor/github.com/google/uuid/doc.go deleted file mode 100644 index 5b8a4b9..0000000 --- a/vendor/github.com/google/uuid/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package uuid generates and inspects UUIDs. -// -// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security -// Services. -// -// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to -// maps or compared directly. -package uuid diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go deleted file mode 100644 index dc60082..0000000 --- a/vendor/github.com/google/uuid/hash.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "crypto/md5" - "crypto/sha1" - "hash" -) - -// Well known namespace IDs and UUIDs -var ( - NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) - NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) - Nil UUID // empty UUID, all zeros - - // The Max UUID is special form of UUID that is specified to have all 128 bits set to 1. - Max = UUID{ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - } -) - -// NewHash returns a new UUID derived from the hash of space concatenated with -// data generated by h. The hash should be at least 16 byte in length. The -// first 16 bytes of the hash are used to form the UUID. The version of the -// UUID will be the lower 4 bits of version. NewHash is used to implement -// NewMD5 and NewSHA1. -func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { - h.Reset() - h.Write(space[:]) //nolint:errcheck - h.Write(data) //nolint:errcheck - s := h.Sum(nil) - var uuid UUID - copy(uuid[:], s) - uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) - uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant - return uuid -} - -// NewMD5 returns a new MD5 (Version 3) UUID based on the -// supplied name space and data. It is the same as calling: -// -// NewHash(md5.New(), space, data, 3) -func NewMD5(space UUID, data []byte) UUID { - return NewHash(md5.New(), space, data, 3) -} - -// NewSHA1 returns a new SHA1 (Version 5) UUID based on the -// supplied name space and data. It is the same as calling: -// -// NewHash(sha1.New(), space, data, 5) -func NewSHA1(space UUID, data []byte) UUID { - return NewHash(sha1.New(), space, data, 5) -} diff --git a/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/google/uuid/marshal.go deleted file mode 100644 index 14bd340..0000000 --- a/vendor/github.com/google/uuid/marshal.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "fmt" - -// MarshalText implements encoding.TextMarshaler. -func (uuid UUID) MarshalText() ([]byte, error) { - var js [36]byte - encodeHex(js[:], uuid) - return js[:], nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (uuid *UUID) UnmarshalText(data []byte) error { - id, err := ParseBytes(data) - if err != nil { - return err - } - *uuid = id - return nil -} - -// MarshalBinary implements encoding.BinaryMarshaler. -func (uuid UUID) MarshalBinary() ([]byte, error) { - return uuid[:], nil -} - -// UnmarshalBinary implements encoding.BinaryUnmarshaler. -func (uuid *UUID) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) - } - copy(uuid[:], data) - return nil -} diff --git a/vendor/github.com/google/uuid/node.go b/vendor/github.com/google/uuid/node.go deleted file mode 100644 index d651a2b..0000000 --- a/vendor/github.com/google/uuid/node.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "sync" -) - -var ( - nodeMu sync.Mutex - ifname string // name of interface being used - nodeID [6]byte // hardware for version 1 UUIDs - zeroID [6]byte // nodeID with only 0's -) - -// NodeInterface returns the name of the interface from which the NodeID was -// derived. The interface "user" is returned if the NodeID was set by -// SetNodeID. -func NodeInterface() string { - defer nodeMu.Unlock() - nodeMu.Lock() - return ifname -} - -// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. -// If name is "" then the first usable interface found will be used or a random -// Node ID will be generated. If a named interface cannot be found then false -// is returned. -// -// SetNodeInterface never fails when name is "". -func SetNodeInterface(name string) bool { - defer nodeMu.Unlock() - nodeMu.Lock() - return setNodeInterface(name) -} - -func setNodeInterface(name string) bool { - iname, addr := getHardwareInterface(name) // null implementation for js - if iname != "" && addr != nil { - ifname = iname - copy(nodeID[:], addr) - return true - } - - // We found no interfaces with a valid hardware address. If name - // does not specify a specific interface generate a random Node ID - // (section 4.1.6) - if name == "" { - ifname = "random" - randomBits(nodeID[:]) - return true - } - return false -} - -// NodeID returns a slice of a copy of the current Node ID, setting the Node ID -// if not already set. -func NodeID() []byte { - defer nodeMu.Unlock() - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - nid := nodeID - return nid[:] -} - -// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes -// of id are used. If id is less than 6 bytes then false is returned and the -// Node ID is not set. -func SetNodeID(id []byte) bool { - if len(id) < 6 { - return false - } - defer nodeMu.Unlock() - nodeMu.Lock() - copy(nodeID[:], id) - ifname = "user" - return true -} - -// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is -// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) NodeID() []byte { - var node [6]byte - copy(node[:], uuid[10:]) - return node[:] -} diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go deleted file mode 100644 index b2a0bc8..0000000 --- a/vendor/github.com/google/uuid/node_js.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2017 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build js - -package uuid - -// getHardwareInterface returns nil values for the JS version of the code. -// This removes the "net" dependency, because it is not used in the browser. -// Using the "net" library inflates the size of the transpiled JS code by 673k bytes. -func getHardwareInterface(name string) (string, []byte) { return "", nil } diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go deleted file mode 100644 index 0cbbcdd..0000000 --- a/vendor/github.com/google/uuid/node_net.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2017 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !js - -package uuid - -import "net" - -var interfaces []net.Interface // cached list of interfaces - -// getHardwareInterface returns the name and hardware address of interface name. -// If name is "" then the name and hardware address of one of the system's -// interfaces is returned. If no interfaces are found (name does not exist or -// there are no interfaces) then "", nil is returned. -// -// Only addresses of at least 6 bytes are returned. -func getHardwareInterface(name string) (string, []byte) { - if interfaces == nil { - var err error - interfaces, err = net.Interfaces() - if err != nil { - return "", nil - } - } - for _, ifs := range interfaces { - if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { - return ifs.Name, ifs.HardwareAddr - } - } - return "", nil -} diff --git a/vendor/github.com/google/uuid/null.go b/vendor/github.com/google/uuid/null.go deleted file mode 100644 index d7fcbf2..0000000 --- a/vendor/github.com/google/uuid/null.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2021 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "database/sql/driver" - "encoding/json" - "fmt" -) - -var jsonNull = []byte("null") - -// NullUUID represents a UUID that may be null. -// NullUUID implements the SQL driver.Scanner interface so -// it can be used as a scan destination: -// -// var u uuid.NullUUID -// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u) -// ... -// if u.Valid { -// // use u.UUID -// } else { -// // NULL value -// } -// -type NullUUID struct { - UUID UUID - Valid bool // Valid is true if UUID is not NULL -} - -// Scan implements the SQL driver.Scanner interface. -func (nu *NullUUID) Scan(value interface{}) error { - if value == nil { - nu.UUID, nu.Valid = Nil, false - return nil - } - - err := nu.UUID.Scan(value) - if err != nil { - nu.Valid = false - return err - } - - nu.Valid = true - return nil -} - -// Value implements the driver Valuer interface. -func (nu NullUUID) Value() (driver.Value, error) { - if !nu.Valid { - return nil, nil - } - // Delegate to UUID Value function - return nu.UUID.Value() -} - -// MarshalBinary implements encoding.BinaryMarshaler. -func (nu NullUUID) MarshalBinary() ([]byte, error) { - if nu.Valid { - return nu.UUID[:], nil - } - - return []byte(nil), nil -} - -// UnmarshalBinary implements encoding.BinaryUnmarshaler. -func (nu *NullUUID) UnmarshalBinary(data []byte) error { - if len(data) != 16 { - return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) - } - copy(nu.UUID[:], data) - nu.Valid = true - return nil -} - -// MarshalText implements encoding.TextMarshaler. -func (nu NullUUID) MarshalText() ([]byte, error) { - if nu.Valid { - return nu.UUID.MarshalText() - } - - return jsonNull, nil -} - -// UnmarshalText implements encoding.TextUnmarshaler. -func (nu *NullUUID) UnmarshalText(data []byte) error { - id, err := ParseBytes(data) - if err != nil { - nu.Valid = false - return err - } - nu.UUID = id - nu.Valid = true - return nil -} - -// MarshalJSON implements json.Marshaler. -func (nu NullUUID) MarshalJSON() ([]byte, error) { - if nu.Valid { - return json.Marshal(nu.UUID) - } - - return jsonNull, nil -} - -// UnmarshalJSON implements json.Unmarshaler. -func (nu *NullUUID) UnmarshalJSON(data []byte) error { - if bytes.Equal(data, jsonNull) { - *nu = NullUUID{} - return nil // valid null UUID - } - err := json.Unmarshal(data, &nu.UUID) - nu.Valid = err == nil - return err -} diff --git a/vendor/github.com/google/uuid/sql.go b/vendor/github.com/google/uuid/sql.go deleted file mode 100644 index 2e02ec0..0000000 --- a/vendor/github.com/google/uuid/sql.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "database/sql/driver" - "fmt" -) - -// Scan implements sql.Scanner so UUIDs can be read from databases transparently. -// Currently, database types that map to string and []byte are supported. Please -// consult database-specific driver documentation for matching types. -func (uuid *UUID) Scan(src interface{}) error { - switch src := src.(type) { - case nil: - return nil - - case string: - // if an empty UUID comes from a table, we return a null UUID - if src == "" { - return nil - } - - // see Parse for required string format - u, err := Parse(src) - if err != nil { - return fmt.Errorf("Scan: %v", err) - } - - *uuid = u - - case []byte: - // if an empty UUID comes from a table, we return a null UUID - if len(src) == 0 { - return nil - } - - // assumes a simple slice of bytes if 16 bytes - // otherwise attempts to parse - if len(src) != 16 { - return uuid.Scan(string(src)) - } - copy((*uuid)[:], src) - - default: - return fmt.Errorf("Scan: unable to scan type %T into UUID", src) - } - - return nil -} - -// Value implements sql.Valuer so that UUIDs can be written to databases -// transparently. Currently, UUIDs map to strings. Please consult -// database-specific driver documentation for matching types. -func (uuid UUID) Value() (driver.Value, error) { - return uuid.String(), nil -} diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go deleted file mode 100644 index c351129..0000000 --- a/vendor/github.com/google/uuid/time.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" - "sync" - "time" -) - -// A Time represents a time as the number of 100's of nanoseconds since 15 Oct -// 1582. -type Time int64 - -const ( - lillian = 2299160 // Julian day of 15 Oct 1582 - unix = 2440587 // Julian day of 1 Jan 1970 - epoch = unix - lillian // Days between epochs - g1582 = epoch * 86400 // seconds between epochs - g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs -) - -var ( - timeMu sync.Mutex - lasttime uint64 // last time we returned - clockSeq uint16 // clock sequence for this run - - timeNow = time.Now // for testing -) - -// UnixTime converts t the number of seconds and nanoseconds using the Unix -// epoch of 1 Jan 1970. -func (t Time) UnixTime() (sec, nsec int64) { - sec = int64(t - g1582ns100) - nsec = (sec % 10000000) * 100 - sec /= 10000000 - return sec, nsec -} - -// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and -// clock sequence as well as adjusting the clock sequence as needed. An error -// is returned if the current time cannot be determined. -func GetTime() (Time, uint16, error) { - defer timeMu.Unlock() - timeMu.Lock() - return getTime() -} - -func getTime() (Time, uint16, error) { - t := timeNow() - - // If we don't have a clock sequence already, set one. - if clockSeq == 0 { - setClockSequence(-1) - } - now := uint64(t.UnixNano()/100) + g1582ns100 - - // If time has gone backwards with this clock sequence then we - // increment the clock sequence - if now <= lasttime { - clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 - } - lasttime = now - return Time(now), clockSeq, nil -} - -// ClockSequence returns the current clock sequence, generating one if not -// already set. The clock sequence is only used for Version 1 UUIDs. -// -// The uuid package does not use global static storage for the clock sequence or -// the last time a UUID was generated. Unless SetClockSequence is used, a new -// random clock sequence is generated the first time a clock sequence is -// requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) -func ClockSequence() int { - defer timeMu.Unlock() - timeMu.Lock() - return clockSequence() -} - -func clockSequence() int { - if clockSeq == 0 { - setClockSequence(-1) - } - return int(clockSeq & 0x3fff) -} - -// SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to -// -1 causes a new sequence to be generated. -func SetClockSequence(seq int) { - defer timeMu.Unlock() - timeMu.Lock() - setClockSequence(seq) -} - -func setClockSequence(seq int) { - if seq == -1 { - var b [2]byte - randomBits(b[:]) // clock sequence - seq = int(b[0])<<8 | int(b[1]) - } - oldSeq := clockSeq - clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant - if oldSeq != clockSeq { - lasttime = 0 - } -} - -// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in -// uuid. The time is only defined for version 1, 2, 6 and 7 UUIDs. -func (uuid UUID) Time() Time { - var t Time - switch uuid.Version() { - case 6: - time := binary.BigEndian.Uint64(uuid[:8]) // Ignore uuid[6] version b0110 - t = Time(time) - case 7: - time := binary.BigEndian.Uint64(uuid[:8]) - t = Time((time>>16)*10000 + g1582ns100) - default: // forward compatible - time := int64(binary.BigEndian.Uint32(uuid[0:4])) - time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 - time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 - t = Time(time) - } - return t -} - -// ClockSequence returns the clock sequence encoded in uuid. -// The clock sequence is only well defined for version 1 and 2 UUIDs. -func (uuid UUID) ClockSequence() int { - return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff -} diff --git a/vendor/github.com/google/uuid/util.go b/vendor/github.com/google/uuid/util.go deleted file mode 100644 index 5ea6c73..0000000 --- a/vendor/github.com/google/uuid/util.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "io" -) - -// randomBits completely fills slice b with random data. -func randomBits(b []byte) { - if _, err := io.ReadFull(rander, b); err != nil { - panic(err.Error()) // rand should never fail - } -} - -// xvalues returns the value of a byte as a hexadecimal digit or 255. -var xvalues = [256]byte{ - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, -} - -// xtob converts hex characters x1 and x2 into a byte. -func xtob(x1, x2 byte) (byte, bool) { - b1 := xvalues[x1] - b2 := xvalues[x2] - return (b1 << 4) | b2, b1 != 255 && b2 != 255 -} diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go deleted file mode 100644 index 5232b48..0000000 --- a/vendor/github.com/google/uuid/uuid.go +++ /dev/null @@ -1,365 +0,0 @@ -// Copyright 2018 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "crypto/rand" - "encoding/hex" - "errors" - "fmt" - "io" - "strings" - "sync" -) - -// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC -// 4122. -type UUID [16]byte - -// A Version represents a UUID's version. -type Version byte - -// A Variant represents a UUID's variant. -type Variant byte - -// Constants returned by Variant. -const ( - Invalid = Variant(iota) // Invalid UUID - RFC4122 // The variant specified in RFC4122 - Reserved // Reserved, NCS backward compatibility. - Microsoft // Reserved, Microsoft Corporation backward compatibility. - Future // Reserved for future definition. -) - -const randPoolSize = 16 * 16 - -var ( - rander = rand.Reader // random function - poolEnabled = false - poolMu sync.Mutex - poolPos = randPoolSize // protected with poolMu - pool [randPoolSize]byte // protected with poolMu -) - -type invalidLengthError struct{ len int } - -func (err invalidLengthError) Error() string { - return fmt.Sprintf("invalid UUID length: %d", err.len) -} - -// IsInvalidLengthError is matcher function for custom error invalidLengthError -func IsInvalidLengthError(err error) bool { - _, ok := err.(invalidLengthError) - return ok -} - -// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both -// the standard UUID forms defined in RFC 4122 -// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, -// Parse accepts non-standard strings such as the raw hex encoding -// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, -// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are -// examined in the latter case. Parse should not be used to validate strings as -// it parses non-standard encodings as indicated above. -func Parse(s string) (UUID, error) { - var uuid UUID - switch len(s) { - // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36: - - // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36 + 9: - if !strings.EqualFold(s[:9], "urn:uuid:") { - return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) - } - s = s[9:] - - // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - case 36 + 2: - s = s[1:] - - // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - case 32: - var ok bool - for i := range uuid { - uuid[i], ok = xtob(s[i*2], s[i*2+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - } - return uuid, nil - default: - return uuid, invalidLengthError{len(s)} - } - // s is now at least 36 bytes long - // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34, - } { - v, ok := xtob(s[x], s[x+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - uuid[i] = v - } - return uuid, nil -} - -// ParseBytes is like Parse, except it parses a byte slice instead of a string. -func ParseBytes(b []byte) (UUID, error) { - var uuid UUID - switch len(b) { - case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { - return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) - } - b = b[9:] - case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} - b = b[1:] - case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - var ok bool - for i := 0; i < 32; i += 2 { - uuid[i/2], ok = xtob(b[i], b[i+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - } - return uuid, nil - default: - return uuid, invalidLengthError{len(b)} - } - // s is now at least 36 bytes long - // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx - if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { - return uuid, errors.New("invalid UUID format") - } - for i, x := range [16]int{ - 0, 2, 4, 6, - 9, 11, - 14, 16, - 19, 21, - 24, 26, 28, 30, 32, 34, - } { - v, ok := xtob(b[x], b[x+1]) - if !ok { - return uuid, errors.New("invalid UUID format") - } - uuid[i] = v - } - return uuid, nil -} - -// MustParse is like Parse but panics if the string cannot be parsed. -// It simplifies safe initialization of global variables holding compiled UUIDs. -func MustParse(s string) UUID { - uuid, err := Parse(s) - if err != nil { - panic(`uuid: Parse(` + s + `): ` + err.Error()) - } - return uuid -} - -// FromBytes creates a new UUID from a byte slice. Returns an error if the slice -// does not have a length of 16. The bytes are copied from the slice. -func FromBytes(b []byte) (uuid UUID, err error) { - err = uuid.UnmarshalBinary(b) - return uuid, err -} - -// Must returns uuid if err is nil and panics otherwise. -func Must(uuid UUID, err error) UUID { - if err != nil { - panic(err) - } - return uuid -} - -// Validate returns an error if s is not a properly formatted UUID in one of the following formats: -// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} -// It returns an error if the format is invalid, otherwise nil. -func Validate(s string) error { - switch len(s) { - // Standard UUID format - case 36: - - // UUID with "urn:uuid:" prefix - case 36 + 9: - if !strings.EqualFold(s[:9], "urn:uuid:") { - return fmt.Errorf("invalid urn prefix: %q", s[:9]) - } - s = s[9:] - - // UUID enclosed in braces - case 36 + 2: - if s[0] != '{' || s[len(s)-1] != '}' { - return fmt.Errorf("invalid bracketed UUID format") - } - s = s[1 : len(s)-1] - - // UUID without hyphens - case 32: - for i := 0; i < len(s); i += 2 { - _, ok := xtob(s[i], s[i+1]) - if !ok { - return errors.New("invalid UUID format") - } - } - - default: - return invalidLengthError{len(s)} - } - - // Check for standard UUID format - if len(s) == 36 { - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return errors.New("invalid UUID format") - } - for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { - if _, ok := xtob(s[x], s[x+1]); !ok { - return errors.New("invalid UUID format") - } - } - } - - return nil -} - -// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx -// , or "" if uuid is invalid. -func (uuid UUID) String() string { - var buf [36]byte - encodeHex(buf[:], uuid) - return string(buf[:]) -} - -// URN returns the RFC 2141 URN form of uuid, -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. -func (uuid UUID) URN() string { - var buf [36 + 9]byte - copy(buf[:], "urn:uuid:") - encodeHex(buf[9:], uuid) - return string(buf[:]) -} - -func encodeHex(dst []byte, uuid UUID) { - hex.Encode(dst, uuid[:4]) - dst[8] = '-' - hex.Encode(dst[9:13], uuid[4:6]) - dst[13] = '-' - hex.Encode(dst[14:18], uuid[6:8]) - dst[18] = '-' - hex.Encode(dst[19:23], uuid[8:10]) - dst[23] = '-' - hex.Encode(dst[24:], uuid[10:]) -} - -// Variant returns the variant encoded in uuid. -func (uuid UUID) Variant() Variant { - switch { - case (uuid[8] & 0xc0) == 0x80: - return RFC4122 - case (uuid[8] & 0xe0) == 0xc0: - return Microsoft - case (uuid[8] & 0xe0) == 0xe0: - return Future - default: - return Reserved - } -} - -// Version returns the version of uuid. -func (uuid UUID) Version() Version { - return Version(uuid[6] >> 4) -} - -func (v Version) String() string { - if v > 15 { - return fmt.Sprintf("BAD_VERSION_%d", v) - } - return fmt.Sprintf("VERSION_%d", v) -} - -func (v Variant) String() string { - switch v { - case RFC4122: - return "RFC4122" - case Reserved: - return "Reserved" - case Microsoft: - return "Microsoft" - case Future: - return "Future" - case Invalid: - return "Invalid" - } - return fmt.Sprintf("BadVariant%d", int(v)) -} - -// SetRand sets the random number generator to r, which implements io.Reader. -// If r.Read returns an error when the package requests random data then -// a panic will be issued. -// -// Calling SetRand with nil sets the random number generator to the default -// generator. -func SetRand(r io.Reader) { - if r == nil { - rander = rand.Reader - return - } - rander = r -} - -// EnableRandPool enables internal randomness pool used for Random -// (Version 4) UUID generation. The pool contains random bytes read from -// the random number generator on demand in batches. Enabling the pool -// may improve the UUID generation throughput significantly. -// -// Since the pool is stored on the Go heap, this feature may be a bad fit -// for security sensitive applications. -// -// Both EnableRandPool and DisableRandPool are not thread-safe and should -// only be called when there is no possibility that New or any other -// UUID Version 4 generation function will be called concurrently. -func EnableRandPool() { - poolEnabled = true -} - -// DisableRandPool disables the randomness pool if it was previously -// enabled with EnableRandPool. -// -// Both EnableRandPool and DisableRandPool are not thread-safe and should -// only be called when there is no possibility that New or any other -// UUID Version 4 generation function will be called concurrently. -func DisableRandPool() { - poolEnabled = false - defer poolMu.Unlock() - poolMu.Lock() - poolPos = randPoolSize -} - -// UUIDs is a slice of UUID types. -type UUIDs []UUID - -// Strings returns a string slice containing the string form of each UUID in uuids. -func (uuids UUIDs) Strings() []string { - var uuidStrs = make([]string, len(uuids)) - for i, uuid := range uuids { - uuidStrs[i] = uuid.String() - } - return uuidStrs -} diff --git a/vendor/github.com/google/uuid/version1.go b/vendor/github.com/google/uuid/version1.go deleted file mode 100644 index 4631096..0000000 --- a/vendor/github.com/google/uuid/version1.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "encoding/binary" -) - -// NewUUID returns a Version 1 UUID based on the current NodeID and clock -// sequence, and the current time. If the NodeID has not been set by SetNodeID -// or SetNodeInterface then it will be set automatically. If the NodeID cannot -// be set NewUUID returns nil. If clock sequence has not been set by -// SetClockSequence then it will be set automatically. If GetTime fails to -// return the current NewUUID returns nil and an error. -// -// In most cases, New should be used. -func NewUUID() (UUID, error) { - var uuid UUID - now, seq, err := GetTime() - if err != nil { - return uuid, err - } - - timeLow := uint32(now & 0xffffffff) - timeMid := uint16((now >> 32) & 0xffff) - timeHi := uint16((now >> 48) & 0x0fff) - timeHi |= 0x1000 // Version 1 - - binary.BigEndian.PutUint32(uuid[0:], timeLow) - binary.BigEndian.PutUint16(uuid[4:], timeMid) - binary.BigEndian.PutUint16(uuid[6:], timeHi) - binary.BigEndian.PutUint16(uuid[8:], seq) - - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - copy(uuid[10:], nodeID[:]) - nodeMu.Unlock() - - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go deleted file mode 100644 index 7697802..0000000 --- a/vendor/github.com/google/uuid/version4.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2016 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "io" - -// New creates a new random UUID or panics. New is equivalent to -// the expression -// -// uuid.Must(uuid.NewRandom()) -func New() UUID { - return Must(NewRandom()) -} - -// NewString creates a new random UUID and returns it as a string or panics. -// NewString is equivalent to the expression -// -// uuid.New().String() -func NewString() string { - return Must(NewRandom()).String() -} - -// NewRandom returns a Random (Version 4) UUID. -// -// The strength of the UUIDs is based on the strength of the crypto/rand -// package. -// -// Uses the randomness pool if it was enabled with EnableRandPool. -// -// A note about uniqueness derived from the UUID Wikipedia entry: -// -// Randomly generated UUIDs have 122 random bits. One's annual risk of being -// hit by a meteorite is estimated to be one chance in 17 billion, that -// means the probability is about 0.00000000006 (6 × 10−11), -// equivalent to the odds of creating a few tens of trillions of UUIDs in a -// year and having one duplicate. -func NewRandom() (UUID, error) { - if !poolEnabled { - return NewRandomFromReader(rander) - } - return newRandomFromPool() -} - -// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader. -func NewRandomFromReader(r io.Reader) (UUID, error) { - var uuid UUID - _, err := io.ReadFull(r, uuid[:]) - if err != nil { - return Nil, err - } - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return uuid, nil -} - -func newRandomFromPool() (UUID, error) { - var uuid UUID - poolMu.Lock() - if poolPos == randPoolSize { - _, err := io.ReadFull(rander, pool[:]) - if err != nil { - poolMu.Unlock() - return Nil, err - } - poolPos = 0 - } - copy(uuid[:], pool[poolPos:(poolPos+16)]) - poolPos += 16 - poolMu.Unlock() - - uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 - uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version6.go b/vendor/github.com/google/uuid/version6.go deleted file mode 100644 index 339a959..0000000 --- a/vendor/github.com/google/uuid/version6.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2023 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import "encoding/binary" - -// UUID version 6 is a field-compatible version of UUIDv1, reordered for improved DB locality. -// It is expected that UUIDv6 will primarily be used in contexts where there are existing v1 UUIDs. -// Systems that do not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. -// -// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#uuidv6 -// -// NewV6 returns a Version 6 UUID based on the current NodeID and clock -// sequence, and the current time. If the NodeID has not been set by SetNodeID -// or SetNodeInterface then it will be set automatically. If the NodeID cannot -// be set NewV6 set NodeID is random bits automatically . If clock sequence has not been set by -// SetClockSequence then it will be set automatically. If GetTime fails to -// return the current NewV6 returns Nil and an error. -func NewV6() (UUID, error) { - var uuid UUID - now, seq, err := GetTime() - if err != nil { - return uuid, err - } - - /* - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | time_high | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | time_mid | time_low_and_version | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |clk_seq_hi_res | clk_seq_low | node (0-1) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | node (2-5) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - - binary.BigEndian.PutUint64(uuid[0:], uint64(now)) - binary.BigEndian.PutUint16(uuid[8:], seq) - - uuid[6] = 0x60 | (uuid[6] & 0x0F) - uuid[8] = 0x80 | (uuid[8] & 0x3F) - - nodeMu.Lock() - if nodeID == zeroID { - setNodeInterface("") - } - copy(uuid[10:], nodeID[:]) - nodeMu.Unlock() - - return uuid, nil -} diff --git a/vendor/github.com/google/uuid/version7.go b/vendor/github.com/google/uuid/version7.go deleted file mode 100644 index 3167b64..0000000 --- a/vendor/github.com/google/uuid/version7.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2023 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "io" -) - -// UUID version 7 features a time-ordered value field derived from the widely -// implemented and well known Unix Epoch timestamp source, -// the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. -// As well as improved entropy characteristics over versions 1 or 6. -// -// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#name-uuid-version-7 -// -// Implementations SHOULD utilize UUID version 7 over UUID version 1 and 6 if possible. -// -// NewV7 returns a Version 7 UUID based on the current time(Unix Epoch). -// Uses the randomness pool if it was enabled with EnableRandPool. -// On error, NewV7 returns Nil and an error -func NewV7() (UUID, error) { - uuid, err := NewRandom() - if err != nil { - return uuid, err - } - makeV7(uuid[:]) - return uuid, nil -} - -// NewV7FromReader returns a Version 7 UUID based on the current time(Unix Epoch). -// it use NewRandomFromReader fill random bits. -// On error, NewV7FromReader returns Nil and an error. -func NewV7FromReader(r io.Reader) (UUID, error) { - uuid, err := NewRandomFromReader(r) - if err != nil { - return uuid, err - } - - makeV7(uuid[:]) - return uuid, nil -} - -// makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) -// uuid[8] already has the right version number (Variant is 10) -// see function NewV7 and NewV7FromReader -func makeV7(uuid []byte) { - /* - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | unix_ts_ms | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | unix_ts_ms | ver | rand_a (12 bit seq) | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - |var| rand_b | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | rand_b | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - */ - _ = uuid[15] // bounds check - - t, s := getV7Time() - - uuid[0] = byte(t >> 40) - uuid[1] = byte(t >> 32) - uuid[2] = byte(t >> 24) - uuid[3] = byte(t >> 16) - uuid[4] = byte(t >> 8) - uuid[5] = byte(t) - - uuid[6] = 0x70 | (0x0F & byte(s>>8)) - uuid[7] = byte(s) -} - -// lastV7time is the last time we returned stored as: -// -// 52 bits of time in milliseconds since epoch -// 12 bits of (fractional nanoseconds) >> 8 -var lastV7time int64 - -const nanoPerMilli = 1000000 - -// getV7Time returns the time in milliseconds and nanoseconds / 256. -// The returned (milli << 12 + seq) is guarenteed to be greater than -// (milli << 12 + seq) returned by any previous call to getV7Time. -func getV7Time() (milli, seq int64) { - timeMu.Lock() - defer timeMu.Unlock() - - nano := timeNow().UnixNano() - milli = nano / nanoPerMilli - // Sequence number is between 0 and 3906 (nanoPerMilli>>8) - seq = (nano - milli*nanoPerMilli) >> 8 - now := milli<<12 + seq - if now <= lastV7time { - now = lastV7time + 1 - milli = now >> 12 - seq = now & 0xfff - } - lastV7time = now - return milli, seq -} diff --git a/vendor/modules.txt b/vendor/modules.txt deleted file mode 100644 index 898177b..0000000 --- a/vendor/modules.txt +++ /dev/null @@ -1,22 +0,0 @@ -# github.com/alecthomas/kong v1.11.0 -## explicit; go 1.20 -github.com/alecthomas/kong -# github.com/anduril/lattice-sdk-go/v2 v2.2.0 -## explicit; go 1.18 -github.com/anduril/lattice-sdk-go/v2 -github.com/anduril/lattice-sdk-go/v2/client -github.com/anduril/lattice-sdk-go/v2/core -github.com/anduril/lattice-sdk-go/v2/entities -github.com/anduril/lattice-sdk-go/v2/internal -github.com/anduril/lattice-sdk-go/v2/objects -github.com/anduril/lattice-sdk-go/v2/option -github.com/anduril/lattice-sdk-go/v2/tasks -# github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc -## explicit -# github.com/google/uuid v1.6.0 -## explicit -github.com/google/uuid -# github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 -## explicit -# github.com/stretchr/testify v1.10.0 -## explicit; go 1.17