cli

package
v0.20.0 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2023 License: MIT Imports: 69 Imported by: 0

Documentation

Index

Constants

View Source
const (
	IndentLevel1 chroma.TokenType = 9000 + iota
	IndentLevel2
	IndentLevel3
)

Variables

View Source
var Cache *viper.Viper

Cache is used to store temporary data between runs.

DisplayRanges includes all viewable Unicode characters along with white space.

View Source
var GlobalFlags *pflag.FlagSet

GlobalFlags contains all the fixed up front flags This allows us to parse them before we hand over control to cobra

View Source
var MarkdownStyle = ansi.StyleConfig{
	Document: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			BlockPrefix: "\n",
			BlockSuffix: "\n",
		},
		Margin: uintPtr(2),
	},
	BlockQuote: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Color: stringPtr("#ffd7d7"),
		},
		Indent:      uintPtr(1),
		IndentToken: stringPtr("│ "),
	},
	List: ansi.StyleList{
		LevelIndent: 2,
	},
	Heading: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			BlockSuffix: "\n",
			Color:       stringPtr("#5fafd7"),
			Bold:        boolPtr(true),
		},
	},
	H1: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix:          " ",
			Suffix:          " ",
			Color:           stringPtr("#000"),
			BackgroundColor: stringPtr("#ff5f87"),
			Bold:            boolPtr(true),
		},
	},
	H2: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix: "## ",
		},
	},
	H3: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix: "### ",
		},
	},
	H4: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix: "#### ",
		},
	},
	H5: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix: "##### ",
		},
	},
	H6: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix: "###### ",
			Color:  stringPtr("35"),
			Bold:   boolPtr(false),
		},
	},
	Strikethrough: ansi.StylePrimitive{
		CrossedOut: boolPtr(true),
	},
	Emph: ansi.StylePrimitive{
		Italic: boolPtr(true),
	},
	Strong: ansi.StylePrimitive{
		Bold: boolPtr(true),
	},
	HorizontalRule: ansi.StylePrimitive{
		Color:  stringPtr("240"),
		Format: "\n--------\n",
	},
	Item: ansi.StylePrimitive{
		BlockPrefix: "• ",
	},
	Enumeration: ansi.StylePrimitive{
		BlockPrefix: ". ",
	},
	Task: ansi.StyleTask{
		StylePrimitive: ansi.StylePrimitive{},
		Ticked:         "[✓] ",
		Unticked:       "[ ] ",
	},
	Link: ansi.StylePrimitive{
		Color:     stringPtr("#D6FFB7"),
		Italic:    boolPtr(true),
		Underline: boolPtr(true),
	},
	LinkText: ansi.StylePrimitive{
		Color: stringPtr("#afd787"),
		Bold:  boolPtr(true),
	},
	Image: ansi.StylePrimitive{
		Color:     stringPtr("212"),
		Underline: boolPtr(true),
	},
	ImageText: ansi.StylePrimitive{
		Color:  stringPtr("243"),
		Format: "Image: {{.text}} →",
	},
	Code: ansi.StyleBlock{
		StylePrimitive: ansi.StylePrimitive{
			Prefix:          " ",
			Suffix:          " ",
			Color:           stringPtr("#d78700"),
			BackgroundColor: stringPtr("236"),
		},
	},
	CodeBlock: ansi.StyleCodeBlock{
		StyleBlock: ansi.StyleBlock{
			StylePrimitive: ansi.StylePrimitive{
				Color: stringPtr("244"),
			},
			Margin: uintPtr(2),
		},
		Chroma: &ansi.Chroma{
			Text: ansi.StylePrimitive{
				Color: stringPtr("#C4C4C4"),
			},

			Comment: ansi.StylePrimitive{
				Color: stringPtr("#9e9e9e"),
			},
			CommentPreproc: ansi.StylePrimitive{
				Color: stringPtr("#FF875F"),
			},
			Keyword: ansi.StylePrimitive{
				Color: stringPtr("#ff5f87"),
			},
			KeywordReserved: ansi.StylePrimitive{
				Color: stringPtr("#ff5f87"),
			},
			KeywordNamespace: ansi.StylePrimitive{
				Color: stringPtr("#ff5f87"),
			},
			KeywordType: ansi.StylePrimitive{
				Color: stringPtr("#af87af"),
			},
			Operator: ansi.StylePrimitive{
				Color: stringPtr("#ffd7d7"),
			},
			Punctuation: ansi.StylePrimitive{
				Color: stringPtr("#9e9e9e"),
			},
			Name: ansi.StylePrimitive{
				Color: stringPtr("#C4C4C4"),
			},
			NameBuiltin: ansi.StylePrimitive{
				Color: stringPtr("#af87af"),
			},
			NameTag: ansi.StylePrimitive{
				Color: stringPtr("#5fafd7"),
			},
			NameAttribute: ansi.StylePrimitive{
				Color: stringPtr("#5fafd7"),
			},
			NameClass: ansi.StylePrimitive{
				Color:     stringPtr("#F1F1F1"),
				Underline: boolPtr(true),
				Bold:      boolPtr(true),
			},
			NameDecorator: ansi.StylePrimitive{
				Color: stringPtr("#FED2AF"),
			},
			NameFunction: ansi.StylePrimitive{
				Color: stringPtr("#5fafd7"),
			},
			LiteralNumber: ansi.StylePrimitive{
				Color: stringPtr("#d78700"),
			},
			LiteralString: ansi.StylePrimitive{
				Color: stringPtr("#afd787"),
			},
			LiteralStringEscape: ansi.StylePrimitive{
				Color: stringPtr("#D6FFB7"),
			},
			GenericDeleted: ansi.StylePrimitive{
				Color: stringPtr("#ff5f87"),
			},
			GenericEmph: ansi.StylePrimitive{
				Italic: boolPtr(true),
			},
			GenericInserted: ansi.StylePrimitive{
				Color: stringPtr("#afd787"),
			},
			GenericStrong: ansi.StylePrimitive{
				Bold: boolPtr(true),
			},
			GenericSubheading: ansi.StylePrimitive{
				Color: stringPtr("#777777"),
			},
			Background: ansi.StylePrimitive{
				BackgroundColor: stringPtr("#373737"),
			},
		},
	},
	Table: ansi.StyleTable{
		StyleBlock: ansi.StyleBlock{
			StylePrimitive: ansi.StylePrimitive{},
		},
		CenterSeparator: stringPtr("┼"),
		ColumnSeparator: stringPtr("│"),
		RowSeparator:    stringPtr("─"),
	},
	DefinitionDescription: ansi.StylePrimitive{
		BlockPrefix: "\n🠶 ",
	},
}
View Source
var ReadableLexer = lexers.Register(chroma.MustNewLazyLexer(
	&chroma.Config{
		Name:         "CLI Readable",
		Aliases:      []string{"readable"},
		NotMultiline: true,
		DotAll:       true,
	},
	func() chroma.Rules {
		return chroma.Rules{
			"whitespace": {
				{
					Pattern: `\s+`,
					Type:    chroma.Text,
				},
			},
			"scalar": {
				{
					Pattern: `(true|false|null)\b`,
					Type:    chroma.KeywordConstant,
				},
				{
					Pattern: `"?0x[0-9a-f]+(\\.\\.\\.)?"?`,
					Type:    chroma.LiteralNumberHex,
				},
				{
					Pattern: `"?[0-9]{4}-[0-9]{2}-[0-9]{2}(T[0-9:+-.]+Z?)?"?`,
					Type:    chroma.LiteralDate,
				},
				{
					Pattern: `-?(0|[1-9]\d*)(\.\d+[eE](\+|-)?\d+|[eE](\+|-)?\d+|\.\d+)`,
					Type:    chroma.LiteralNumberFloat,
				},
				{
					Pattern: `-?(0|[1-9]\d*)`,
					Type:    chroma.LiteralNumberInteger,
				},
				{
					Pattern: `"([a-z]+://|/)(\\\\|\\"|[^"])+"`,
					Type:    chroma.LiteralStringSymbol,
				},
				{
					Pattern: `"(\\\\|\\"|[^"])*"`,
					Type:    chroma.LiteralStringDouble,
				},
			},
			"objectrow": {
				{
					Pattern: `:`,
					Type:    chroma.Punctuation,
				},
				{
					Pattern: `\n`,
					Type:    chroma.Punctuation,
					Mutator: chroma.Pop(1),
				},
				{
					Pattern: `\}`,
					Type:    chroma.Punctuation,
					Mutator: chroma.Pop(2),
				},
				chroma.Include("value"),
			},
			"object": {
				chroma.Include("whitespace"),
				{
					Pattern: `\}`,
					Type:    chroma.EmitterFunc(indentEnd),
					Mutator: chroma.Pop(1),
				},
				{
					Pattern: `(\\\\|\\:|[^:])+`,
					Type:    chroma.NameTag,
					Mutator: chroma.Push("objectrow"),
				},
			},
			"arrayvalue": {
				{
					Pattern: `\]`,
					Type:    chroma.EmitterFunc(indentEnd),
					Mutator: chroma.Pop(1),
				},
				chroma.Include("value"),
			},
			"value": {
				chroma.Include("whitespace"),
				{
					Pattern: `\{`,
					Type:    chroma.EmitterFunc(indentStart),
					Mutator: chroma.Push("object"),
				},
				{
					Pattern: `\[`,
					Type:    chroma.EmitterFunc(indentStart),
					Mutator: chroma.Push("arrayvalue"),
				},
				chroma.Include("scalar"),
			},
			"root": {
				chroma.Include("value"),
			},
		}
	},
))

