flags

package
v2.39.2 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2024 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FlagDataName                  = "data"
	FlagDataTemplateName          = "template"
	FlagDataTemplateVariablesName = "templateVars"
	FlagOutputTemplate            = "outputTemplate"
	FlagProcessingModeName        = "processingMode"
	FlagWithTotalPages            = "withTotalPages"
	FlagWithTotalElements         = "withTotalElements"
	FlagPageSize                  = "pageSize"
	FlagCurrentPage               = "currentPage"
	FlagNullInput                 = "nullInput"
	FlagAllowEmptyPipe            = "allowEmptyPipe"
	FlagReadFromPipeText          = "-"
	FlagReadFromPipeJSON          = "-."
)
View Source
const (
	AnnotationValuePipelineAlias      = "pipelineAliases"
	AnnotationValueFromPipeline       = "valueFromPipeline"
	AnnotationValueFromPipelineData   = "valueFromPipeline.data"
	AnnotationValueCollectionProperty = "collectionProperty"
	AnnotationValueDeprecated         = "deprecatedNotice"
	AnnotationValueSemanticMethod     = "semanticMethod"
)

Variables

View Source
var ErrFlagDoesNotExist = errors.New("Flag does not exist")
View Source
var ErrFlagError = errors.New("failed to parse arguments")
View Source
var ErrInvalidDuration = errors.New("invalid duration")

ErrInvalidDuration invalid duration

View Source
var ErrInvalidIDFormat = errors.New("invalid id format")

ErrInvalidIDFormat invalid ID format

View Source
var ErrInvalidJSON = errors.New("invalid json")
View Source
var ErrParameterMissing error = errors.New("missing required parameter")
View Source
var ErrReadFile = errors.New("failed to read file")
View Source
var ErrUnsupportedType = errors.New("unsupported type")

Functions

func BuildCumulocityQuery

func BuildCumulocityQuery(cmd *cobra.Command, fixedParts []string, orderBy string) func([]byte) []byte

func ExactArgsOrExample

func ExactArgsOrExample(n int) cobra.PositionalArgs

ExactArgsOrExample returns an error if there are not exactly n args or --exapmles is not used

func FilterJsonLines

func FilterJsonLines(line []byte) bool

func GetCollectionPropertyFromAnnotation

func GetCollectionPropertyFromAnnotation(cmd *cobra.Command) (value string)

GetCollectionPropertyFromAnnotation returns the collection property path used to return a subset of the json response by default

func GetDeprecationNoticeFromAnnotation added in v2.15.0

func GetDeprecationNoticeFromAnnotation(cmd *cobra.Command) (value string)

GetDeprecationNoticeFromAnnotation returns the deprecated notice if present

func GetDuration

func GetDuration(v string, inferUnit bool, unit time.Duration) (time.Duration, error)

GetDuration get duration with an option of assuming the string is referring to seconds

func GetDurationFlag

func GetDurationFlag(cmd *cobra.Command, name string, inferUnit bool, unit time.Duration) (time.Duration, error)

func GetFlagStringValues

func GetFlagStringValues(cmd *cobra.Command, name string) ([]string, error)

GetFlagStringValues get string slice from either a string slice or string flag

func GetIDArray

func GetIDArray(values []string) (ids []string)

func GetIDs

func GetIDs(cmd *cobra.Command, args []string) (ids []string)

GetIDs returns a list of IDs --id 1234,1234 (comma seperated list (without spaces!)) --id "22437097744 1235" [22437097744, 1235] --id 22437097744 1235,1234 (requires positional arguments as well) --id 22437097744 1235,1234 asdfasdf asdfasdf will be ignored as it does not match the pattern

func GetSemanticMethodFromAnnotation added in v2.22.1

func GetSemanticMethodFromAnnotation(cmd *cobra.Command) (value string)

GetSemanticMethodFromAnnotation returns semantic REST method related to the action from the annotations

func GetStringFromAnnotation

func GetStringFromAnnotation(cmd *cobra.Command, path string) (value string)

GetStringFromAnnotation returns a string value stored in the annotations

func HasValueFromPipeline

func HasValueFromPipeline(cmd *cobra.Command, name string) bool

