cli

package
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 9, 2022 License: MIT Imports: 39 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AuthHandlers = make(map[string]AuthHandler)

AuthHandlers is the map of registered auth type names to handlers

Client makes HTTP requests and parses the responses.

View Source
var (
	ErrCannotUnmarshal = errors.New("Unable to unmarshal response")
)

HTTP Client Errors

View Source
var PreRun func(cmd *cobra.Command, args []string) error

PreRun is a function that will run after flags are parsed but before the command handler has been called.

Root command (entrypoint) of the CLI.

View Source
var Stderr io.Writer = os.Stderr

Stderr is a cross-platform, color-safe writer if colors are enabled, otherwise it defaults to `os.Stderr`.

View Source
var Stdout io.Writer = os.Stdout

Stdout is a cross-platform, color-safe writer if colors are enabled, otherwise it defaults to `os.Stdout`.

Functions

func AddFlag

func AddFlag(path, name, short, description string, defaultValue interface{})

AddFlag registers a new custom flag for the command path. Use the `RegisterBefore` and `RegisterAfter` functions to register a handler that can check the value of this flag.

func BuildHelpConfigCommand added in v0.0.8

func BuildHelpConfigCommand(appName string) *cobra.Command

func BuildHelpInputCommand added in v0.0.8

func BuildHelpInputCommand() *cobra.Command

func BuildSecretsCommands added in v0.0.6

func BuildSecretsCommands() (cmd *cobra.Command)

BuildSecretsCommands sets up basic commands and the credentials file so that new auth handlers can be registered. This MUST be called only after auth handlers have been set up through UseAuth.

func BuildSettingsCommands added in v0.0.6

func BuildSettingsCommands() (configCommand *cobra.Command)

func DeepAssign

func DeepAssign(target, source map[string]interface{})

DeepAssign recursively merges a source map into the target.

func GetBody

func GetBody(mediaType string, args []string) (string, error)

GetBody returns the request body if one was passed either as shorthand arguments or via stdin.

func GetMatchValue

func GetMatchValue(ctx *context.Context, selector string, reqParams map[string]interface{}, decoded interface{}) (interface{}, error)

GetMatchValue returns a value for the given selector query.

func HandleAfter

func HandleAfter(path string, params *viper.Viper, resp *gentleman.Response, data interface{}) interface{}

HandleAfter runs any registered post-request handlers for the given command.

func HandleBefore

func HandleBefore(path string, params *viper.Viper, r *gentleman.Request)

HandleBefore runs any registered pre-request handlers for the given command.

func Init

func Init(config *Config)

Init will set up the CLI.

func InitConfiguration added in v0.0.5

func InitConfiguration(envPrefix, settingsFilePath, secretsFilePath string, globalFlags []GlobalFlag) (err error)

func LogMiddleware

func LogMiddleware(useColor bool)

LogMiddleware adds verbose log info to HTTP requests.

func Markdown

func Markdown(content string) string

Markdown renders terminal-friendly Markdown content.

func Match

func Match(test string, expected json.RawMessage, actual interface{}) (bool, error)

Match returns `true` if the expected value of the match type is found in the given response data.

func RegisterAfter

func RegisterAfter(path string, handler AfterHandlerFunc)

RegisterAfter registers a post-request handler for the given command path. The handler may modify the unmarshalled response.

func RegisterAfterAll added in v0.0.11

func RegisterAfterAll(handler AfterHandlerFunc)

func RegisterBefore

func RegisterBefore(path string, handler BeforeHandlerFunc)

RegisterBefore registers a pre-request handler for the given command path. The handler may modify the request before it gets sent over the wire.

func RegisterBeforeAll added in v0.0.11

func RegisterBeforeAll(handler BeforeHandlerFunc)

func SetCustomFlags

func SetCustomFlags(cmd *cobra.Command)

SetCustomFlags sets up the command with additional registered flags.

func UnmarshalRequest

func UnmarshalRequest(ctx *context.Context, s interface{}) error

UnmarshalRequest body into a given structure `s`. Supports both JSON and YAML depending on the request's content-type header.

func UnmarshalResponse

func UnmarshalResponse(resp *gentleman.Response, s interface{}) error

UnmarshalResponse into a given structure `s`. Supports both JSON and YAML depending on the response's content-type header.

func UseAuth

func UseAuth(typeName string, handler AuthHandler)

UseAuth registers a new auth handler for a given type name. For backward- compatibility, the auth type name can be a blank string. It is recommended to always pass a value for the type name.

func UserAgentMiddleware

func UserAgentMiddleware(appName string)