ReadableLexer colorizes the output of the Readable marshaller.

Root command (entrypoint) of the CLI.

View Source
var SchemaLexer = lexers.Register(chroma.MustNewLazyLexer(
	&chroma.Config{
		Name:         "CLI Schema",
		Aliases:      []string{"schema"},
		NotMultiline: true,
		DotAll:       true,
	},
	func() chroma.Rules {
		return chroma.Rules{
			"whitespace": {
				{Pattern: `\s+`, Type: chroma.Text},
			},
			"value": {
				chroma.Include("whitespace"),
				{
					Pattern: `allOf|anyOf|oneOf`,
					Type:    chroma.NameBuiltin,
				},
				{
					Pattern: `(\()([^ )]+)`,
					Type:    chroma.ByGroups(chroma.Text, chroma.Keyword),
				},
				{
					Pattern: `([^: )]+)(:)([^ )]+)`,
					Type:    chroma.ByGroups(chroma.String, chroma.Text, chroma.Text),
				},
				{
					Pattern: `[^\n]*`,
					Type:    chroma.Text,
					Mutator: chroma.Pop(1),
				},
			},
			"row": {
				chroma.Include("whitespace"),
				{
					Pattern: `allOf|anyOf|oneOf`,
					Type:    chroma.NameBuiltin,
				},
				{
					Pattern: `([^*:\n]+)(\*?)(:)`,
					Type:    chroma.ByGroups(chroma.NameTag, chroma.GenericStrong, chroma.Text),
					Mutator: chroma.Push("value"),
				},
				{
					Pattern: `(\()([^ )]+)`,
					Type:    chroma.ByGroups(chroma.Text, chroma.Keyword),
					Mutator: chroma.Push("value"),
				},
			},
			"root": {
				chroma.Include("row"),
			},
		}
	},
))