HasValueFromPipeline checks if the given flag name supported values from pipeline It checks the command for a special annotation

func NewFlagFileContents

func NewFlagFileContents(cmd *cobra.Command, name string) (iterator.Iterator, error)

NewFlagFileContents returns iterator which will interate over the lines in a file

func NewFlagWithPipeIterator

func NewFlagWithPipeIterator(cmd *cobra.Command, pipeOpt *PipelineOptions, supportsPipeline bool) (iterator.Iterator, error)

NewFlagWithPipeIterator creates an iterator from a command argument or from the pipeline It will automatically try to get the value from a String or a StringSlice flag

func ResolveTemplate added in v2.32.0

func ResolveTemplate(value string, pathResolver Resolver) string

func ShouldReadFromPipeline added in v2.20.2

func ShouldReadFromPipeline(v string) bool

func UnpackGetterOptions

func UnpackGetterOptions(defaultFormat string, options ...string) (src string, dst string, formatter string)

func ValidateID

func ValidateID(v []byte) (err error)

ValidateID returns an error if the input value does not match an id

func WithBody

func WithBody(cmd *cobra.Command, body *mapbuilder.MapBuilder, inputIterators *RequestInputIterators, opts ...GetOption) (err error)

WithBody returns a body from given command line arguments

func WithC8YQueryOptions

func WithC8YQueryOptions(cmd *cobra.Command, inputIterators *RequestInputIterators, opts ...GetOption) ([]string, error)

WithC8YQueryOptions applies given options to a URL Query parameters

func WithFormDataOptions

func WithFormDataOptions(cmd *cobra.Command, form map[string]io.Reader, inputIterators *RequestInputIterators, opts ...GetOption) (err error)

WithFormDataOptions returns a body from given command line arguments

func WithHeaders

func WithHeaders(cmd *cobra.Command, header http.Header, inputIterators *RequestInputIterators, opts ...GetOption) (err error)

WithHeaders sets header values from command line arguments

func WithOptions

func WithOptions(cmd *cobra.Command, opts ...Option) *cobra.Command

WithOptions applies given options to the command

func WithPathParameters

func WithPathParameters(cmd *cobra.Command, path *StringTemplate, inputIterators *RequestInputIterators, opts ...GetOption) (err error)

WithPathParameters returns a path parameter values given from command line arguments

func WithQueryParameters

func WithQueryParameters(cmd *cobra.Command, query *QueryTemplate, inputIterators *RequestInputIterators, opts ...GetOption) (err error)

WithQueryParameters returns a query parameter values given from command line arguments

func WithRequestOptions

func WithRequestOptions(cmd *cobra.Command, args []string, req *c8y.RequestOptions, builderOpts *RequestBuilder) (err error)

Types

type Action

type Action interface {
	Run(interface{}) (interface{}, error)
}

type AnyString added in v2.20.0

type AnyString string

AnyString string type which allows also empty values

type DefaultTemplateString

type DefaultTemplateString string

type DurationGenerator

type DurationGenerator func(time.Duration) time.Duration

func GetDurationGenerator

func GetDurationGenerator(cmd *cobra.Command, minFlag, maxFlag string, inferUnit bool, unit time.Duration) (DurationGenerator, error)

GetDurationGenerator returns a random duration generator func. The generator will return a random duration between the given min or max

type FilePath

type FilePath string

FilePath is a string representation of a file path

type GetOption

type GetOption func(cmd *cobra.Command, inputIterators *RequestInputIterators) (name string, value interface{}, err error)

GetOption gets the value from a flag and returns the value which can be set accordingly

func NewTimestampFromRelative added in v2.31.0

func NewTimestampFromRelative(encode bool, utc bool, opts ...string) GetOption

func WithBoolValue

func WithBoolValue(opts ...string) GetOption

WithBoolValue adds a boolean value from cli arguments to a query parameter

func WithCertificateFile added in v2.13.0

func WithCertificateFile(opts ...string) GetOption

WithCertificateFile adds a PEM certificate file contents

func WithCumulocityQuery added in v2.15.0

func WithCumulocityQuery(queryOptions []GetOption, opts ...string) GetOption

WithCumulocityQuery build a Cumulocity Query Expression

func WithCurrentPage

func WithCurrentPage() GetOption

func WithCustomStringSlice

func WithCustomStringSlice(valuesFunc func() ([]string, error), opts ...string) GetOption

WithCustomStringSlice adds string map values from cli arguments

func WithCustomStringValue

func WithCustomStringValue(transform func([]byte) []byte, targetFunc func() string, opts ...string) GetOption

WithCustomStringValue add a custom string value with a custom tranform function

func WithDataFlagValue

func WithDataFlagValue() GetOption

func WithDataValue

func WithDataValue(opts ...string) GetOption

func WithDataValueAdvanced

func WithDataValueAdvanced(stripCumulocityKeys bool, raw bool, opts ...string) GetOption

WithDataValueAdvanced adds json or shorthand json parsing with additional option to strip the Cumulocity properties from the input

func WithDefaultBoolValue

func WithDefaultBoolValue(opts ...string) GetOption

WithDefaultBoolValue sets a boolean value regardless if the value has been provided by the flag or not

func WithDefaultTemplateString

func WithDefaultTemplateString(value string) GetOption

func WithEncodedRelativeTimestamp

func WithEncodedRelativeTimestamp(opts ...string) GetOption

WithEncodedRelativeTimestamp adds a encoded timestamp (string) value from cli arguments

func WithEncodedRelativeTimestampUTC added in v2.31.0

func WithEncodedRelativeTimestampUTC(opts ...string) GetOption

func WithFileBaseName

func WithFileBaseName(opts ...string) GetOption

WithFileBaseName adds the filename basename from cli arguments

func WithFileContentsAsString added in v2.30.0

func WithFileContentsAsString(opts ...string) GetOption

WithFileContentsAsString read the file contents and provide the value as a string

func WithFileMIMEType

func WithFileMIMEType(name string, opts ...string) GetOption

WithFileMIMEType adds the file MIME type from cli arguments

func WithFilePath

func WithFilePath(opts ...string) GetOption

WithFilePath adds a file path from cli arguments

func WithFileReader

func WithFileReader(opts ...string) GetOption

WithFileReader adds file (as reader) from cli arguments

func WithFloatValue

func WithFloatValue(opts ...string) GetOption

WithFloatValue adds a float (float32) value from cli arguments

func WithFormDataFile

func WithFormDataFile(srcFile string, srcData string) []GetOption

WithFormDataFile adds form data from cli arguments

func WithFormDataFileAndInfo

func WithFormDataFileAndInfo(srcFile string, srcData string) []GetOption

WithFormDataFileAndInfo adds form data from cli arguments

func WithFormDataFileAndInfoWithTemplateSupport added in v2.14.0

func WithFormDataFileAndInfoWithTemplateSupport(templateResolver Resolver, srcFile string, srcData string) []GetOption

func WithIntValue

func WithIntValue(opts ...string) GetOption

WithIntValue adds a integer (int) value from cli arguments

func WithInventoryChildType added in v2.15.0

func WithInventoryChildType(opts ...string) GetOption

func WithOptionalFragment

func WithOptionalFragment(opts ...string) GetOption

WithOptionalFragment adds fragment if the boolean value is true a boolean value from cli arguments to a query parameter

func WithOverrideValue

func WithOverrideValue(opts ...string) GetOption

WithOverrideValue adds an options to override a value via cli arguments. Pipeline input is ignored if this value is present However if the argument refers to an existing file then the value will be ignored!

func WithPageSize

func WithPageSize() GetOption

func WithPipelineIterator

func WithPipelineIterator(opts *PipelineOptions) GetOption

WithPipelineIterator adds pipeline support from cli arguments

func WithProcessingModeValue

func WithProcessingModeValue() GetOption

WithProcessingModeValue adds the processing module value from cli arguments

func WithRelativeDate

func WithRelativeDate(encode bool, opts ...string) GetOption

WithRelativeDate adds a date (only, no time) (string) value from cli arguments

func WithRelativeTimestamp

func WithRelativeTimestamp(opts ...string) GetOption

WithRelativeTimestamp adds a timestamp (string) value from cli arguments

func WithRelativeTimestampUTC added in v2.31.0

func WithRelativeTimestampUTC(opts ...string) GetOption

func WithRequiredProperties

func WithRequiredProperties(values ...string) GetOption

func WithRequiredTemplateString

func WithRequiredTemplateString(value string) GetOption

func WithStaticStringValue

func WithStaticStringValue(opts ...string) GetOption

WithStaticStringValue add a fixed string value

func WithStaticStringValue2 added in v2.20.0

func WithStaticStringValue2(opts ...string) GetOption

func WithStringDefaultValue

func WithStringDefaultValue(defaultValue string, opts ...string) GetOption

WithStringDefaultValue adds a string value from cli arguments

func WithStringFormValue added in v2.14.0

func WithStringFormValue(opts ...string) GetOption

WithStringFormValue adds string (as reader) from cli arguments

func WithStringSliceCSV

func WithStringSliceCSV(opts ...string) GetOption

WithStringSliceCSV adds a string slice as comma separated variables from cli arguments

func WithStringSliceValues

func WithStringSliceValues(opts ...string) GetOption

WithStringSliceValues adds a string slice from cli arguments

func WithStringValue

func WithStringValue(opts ...string) GetOption

WithStringValue adds a string value from cli arguments

func WithTemplateOptions

func WithTemplateOptions(templateName string, variablesName string, pathResolver Resolver) []GetOption

func WithTemplateString

func WithTemplateString(value string, applyLast bool) GetOption

func WithTemplateValue

func WithTemplateValue(src string, pathResolver Resolver) GetOption

func WithTemplateVariablesValue

func WithTemplateVariablesValue(src ...string) GetOption

func WithTotalElements added in v2.16.0

func WithTotalElements() GetOption

func WithTotalPages

func WithTotalPages() GetOption

func WithVersion

func WithVersion(fallbackSrc string, opts ...string) GetOption

type Option

type Option func(*cobra.Command) *cobra.Command

Option adds flags to a given command

func WithBatchOptions

func WithBatchOptions(acceptInputFile bool) Option

WithBatchOptions adds support for batch options

func WithCollectionProperty

func WithCollectionProperty(property string) Option

WithCollectionProperty adds the default property to be plucked from the raw json response so that the important information is returned by default

func WithCommonCumulocityQueryOptions

func WithCommonCumulocityQueryOptions() Option

WithCommonCumulocityQueryOptions adds support for common query parameter options like query, orderBy etc.

func WithData

func WithData() Option

WithData adds support for data input

func WithDeprecationNotice added in v2.15.0

func WithDeprecationNotice(message string) Option

WithDeprecationNotice marks a commands as being deprecated

func WithExtendedPipelineSupport

func WithExtendedPipelineSupport(name string, property string, required bool, aliases ...string) Option

func WithPipelineAliases added in v2.17.0

func WithPipelineAliases(property string, aliases ...string) Option

WithPipelineAliases adds a list of aliases for a flag if it is selected to be sourced from the pipeline

func WithPipelineSupport

func WithPipelineSupport(name string) Option

WithPipelineSupport adds support for pipeline to a argument

func WithProcessingMode

func WithProcessingMode() Option

WithProcessingMode adds support for processing mode

func WithRuntimePipelineProperty added in v2.17.0

func WithRuntimePipelineProperty() Option

func WithSemanticMethod added in v2.22.1

func WithSemanticMethod(v string) Option

WithSemanticMethod sets a semantic REST method which may be different to the actual REST method used useful to be more descriptive about how the action should behave (e.g. prompting).

func WithTemplateNoCompletion added in v2.18.0

func WithTemplateNoCompletion() Option

WithTemplateNoCompletion adds support for templates

type ParameterError

type ParameterError struct {
	Name string

	Err error
}

func (*ParameterError) Error

func (e *ParameterError) Error() string

type PipelineOptions

type PipelineOptions struct {
	Name        string              `json:"name"`
	Required    bool                `json:"required"`
	EmptyPipe   bool                `json:"allowEmptyPipe"`
	Disabled    bool                `json:"disabled"`
	Property    string              `json:"property"`
	Aliases     []string            `json:"aliases"`
	IsID        bool                `json:"isID"`
	Values      []string            `json:"values"`
	Validator   iterator.Validator  `json:"-"`
	Formatter   func([]byte) []byte `json:"-"`
	Format      string              `json:"-"`
	InputFilter func([]byte) bool   `json:"-"`
	PostActions []Action            `json:"-"`
}

func GetPipeOptionsFromAnnotation

func GetPipeOptionsFromAnnotation(cmd *cobra.Command) (options *PipelineOptions, err error)

GetPipeOptionsFromAnnotation returns the pipeline options stored in the annotations

type QueryTemplate

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

QueryTemplate is an iterator that can be used to construct HTTP request queries

func NewQueryTemplate

func NewQueryTemplate() *QueryTemplate

NewQueryTemplate returns a new query iterator template

func (*QueryTemplate) Execute

func (b *QueryTemplate) Execute(ignoreIterators bool) (query url.Values, input any, err error)

Execute evalulates the variables and returns a query parameters which can be used for rest requests

func (*QueryTemplate) GetNext

func (b *QueryTemplate) GetNext() ([]byte, interface{}, error)

GetNext returns the next template path

func (*QueryTemplate) GetQueryUnescape

func (b *QueryTemplate) GetQueryUnescape(ignoreIterators bool) (string, error)

GetQueryUnescape returns the unescaped query. User can choose whether iterators are evalulated or not

func (*QueryTemplate) HasVariable

func (b *QueryTemplate) HasVariable(name string) bool

HasVariable returns true if the variable has already been defined

func (*QueryTemplate) IsBound

func (b *QueryTemplate) IsBound() bool

IsBound return true if the iterator is bound

func (*QueryTemplate) SetVariable

func (b *QueryTemplate) SetVariable(name string, value interface{})

SetVariable sets a give path variable which will be evalulated when fetching the next value

type RawString

type RawString string

RawString raw string type

type RequestBuilder

type RequestBuilder struct {
	HeaderOptions   []GetOption
	QueryOptions    []GetOption
	BodyOptions     []GetOption
	FormDataOptions []GetOption
	PathOptions     []GetOption
}

type RequestInputIterators

type RequestInputIterators struct {
	Total       int
	Path        *StringTemplate
	Body        *mapbuilder.MapBuilder
	Query       *QueryTemplate
	PipeOptions *PipelineOptions
}

RequestInputIterators contains all request input iterators

type RequiredKeys

type RequiredKeys []string

type RequiredTemplateString

type RequiredTemplateString string

type Resolver

type Resolver interface {
	Resolve(string) (string, error)
}

type StringTemplate

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

StringTemplate is a template which can input parameters which will be ev

func NewStringTemplate

func NewStringTemplate(template string) *StringTemplate

NewStringTemplate returns a new string template

func (*StringTemplate) CheckRequired

func (b *StringTemplate) CheckRequired() error

CheckRequired check if all required variables are provided

func (*StringTemplate) Execute

func (b *StringTemplate) Execute(ignoreIterators bool, template ...string) (output string, input interface{}, err error)

Execute replaces all of the path parameters in a given URI with the provided values Example:

"alarm/alarms/{id}" => "alarm/alarms/1234" if given a parameter map of {"id": "1234"}

func (*StringTemplate) GetNext

func (b *StringTemplate) GetNext() ([]byte, interface{}, error)

GetNext returns the next template path

func (*StringTemplate) GetTemplate

func (b *StringTemplate) GetTemplate() string

GetTemplate return the string template

func (*StringTemplate) IsBound

func (b *StringTemplate) IsBound() bool

IsBound return true if the iterator is bound

func (*StringTemplate) SetAllowEmptyValues

func (b *StringTemplate) SetAllowEmptyValues(value bool)

func (*StringTemplate) SetTemplate

func (b *StringTemplate) SetTemplate(template string)

SetTemplate updates the string template

func (*StringTemplate) SetVariable

func (b *StringTemplate) SetVariable(name string, value interface{})

SetVariable sets a give path variable which will be evalulated when fetching the next value

type Template

type Template string

type TemplateVariables

type TemplateVariables map[string]interface{}

Jump to

Keyboard shortcuts

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