UserAgentMiddleware sets the user-agent header on requests.

Types

type AfterHandlerFunc

type AfterHandlerFunc func(string, *viper.Viper, *gentleman.Response, interface{}) interface{}

AfterHandlerFunc is a function that runs after a request has been sent and the response is unmarshalled. It may modify the response. It must return the response data regardless of whether it was modified.

type Applications added in v0.0.5

type Applications struct {
	CLI CLI `mapstructure:"cli"`
}

type AuthHandler

type AuthHandler interface {
	ExecuteFlow(log *zerolog.Logger) (*oauth2.Token, error)

	// ProfileKeys returns the key names for fields to store in the profileName.
	ProfileKeys() []string

	// OnRequest gets run before the request goes out on the wire.
	OnRequest(log *zerolog.Logger, request *http.Request) error
}

AuthHandler describes a handler that can be called on a request to inject auth information and is agnostic to the type of auth.

type AuthServer added in v0.0.5

type AuthServer struct {
	ClientID string   `mapstructure:"client_id"`
	Issuer   string   `mapstructure:"issuer"`
	Keys     []string `mapstructure:"keys"`
	ListKeys []string `mapstructure:"list_keys"`
	Scopes   []string `mapstructure:"scopes"`
}

type BeforeHandlerFunc

type BeforeHandlerFunc func(string, *viper.Viper, *gentleman.Request)

BeforeHandlerFunc is a function that runs before a command sends a request over the wire. It may modify the request.

func MakeAddHeaders added in v0.0.11

func MakeAddHeaders(config ClientConfiguration) BeforeHandlerFunc

type CLI added in v0.0.5

type CLI struct {
	Verbosity    VerbosityType `mapstructure:"verbosity"`
	OutputFormat string        `mapstructure:"output_format"`
	Query        string        `mapstructure:"query"`
	Raw          bool          `mapstructure:"raw"`
}

func (CLI) ZeroLogLevel added in v0.0.5

func (c CLI) ZeroLogLevel() zerolog.Level

type ClientConfiguration added in v0.0.5

type ClientConfiguration struct {
	Secrets  Secrets  `mapstructure:"secrets"`
	Settings Settings `mapstructure:"settings"`
	// contains filtered or unexported fields
}
var RunConfig ClientConfiguration

func LoadConfiguration added in v0.0.5

func LoadConfiguration(envPrefix, settingsFilePath, secretsFilePath string, globalFlags []GlobalFlag) (config ClientConfiguration, err error)

LoadConfiguration loads secret and settings files. It will additional override those persisted values with (1) environment variables and (2) flag values (in order of increasing precedence).

func (ClientConfiguration) GetAuthServer added in v0.0.5

func (cc ClientConfiguration) GetAuthServer() AuthServer

func (ClientConfiguration) GetCredentials added in v0.0.5

func (cc ClientConfiguration) GetCredentials() Credentials

func (ClientConfiguration) GetProfile added in v0.0.5

func (cc ClientConfiguration) GetProfile() Profile

func (*ClientConfiguration) UpdateCredentialsToken added in v0.0.5

func (cc *ClientConfiguration) UpdateCredentialsToken(credentialsName string, token *oauth2.Token) error

func (ClientConfiguration) WriteSecrets added in v0.0.13

func (cc ClientConfiguration) WriteSecrets(updates map[string]interface{}) (err error)

func (ClientConfiguration) WriteSettings added in v0.0.13

func (cc ClientConfiguration) WriteSettings(updates map[string]interface{}) (err error)

type Config

type Config struct {
	AppName   string
	EnvPrefix string
	Version   string
}

Config is used to pass settings to the CLI.

type ConsoleWriter

type ConsoleWriter struct {
	Out     io.Writer
	NoColor bool
}

ConsoleWriter reads a JSON object per write operation and outputs an optionally colored human readable version on the Out writer. This has been modified from the ConsoleWriter that ships with zerolog.

func (ConsoleWriter) Write

func (w ConsoleWriter) Write(p []byte) (n int, err error)

type Credentials added in v0.0.5

type Credentials struct {
	TokenPayload TokenPayload `mapstructure:"token_payload"`
}

type DefaultFormatter

type DefaultFormatter struct {
	// contains filtered or unexported fields
}

DefaultFormatter can apply JMESPath queries and can output prettyfied JSON and YAML output. If Stdout is a TTY, then colorized output is provided. The default formatter uses the `query` and `output-format` configuration values to perform JMESPath queries and set JSON (default) or YAML output.

func NewDefaultFormatter