SchemaLexer colorizes schema output.

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 Stdin interface {
	Stat() (fs.FileInfo, error)
	io.Reader
} = os.Stdin

Stdin represents the command input, which defaults to os.Stdin.

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 AddAuth

func AddAuth(name string, h AuthHandler)

AddAuth registers a new named auth handler.

func AddContentType

func AddContentType(short, name string, q float32, ct ContentType)

AddContentType adds a new content type marshaller with the given default content type name and q factor (0-1.0, higher has priority).

func AddEncoding

func AddEncoding(name string, encoding ContentEncoding)

AddEncoding adds a new content encoding with the given name.

func AddGlobalFlag

func AddGlobalFlag(name, short, description string, defaultValue interface{}, multi bool)

AddGlobalFlag will make a new global flag on the root command.

func AddLinkParser

func AddLinkParser(parser LinkParser)

AddLinkParser adds a new link parser to create standardized link relation objects on a parsed response.

func AddLoader

func AddLoader(loader Loader)

AddLoader adds a new API spec loader to the CLI.

func BestEffortSystemCertPool added in v0.7.0

func BestEffortSystemCertPool() *x509.CertPool

BestEffortSystemCertPool returns system cert pool as best effort, otherwise an empty cert pool

func CachedTransport

func CachedTransport() *httpcache.Transport

CachedTransport returns an HTTP transport with caching abilities.

func DecodeResponse

func DecodeResponse(resp *http.Response) error

DecodeResponse will replace the response body with a decoding reader if needed. Assumes the original body will be closed outside of this function.

func Defaults added in v0.3.0

func Defaults()

Defaults adds the default encodings, content types, and link parsers to the CLI.

func FixAddress added in v0.16.0

func FixAddress(addr string) string

FixAddress can convert `:8000` or `example.com` to a full URL.

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 GetExitCode added in v0.17.0

func GetExitCode() int

GetExitCode returns the exit code to use based on the last HTTP status code.

func GetLastStatus added in v0.17.0

func GetLastStatus() int

GetLastStatus returns the last HTTP status code returned by a request. A request can opt out of this via the IgnoreStatus option.

func Highlight

func Highlight(lexer string, data []byte) ([]byte, error)

Highlight a block of data with the given lexer.

func IgnoreCLIParams added in v0.20.0

func IgnoreCLIParams() requestOption

IgnoreCLIParams only applies the profile, but ignores commandline and env params

func IgnoreStatus added in v0.17.0

func IgnoreStatus() requestOption

IgnoreStatus ignores the response status code.

func Init

func Init(name string, version string)

Init will set up the CLI.

func InvalidateCachedTransport

func InvalidateCachedTransport() http.RoundTripper

InvalidateCachedTransport returns an HTTP transport which will not read cached items (it deletes them) and then refreshes the cache when new items are fetched.

func LogDebug

func LogDebug(format string, values ...interface{})

LogDebug logs a debug message if --rsh-verbose (-v) was passed.

func LogDebugRequest

func LogDebugRequest(req *http.Request)

LogDebugRequest logs the request in a debug message if verbose output is enabled.

func LogDebugResponse

func LogDebugResponse(start time.Time, resp *http.Response)

LogDebugResponse logs the response in a debug message if verbose output is enabled.

func LogError

func LogError(format string, values ...interface{})

LogError logs an error message.

func LogInfo

func LogInfo(format string, values ...interface{})

LogInfo logs an info message.

func LogWarning

func LogWarning(format string, values ...interface{})

LogWarning logs a warning message.

func MakeRequest

func MakeRequest(req *http.Request, options ...requestOption) (*http.Response, error)

MakeRequest makes an HTTP request using the default client. It adds the user-agent, auth, and any passed headers or query params to the request before sending it out on the wire. If verbose mode is enabled, it will print out both the request and response.

func MakeRequestAndFormat

func MakeRequestAndFormat(req *http.Request)

MakeRequestAndFormat is a convenience function for calling `GetParsedResponse` and then calling the default formatter's `Format` function with the parsed response. Panics on error.

func Marshal

func Marshal(contentType string, value interface{}) ([]byte, error)

Marshal a value to the given content type, e.g. `application/json`.

func MarshalReadable

func MarshalReadable(v interface{}) ([]byte, error)

MarshalReadable marshals a value into a human-friendly readable format.

func MarshalShort added in v0.15.0

func MarshalShort(name string, pretty bool, value any) ([]byte, error)

MarshalShort marshals a value given a short name, e.g. `json`. If pretty is true then the output will be pretty/indented if the marshaler supports pretty output (e.g. JSON).

func MinCachedTransport

func MinCachedTransport(min time.Duration) *httpcache.Transport

MinCachedTransport returns an HTTP transport with caching abilities and a minimum cache duration for any responses if no cache headers are set.

func ParseLinks(base *url.URL, resp *Response) error

ParseLinks uses all registered LinkParsers to parse links for a response.

func Run

func Run() (returnErr error)

Run the CLI! Parse arguments, make requests, print responses.

func Unmarshal

func Unmarshal(contentType string, data []byte, value interface{}) error

Unmarshal raw data from the given content type into a value.

func WithClient

func WithClient(c *http.Client) requestOption

WithClient sets the client to use for the request.

func WithoutLog

func WithoutLog() requestOption

WithoutLog disabled debug logging for the given request/response.

Types

type API

type API struct {
	RestishVersion string      `json:"restish_version" yaml:"restish_version"`
	Short          string      `json:"short" yaml:"short"`
	Long           string      `json:"long,omitempty" yaml:"long,omitempty"`
	Operations     []Operation `json:"operations,omitempty" yaml:"operations,omitempty"`
	Auth           []APIAuth   `json:"auth,omitempty" yaml:"auth,omitempty"`
	AutoConfig     AutoConfig  `json:"auto_config,omitempty" yaml:"auto_config,omitempty"`
}

API represents an abstracted API description used to build CLI commands around available resources, operations, and links. An API is produced by a Loader and cached by the CLI in-between runs when possible.

func Load

func Load(entrypoint string, root *cobra.Command) (API, error)

Load will hydrate the command tree for an API, possibly refreshing the API spec if the cache is out of date.

func (*API) Merge

func (a *API) Merge(other API)

Merge two APIs together. Takes the description if none is set and merges operations. Ignores auth - if that differs then create another API instead.

type APIAuth

type APIAuth struct {
	Name   string            `json:"name" yaml:"name"`
	Params map[string]string `json:"params,omitempty" yaml:"params,omitempty"`
}

APIAuth describes the auth type and parameters for an API.

type APIConfig

type APIConfig struct {
	Base          string                 `json:"base" yaml:"base"`
	OperationBase string                 `json:"operation_base,omitempty" yaml:"operation_base,omitempty" mapstructure:"operation_base,omitempty"`
	SpecFiles     []string               `json:"spec_files,omitempty" yaml:"spec_files,omitempty" mapstructure:"spec_files,omitempty"`
	Profiles      map[string]*APIProfile `json:"profiles,omitempty" yaml:"profiles,omitempty" mapstructure:",omitempty"`
	TLS           *TLSConfig             `json:"tls,omitempty" yaml:"tls,omitempty" mapstructure:",omitempty"`
	// contains filtered or unexported fields
}

APIConfig describes per-API configuration options like the base URI and auth scheme, if any.

func (APIConfig) GetPrettyDisplay added in v0.14.0

func (a APIConfig) GetPrettyDisplay(outFormat string) ([]byte, error)

Return colorized string of configuration in JSON or YAML

func (APIConfig) Save

func (a APIConfig) Save() error

Save the API configuration to disk.

type APIProfile

type APIProfile struct {
	Base    string            `json:"base,omitempty" yaml:"base,omitempty"`
	Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
	Query   map[string]string `json:"query,omitempty" yaml:"query,omitempty"`
	Auth    *APIAuth          `json:"auth,omitempty" yaml:"auth,omitempty"`
}

APIProfile contains account-specific API information

type AuthHandler

type AuthHandler interface {
	// Parameters returns an ordered list of required and optional input
	// parameters for this auth handler. Used when configuring an API.
	Parameters() []AuthParam

	// OnRequest applies auth to an outgoing request before it hits the wire.
	OnRequest(req *http.Request, key string, params map[string]string) error
}

AuthHandler is used to register new authentication handlers that will apply auth to an outgoing request as needed.

type AuthParam

type AuthParam struct {
	Name     string
	Help     string
	Required bool
}

AuthParam describes an auth input parameter for an AuthHandler.

type AutoConfig added in v0.5.0

type AutoConfig struct {
	Headers map[string]string        `json:"headers,omitempty" yaml:"headers,omitempty"`
	Prompt  map[string]AutoConfigVar `json:"prompt,omitempty" yaml:"prompt,omitempty"`
	Auth    APIAuth                  `json:"auth,omitempty" yaml:"auth,omitempty"`
}

AutoConfig holds an API's automatic configuration settings for the CLI. These are advertised via OpenAPI extension and picked up by the CLI to make it easier to get started using an API.

type AutoConfigVar added in v0.5.0

type AutoConfigVar struct {
	Description string        `json:"description,omitempty" yaml:"description,omitempty"`
	Example     string        `json:"example,omitempty" yaml:"example,omitempty"`
	Default     interface{}   `json:"default,omitempty" yaml:"default,omitempty"`
	Enum        []interface{} `json:"enum,omitempty" yaml:"enum,omitempty"`

	// Exclude the value from being sent to the server. This essentially makes
	// it a value which is only used in param templates.
	Exclude bool `json:"exclude,omitempty"`
}

AutoConfigVar represents a variable given by the user when prompted during auto-configuration setup of an API.

type BasicAuth

type BasicAuth struct{}

BasicAuth implements HTTP Basic authentication.

func (*BasicAuth) OnRequest

func (a *BasicAuth) OnRequest(req *http.Request, key string, params map[string]string) error

OnRequest gets run before the request goes out on the wire.

func (*BasicAuth) Parameters

func (a *BasicAuth) Parameters() []AuthParam

Parameters define the HTTP Basic Auth parameter names.

type BrotliEncoding

type BrotliEncoding struct{}

BrotliEncoding supports RFC 7932 Brotli content encoding.

func (BrotliEncoding) Reader

func (b BrotliEncoding) Reader(stream io.Reader) (io.Reader, error)

Reader returns a new reader for the stream that removes the brotli encoding.

type CBOR

type CBOR struct{}

CBOR describes content types like `application/cbor` or `application/foo+cbor`. http://cbor.io/

func (CBOR) Detect

func (c CBOR) Detect(contentType string) bool

Detect if the content type is YAML.

func (CBOR) Marshal

func (c CBOR) Marshal(value interface{}) ([]byte, error)

Marshal the value to encoded YAML.

func (CBOR) Unmarshal

func (c CBOR) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from encoded YAML.

type ContentEncoding

type ContentEncoding interface {
	Reader(stream io.Reader) (io.Reader, error)
}

ContentEncoding is used to encode/decode content for transfer over the wire, for example with gzip.

type ContentType

type ContentType interface {
	Detect(contentType string) bool
	Marshal(value interface{}) ([]byte, error)
	Unmarshal(data []byte, value interface{}) error
}

ContentType is used to marshal/unmarshal data to various formats.

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 `rsh-filter` and `rsh-output-format` configuration values to perform JMESPath queries and set JSON (default) or YAML output.

func NewDefaultFormatter

func NewDefaultFormatter(tty, color bool) *DefaultFormatter

NewDefaultFormatter creates a new formatted with autodetected TTY capabilities.

func (*DefaultFormatter) Format

func (f *DefaultFormatter) Format(resp Response) error

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

type DeflateEncoding added in v0.18.0

type DeflateEncoding struct{}

DeflateEncoding supports gzip-encoded response content.

func (DeflateEncoding) Reader added in v0.18.0

func (g DeflateEncoding) Reader(stream io.Reader) (io.Reader, error)

Reader returns a new reader for the stream that removes the gzip encoding.

type ExternalToolAuth added in v0.15.0

type ExternalToolAuth struct{}

ExternalToolAuth defers authentication to a third party tool. This avoids baking all possible authentication implementations inside restish itself.

func (*ExternalToolAuth) OnRequest added in v0.15.0

func (a *ExternalToolAuth) OnRequest(req *http.Request, key string, params map[string]string) error

OnRequest gets run before the request goes out on the wire. The supplied commandline argument is ran with a JSON input and expects a JSON output on stdout

func (*ExternalToolAuth) Parameters added in v0.15.0

func (a *ExternalToolAuth) Parameters() []AuthParam

Parameters defines the ExternalToolAuth parameter names. A single parameter is supported and required: `commandline` which points to the tool to call to authenticate a request.

type Gron added in v0.18.0

type Gron struct{}

Gron describes an output format for easier grepping. This is based on the excellent https://github.com/tomnomnom/gron tool, but makes the format available as a built-in Restish output option.

func (Gron) Detect added in v0.18.0

func (t Gron) Detect(contentType string) bool

Detect if the content type is gron-able.

func (Gron) Marshal added in v0.18.0

func (t Gron) Marshal(value interface{}) ([]byte, error)

Marshal the value to a gron string.

func (Gron) Unmarshal added in v0.18.0

func (t Gron) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from a gron string.

type GzipEncoding

type GzipEncoding struct{}

GzipEncoding supports gzip-encoded response content.

func (GzipEncoding) Reader

func (g GzipEncoding) Reader(stream io.Reader) (io.Reader, error)

Reader returns a new reader for the stream that removes the gzip encoding.

type HALParser

type HALParser struct{}

HALParser parses HAL hypermedia links. Ignores curies.

func (h HALParser) ParseLinks(resp *Response) error

ParseLinks processes the links in a parsed response.

type Ion

type Ion struct{}

Ion describes content types like `application/ion`.

func (Ion) Detect

func (i Ion) Detect(contentType string) bool

Detect if the content type is Ion.

func (Ion) Marshal

func (i Ion) Marshal(value interface{}) ([]byte, error)

Marshal the value to encoded binary Ion.

func (Ion) MarshalPretty added in v0.15.0

func (i Ion) MarshalPretty(value interface{}) ([]byte, error)

MarshalPretty the value to pretty encoded JSON.

func (Ion) Unmarshal

func (i Ion) Unmarshal(data []byte, value interface{}) error

Unmarshal the value form encoded binary or text Ion.

type JSON

type JSON struct{}

JSON describes content types like `application/json` or `application/problem+json`.

func (JSON) Detect

func (j JSON) Detect(contentType string) bool

Detect if the content type is JSON.

func (JSON) Marshal

func (j JSON) Marshal(value interface{}) ([]byte, error)

Marshal the value to encoded JSON.

func (JSON) MarshalPretty added in v0.15.0

func (j JSON) MarshalPretty(value interface{}) ([]byte, error)

MarshalPretty the value to pretty encoded JSON.

func (JSON) Unmarshal

func (j JSON) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from encoded JSON.

type JSONAPIParser

type JSONAPIParser struct{}

JSONAPIParser parses JSON:API hypermedia links.

func (j JSONAPIParser) ParseLinks(resp *Response) error

ParseLinks processes the links in a parsed response.

type Link struct {
	Rel string `json:"rel"`
	URI string `json:"uri"`
}

Link describes a hypermedia link to another resource.

type LinkHeaderParser

type LinkHeaderParser struct{}

LinkHeaderParser parses RFC 5988 HTTP link relation headers.

func (l LinkHeaderParser) ParseLinks(resp *Response) error

ParseLinks processes the links in a parsed response.

type LinkParser

type LinkParser interface {
	ParseLinks(resp *Response) error
}

LinkParser parses link relationships in a response.

type Links map[string][]*Link

Links represents a map of `rel` => list of linke relations.

type Loader

type Loader interface {
	LocationHints() []string
	Detect(resp *http.Response) bool
	Load(entrypoint, spec url.URL, resp *http.Response) (API, error)
}

Loader is used to detect and load an API spec, turning it into CLI commands.

type MsgPack

type MsgPack struct{}

MsgPack describes content types like `application/msgpack` or `application/foo+msgpack`. https://msgpack.org/

func (MsgPack) Detect

func (m MsgPack) Detect(contentType string) bool

Detect if the content type is YAML.

func (MsgPack) Marshal

func (m MsgPack) Marshal(value interface{}) ([]byte, error)

Marshal the value to encoded YAML.

func (MsgPack) Unmarshal

func (m MsgPack) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from encoded YAML.

type Operation

type Operation struct {
	Name          string   `json:"name" yaml:"name"`
	Group         string   `json:"group,omitempty" yaml:"group,omitempty"`
	Aliases       []string `json:"aliases,omitempty" yaml:"aliases,omitempty"`
	Short         string   `json:"short,omitempty" yaml:"short,omitempty"`
	Long          string   `json:"long,omitempty" yaml:"long,omitempty"`
	Method        string   `json:"method,omitempty" yaml:"method,omitempty"`
	URITemplate   string   `json:"uri_template" yaml:"uri_template"`
	PathParams    []*Param `json:"path_params,omitempty" yaml:"path_params,omitempty"`
	QueryParams   []*Param `json:"query_params,omitempty" yaml:"query_params,omitempty"`
	HeaderParams  []*Param `json:"header_params,omitempty" yaml:"header_params,omitempty"`
	BodyMediaType string   `json:"body_media_type,omitempty" yaml:"body_media_type,omitempty"`
	Examples      []string `json:"examples,omitempty" yaml:"examples,omitempty"`
	Hidden        bool     `json:"hidden,omitempty" yaml:"hidden,omitempty"`
	Deprecated    string   `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
}

Operation represents an API action, e.g. list-things or create-user

type Param

type Param struct {
	Type        string      `json:"type" yaml:"type"`
	Name        string      `json:"name" yaml:"name"`
	DisplayName string      `json:"display_name,omitempty" yaml:"display_name,omitempty"`
	Description string      `json:"description,omitempty" yaml:"description,omitempty"`
	Style       Style       `json:"style,omitempty" yaml:"style,omitempty"`
	Explode     bool        `json:"explode,omitempty" yaml:"explide,omitempty"`
	Default     interface{} `json:"default,omitempty" yaml:"default,omitempty"`
	Example     interface{} `json:"example,omitempty" yaml:"example,omitempty"`
}

Param represents an API operation input parameter.

func (Param) AddFlag

func (p Param) AddFlag(flags *pflag.FlagSet) interface{}

AddFlag adds a new option flag to a command's flag set for this parameter.

func (Param) OptionName added in v0.13.1

func (p Param) OptionName() string

OptionName returns the commandline option name for this parameter.

func (Param) Parse

func (p Param) Parse(value string) (interface{}, error)

Parse the parameter from a string input (e.g. command line argument)

func (Param) Serialize

func (p Param) Serialize(value interface{}) []string

Serialize the parameter based on the type/style/explode configuration.

type PathBuffer added in v0.18.0

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

PathBuffer builds up a path string from multiple parts.

func NewPathBuffer added in v0.18.0

func NewPathBuffer(parts [][]byte) *PathBuffer

NewPathBuffer creates a new path buffer with the given underlying initial data loaded into it.

func (*PathBuffer) Bytes added in v0.18.0

func (b *PathBuffer) Bytes() []byte

func (*PathBuffer) Pop added in v0.18.0

func (b *PathBuffer) Pop()

func (*PathBuffer) Push added in v0.18.0

func (b *PathBuffer) Push(s string)

type PrettyMarshaller added in v0.15.0

type PrettyMarshaller interface {
	MarshalPretty(value any) ([]byte, error)
}

PrettyMarshaller describes an optional method that ContentTypes can implement to provide nicer output for humans. This is optional because only some formats support the pretty/indented concept.

type Readable added in v0.15.0

type Readable struct{}

Readable describes a readable marshaller.

func (Readable) Detect added in v0.15.0

func (r Readable) Detect(contentType string) bool

Detect if the content type is Ion.

func (Readable) Marshal added in v0.15.0

func (r Readable) Marshal(value interface{}) ([]byte, error)

Marshal the value to encoded binary Ion.

func (Readable) Unmarshal added in v0.15.0

func (i Readable) Unmarshal(data []byte, value interface{}) error

Unmarshal the value form encoded binary or text Ion.

type Request added in v0.15.0

type Request struct {
	Method string      `json:"method"`
	URI    string      `json:"uri"`
	Header http.Header `json:"headers"`
	Body   string      `json:"body"`
}

Request is used to exchange requests with the external tool.

type Response

type Response struct {
	Proto   string            `json:"proto"`
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	Links   Links             `json:"links"`
	Body    interface{}       `json:"body"`
}

Response describes a parsed HTTP response which can be marshalled to enable printing and filtering/projection.

func GetParsedResponse

func GetParsedResponse(req *http.Request, options ...requestOption) (Response, error)

GetParsedResponse makes a request and gets the parsed response back. It handles any auto-pagination or linking that needs to be done and may return a psuedo-responsse that is a combination of all responses.

func ParseResponse

func ParseResponse(resp *http.Response) (Response, error)

ParseResponse takes an HTTP response and tries to parse it using the registered content types. It returns a map representing the request,

func (Response) Map

func (r Response) Map() map[string]any

Map returns a map representing this response matching the encoded JSON.

type ResponseFormatter

type ResponseFormatter interface {
	Format(Response) 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 SirenParser

type SirenParser struct{}

SirenParser parses Siren hypermedia links.

func (s SirenParser) ParseLinks(resp *Response) error

ParseLinks processes the links in a parsed response.

type Style

type Style int

Style is an encoding style for parameters.

const (
	// StyleSimple corresponds to OpenAPI 3 simple parameters
	StyleSimple Style = iota

	// StyleForm corresponds to OpenAPI 3 form parameters
	StyleForm
)

type TLSConfig added in v0.7.0

type TLSConfig struct {
	InsecureSkipVerify bool   `json:"insecure,omitempty" yaml:"insecure,omitempty" mapstructure:"insecure"`
	Cert               string `json:"cert,omitempty" yaml:"cert,omitempty"`
	Key                string `json:"key,omitempty" yaml:"key,omitempty"`
	CACert             string `json:"ca_cert,omitempty" yaml:"ca_cert,omitempty" mapstructure:"ca_cert"`
}

TLSConfig contains the TLS setup for the HTTP client

type Table added in v0.15.0

type Table struct{}

Table describes an output format for terminal tables.

func (Table) Detect added in v0.15.0

func (t Table) Detect(contentType string) bool

Detect if the content type is table.

func (Table) Marshal added in v0.15.0

func (t Table) Marshal(value interface{}) ([]byte, error)

Marshal the value to a table string.

func (Table) Unmarshal added in v0.15.0

func (t Table) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from a table string.

type TerrificallySimpleJSONParser

type TerrificallySimpleJSONParser struct{}

TerrificallySimpleJSONParser parses `self` links from JSON-like formats.

func (t TerrificallySimpleJSONParser) ParseLinks(resp *Response) error

ParseLinks processes the links in a parsed response.

type Text

type Text struct{}

Text describes content types like `text/plain` or `text/html`.

func (Text) Detect

func (t Text) Detect(contentType string) bool

Detect if the content type is text.

func (Text) Marshal

func (t Text) Marshal(value interface{}) ([]byte, error)

Marshal the value to a text string.

func (Text) Unmarshal

func (t Text) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from a text string.

type YAML

type YAML struct{}

YAML describes content types like `application/yaml` or `application/foo+yaml`.

func (YAML) Detect

func (y YAML) Detect(contentType string) bool

Detect if the content type is YAML.

func (YAML) Marshal

func (y YAML) Marshal(value interface{}) ([]byte, error)

Marshal the value to encoded YAML.

func (YAML) Unmarshal

func (y YAML) Unmarshal(data []byte, value interface{}) error

Unmarshal the value from encoded YAML.

Jump to

Keyboard shortcuts

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