func NewDefaultFormatter(tty bool) *DefaultFormatter

NewDefaultFormatter creates a new formatted with autodetected TTY capabilities.

func (*DefaultFormatter) Format

func (f *DefaultFormatter) Format(data interface{}) error

Format will filter, prettify, colorize and output the data.

type GlobalFlag added in v0.0.5

type GlobalFlag struct {
	*pflag.Flag
	UseDefault bool
	// contains filtered or unexported fields
}

func MakeAndParseGlobalFlags added in v0.0.5

func MakeAndParseGlobalFlags(defaults GlobalFlagDefaults) (globalFlags []GlobalFlag, flagSet *pflag.FlagSet, err error)

type GlobalFlagDefaults added in v0.0.5

type GlobalFlagDefaults struct {
	ProfileName     string
	AuthServerName  string
	CredentialsName string
	ApiURL          string
	OutputFormat    string
	Verbosity       string
	Headers         []string
	Raw             bool
}

func NewGlobalFlagDefaults added in v0.0.5

func NewGlobalFlagDefaults(apiURL string) GlobalFlagDefaults

type OAuthHandler added in v0.0.14

type OAuthHandler interface {
	NewToken() (token *oauth2.Token, err error)
}

type Profile added in v0.0.5

type Profile struct {
	ApiURL          string                 `mapstructure:"api_url"`
	AuthServerName  string                 `mapstructure:"auth_server_name"`
	CredentialsName string                 `mapstructure:"credentials_name"`
	Headers         []string               `mapstructure:"headers"`
	Extra           map[string]interface{} `mapstructure:",remain"`
	Applications    `mapstructure:"applications"`
}

func (Profile) ToProfileViperKeys added in v0.0.13

func (p Profile) ToProfileViperKeys(profileName, apiURL string) map[string]interface{}

ToProfileViperKeys returns a map of Viper keys to values for this profile. It includes the top-level profile.{profileName} prefix, which is what Viper will use when (un)marshalling Settings. Note, this includes embedding all of the key value pairs in Profile.Extra. It does not include any field that is set to its default value. Why is this needed? First, mapstructure.Decode will inaccurately nest key value pairs in Profile.Extra under an "Extra" key. Second, viper.WriteConfig will return the following error on custom string fields, such as VerbosityType, during TOML marshalling: While marshaling config: cannot convert type cli.VerbosityType to Tree To side step these issues, we provide this as a convenience method for representing a profile as a map of Viper keys and values. Clients can then pass the returned map to ClientConfiguration.WriteSettings.

type ResponseFormatter

type ResponseFormatter interface {
	Format(interface{}) error
}

ResponseFormatter will filter, prettify, and print out the results of a call.

var Formatter ResponseFormatter

Formatter is the currently configured response output formatter.

type Secrets added in v0.0.5

type Secrets struct {
	Credentials map[string]Credentials `mapstructure:"credentials"`
}

type Settings added in v0.0.5

type Settings struct {
	// ProfileName will be read from settings.toml default_profile_name,
	// then the %envPrefix%_PROFILE_NAME, and then the --profile-name global flag.
	ProfileName string                `mapstructure:"default_profile_name"`
	Profiles    map[string]Profile    `mapstructure:"profiles"`
	AuthServers map[string]AuthServer `mapstructure:"auth_servers"`
	// contains filtered or unexported fields
}

type TokenPayload added in v0.0.5

type TokenPayload struct {
	ExpiresIn    int    `mapstructure:"expires_in"`
	RefreshToken string `mapstructure:"refresh_token"`
	AccessToken  string `mapstructure:"access_token"`
	IDToken      string `mapstructure:"id_token"`
	Scope        string `mapstructure:"scope"`
	TokenType    string `mapstructure:"token_type"`
}

func (TokenPayload) ExpiresAt added in v0.0.5

func (tp TokenPayload) ExpiresAt() (time.Time, error)

func (TokenPayload) ParseClaimsUnverified added in v0.0.11

func (tp TokenPayload) ParseClaimsUnverified() (jwt.MapClaims, error)

func (TokenPayload) ToMap added in v0.0.5

func (tp TokenPayload) ToMap() map[string]interface{}

type VerbosityType added in v0.0.5

type VerbosityType string
const VerbosityTypeDebug VerbosityType = "debug"
const VerbosityTypeError VerbosityType = "error"
const VerbosityTypeFatal VerbosityType = "fatal"
const VerbosityTypeInfo VerbosityType = "info"
const VerbosityTypePanic VerbosityType = "panic"
const VerbosityTypeWarn VerbosityType = "warn"

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL