parameters

package
v0.5.13 Latest Latest
Warning

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

Go to latest
Published: May 1, 2024 License: MIT Imports: 23 Imported by: 66

Documentation

Index

Constants

View Source
const SourceDefaults = "defaults"

Variables

This section is empty.

Functions

func GenerateUseString added in v0.4.9

func GenerateUseString(cmdName string, pds *ParameterDefinitions) string

GenerateUseString creates a string representation of the 'Use' field for a given cobra command and a list of parameter definitions. The first word of the existing 'Use' field is treated as the verb for the command. The resulting string briefly describes how to use the command respecting the following conventions:

  • Required parameters are enclosed in '<>'.
  • Optional parameters are enclosed in '[]'.
  • Optional parameters that accept multiple input (ParameterTypeStringList or ParameterTypeIntegerList) are followed by '...'.
  • If a parameter has a default value, it is specified after parameter name like 'parameter (default: value)'.

For example:

  • If there is a required parameter 'name', and an optional parameter 'age' with a default value of '30', the resulting string will be: 'verb <name> [age (default: 30)]'.
  • If there is a required parameter 'name', and an optional parameter 'colors' of type ParameterTypeStringList, the resulting Use string will be: 'verb <name> [colors...]'

func ParseDate

func ParseDate(value string) (time.Time, error)

ParseDate parses a string into a time.Time based on predefined date formats.

It first tries parsing with dateparse.ParseAny using standard formats. If that fails, it tries naturaldate.Parse which handles relative natural language dates.

If both parsing attempts fail, an error is returned. The reference time passed to naturaldate.Parse defaults to time.Now().

func RenderValue added in v0.2.46

func RenderValue(type_ ParameterType, value interface{}) (string, error)

RenderValue renders the given value to string so that it can be parsed as a cobra command line flag. TODO(manuel, 2023-09-09) Refactor rendering of values to strings that can be parsed. This is only applicable to parsing using cobra, but really we now have many more ways of parsing a flag out of a string, among which GET query and FORM input parameters.

func StructToDataMap added in v0.5.13

func StructToDataMap(s interface{}) (map[string]interface{}, error)

StructToDataMap transforms a struct into a map[string]interface{} based on the `glazed.parameter` annotations.

If a struct field is annotated with `glazed.parameter:"<pattern>*"` (contains a wildcard `*`), the field is expected to be a map. The function will match the map keys against the wildcard pattern and include the matching key-value pairs in the resulting data map.

Returns an error if: - Parsing the `glazed.parameter` tag fails for any field. - A field annotated with a wildcard is not a map.

Types

type ErrInvalidValue added in v0.4.36

type ErrInvalidValue struct {
	Value interface{}
	Name  string
	Type  ParameterType
}

func (ErrInvalidValue) Error added in v0.4.36

func (e ErrInvalidValue) Error() string

type FileData added in v0.4.11

type FileData struct {
	Content          string
	ParsedContent    interface{}
	ParseError       error
	RawContent       []byte
	StringContent    string
	IsList           bool
	IsObject         bool
	BaseName         string
	Extension        string
	FileType         FileType
	Path             string
	RelativePath     string
	AbsolutePath     string
	Size             int64
	LastModifiedTime time.Time
	Permissions      os.FileMode
	IsDirectory      bool
}

func GetFileData added in v0.4.11

func GetFileData(filename string) (*FileData, error)

func (*FileData) PrettyPrint added in v0.4.32

func (fd *FileData) PrettyPrint() string

type FileType added in v0.4.11

type FileType string
const (
	Unknown FileType = "Unknown"
	JSON    FileType = "JSON"
	YAML    FileType = "YAML"
	CSV     FileType = "CSV"
	TEXT    FileType = "TEXT"
)

type ParameterDefinition

type ParameterDefinition struct {
	Name       string        `yaml:"name"`
	ShortFlag  string        `yaml:"shortFlag,omitempty"`
	Type       ParameterType `yaml:"type"`
	Help       string        `yaml:"help,omitempty"`
	Default    *interface{}  `yaml:"default,omitempty"`
	Choices    []string      `yaml:"choices,omitempty"`
	Required   bool          `yaml:"required,omitempty"`
	IsArgument bool          `yaml:"-"`
}

ParameterDefinition is a declarative way of describing a command line parameter. A ParameterDefinition can be either a Flag or an Argument. Along with metadata (Name, Help) that is useful for help, it also specifies a Type, a Default value and if it is Required.

func NewParameterDefinition

func NewParameterDefinition(
	name string,
	parameterType ParameterType,
	options ...ParameterDefinitionOption,
) *ParameterDefinition

func (*ParameterDefinition) CheckParameterDefaultValueValidity

func (p *ParameterDefinition) CheckParameterDefaultValueValidity() error

CheckParameterDefaultValueValidity checks if the ParameterDefinition's Default is valid. This is used when validating loading from a YAML file or setting up cobra flag definitions.

func (*ParameterDefinition) CheckValueValidity added in v0.2.54

func (p *ParameterDefinition) CheckValueValidity(v interface{}) error

CheckValueValidity checks if the given value is valid for the ParameterDefinition.

func (*ParameterDefinition) Clone added in v0.4.36

func (*ParameterDefinition) InitializeValueToEmptyValue added in v0.4.9

func (p *ParameterDefinition) InitializeValueToEmptyValue(value reflect.Value) error

InitializeValueToEmptyValue initializes the given value to the empty value of the type of the parameter.

func (*ParameterDefinition) IsEqualToDefault added in v0.2.55

func (p *ParameterDefinition) IsEqualToDefault(i interface{}) bool

func (*ParameterDefinition) ParseFromReader added in v0.2.16

func (p *ParameterDefinition) ParseFromReader(
	f io.Reader, filename string,
	options ...ParseStepOption,
) (*ParsedParameter, error)

ParseFromReader parses a single element for the type from the reader. In the case of parameters taking multiple files, this needs to be called for each file and merged at the caller level.

func (*ParameterDefinition) ParseParameter

func (p *ParameterDefinition) ParseParameter(v []string, options ...ParseStepOption) (*ParsedParameter, error)

ParseParameter parses command line arguments according to the given ParameterDefinition. It returns the parsed parameter value and a non-nil error if parsing failed.

The function takes a list of strings that can be gathered from the command line arguments. This is because cobra for example allows slice flags to be passed by reusing the same flag multiple times (or by parsing comma-separated values).

If the parameter is required and not provided, an error is returned. If the parameter is optional and not provided, the default value is returned.

## Expected type parsing

The ParameterDefinition specifies the expected type and how to parse the arguments:

  • ParameterTypeString: parsed from a single string value
  • ParameterTypeInteger, ParameterTypeFloat, ParameterTypeBool: parsed from a single value
  • ParameterTypeStringList, ParameterTypeIntegerList, ParameterTypeFloatList: parsed from multiple values
  • ParameterTypeFile: load file contents into a FileData struct
  • ParameterTypeFileList: load multiple files into []*FileData
  • ParameterTypeChoice, ParameterTypeChoiceList: validated against allowed choices
  • ParameterTypeKeyValue: parsed from colon separated strings or files
  • ParameterTypeObjectListFromFile, ParameterTypeObjectListFromFiles: deserialized object lists from JSON/YAML files
  • ParameterTypeObjectFromFile: deserialized a single object from a JSON/YAML file
  • ParameterTypeStringFromFile, ParameterTypeStringFromFiles: load file contents as strings
  • ParameterTypeStringListFromFile, ParameterTypeStringListFromFiles: load file lines as a string list
  • ParameterTypeDate: parsed into time.Time

The parsing logic depends on the Type in the ParameterDefinition.

## ParameterType -> Bype mappings

ParameterTypeString -> string ParameterTypeInteger -> int ParameterTypeFloat -> float64 ParameterTypeBool -> bool ParameterTypeStringList -> []string ParameterTypeIntegerList -> []int ParameterTypeFloatList -> []float64 ParameterTypeChoice -> string ParameterTypeChoiceList -> []string ParameterTypeDate -> time.Time ParameterTypeFile -> *FileData ParameterTypeFileList -> []*FileData ParameterTypeObjectListFromFile -> []interface{} ParameterTypeObjectFromFile -> map[string]interface{} ParameterTypeStringFromFile -> string ParameterTypeStringFromFiles -> string ParameterTypeStringListFromFile -> []string ParameterTypeStringListFromFiles -> []string ParameterTypeKeyValue -> map[string]interface{}

TODO(manuel, 2023-12-22) We should provide the parsing context from higher up here, instead of just calling it strings

func (*ParameterDefinition) SetDefaultFromValue added in v0.2.13

func (p *ParameterDefinition) SetDefaultFromValue(value reflect.Value) error

SetDefaultFromValue sets the Default field of the ParameterDefinition to the provided value. It handles nil values and dereferencing pointers. The value is type checked before being set.

func (*ParameterDefinition) SetValueFromDefault

func (p *ParameterDefinition) SetValueFromDefault(value reflect.Value) error

SetValueFromDefault assigns the default value of the ParameterDefinition to the given value. If the Default value is nil, the value is set to the zero value of the type.

func (*ParameterDefinition) SetValueFromInterface added in v0.4.9

func (p *ParameterDefinition) SetValueFromInterface(value reflect.Value, v interface{}) error

SetValueFromInterface assigns the value v to the given reflect.Value based on the ParameterDefinition's type. It handles type checking and conversion for the various supported parameter types.

func (*ParameterDefinition) String

func (p *ParameterDefinition) String() string

type ParameterDefinitionOption

type ParameterDefinitionOption func(*ParameterDefinition)

func WithChoices

func WithChoices(choices ...string) ParameterDefinitionOption

func WithDefault

func WithDefault(defaultValue interface{}) ParameterDefinitionOption

func WithHelp

func WithHelp(help string) ParameterDefinitionOption

func WithIsArgument added in v0.4.36

func WithIsArgument(isArgument bool) ParameterDefinitionOption

func WithRequired

func WithRequired(required bool) ParameterDefinitionOption

func WithShortFlag

func WithShortFlag(shortFlag string) ParameterDefinitionOption

type ParameterDefinitions added in v0.4.36

type ParameterDefinitions struct {
	*orderedmap.OrderedMap[string, *ParameterDefinition]
}

ParameterDefinitions is an ordered map of ParameterDefinition.

func LoadParameterDefinitionsFromYAML added in v0.2.84

func LoadParameterDefinitionsFromYAML(yamlContent []byte) *ParameterDefinitions

LoadParameterDefinitionsFromYAML loads a map of ParameterDefinitions from a YAML file. It checks that default values are valid. It returns the ParameterDefinitions as a map indexed by name, and as a list.

func NewParameterDefinitions added in v0.4.36

func NewParameterDefinitions(options ...ParameterDefinitionsOption) *ParameterDefinitions

func (*ParameterDefinitions) AddParametersToCobraCommand added in v0.4.36

func (pds *ParameterDefinitions) AddParametersToCobraCommand(
	cmd *cobra.Command,
	prefix string,
) error

AddParametersToCobraCommand takes the parameters from a CommandDescription and converts them to cobra flags, before adding them to the Parameters() of a the passed cobra command.

func (*ParameterDefinitions) Clone added in v0.4.36

Clone returns a cloned copy of the ParameterDefinitions. The parameter definitions are cloned as well.

func (*ParameterDefinitions) ForEach added in v0.4.36

func (pds *ParameterDefinitions) ForEach(f func(definition *ParameterDefinition))

ForEach calls the given function f on each parameter definition in p.

func (*ParameterDefinitions) ForEachE added in v0.4.36

func (pds *ParameterDefinitions) ForEachE(f func(definition *ParameterDefinition) error) error

ForEachE calls the given function f on each parameter definition in p. If f returns an error, ForEachE stops iterating and returns the error immediately.

func (*ParameterDefinitions) GatherArguments added in v0.4.36

func (pds *ParameterDefinitions) GatherArguments(
	args []string,
	onlyProvided bool,
	ignoreRequired bool,
	parseOptions ...ParseStepOption,
) (*ParsedParameters, error)

GatherArguments parses positional string arguments into a map of values.

It takes the command-line arguments, the expected argument definitions, and a boolean indicating whether to only include explicitly provided arguments, not the default values of missing arguments.

Only the last parameter definitions can be a list parameter type.

Required arguments missing from the input will result in an error. Arguments with default values can be included based on the onlyProvided flag.

The result is a map with argument names as keys and parsed values. Argument order is maintained.

Any extra arguments not defined will result in an error. Parsing errors for individual arguments will also return errors.

func (*ParameterDefinitions) GatherFlagsFromCobraCommand added in v0.4.36

func (pds *ParameterDefinitions) GatherFlagsFromCobraCommand(
	cmd *cobra.Command,
	onlyProvided bool,
	ignoreRequired bool,
	prefix string,
	options ...ParseStepOption,
) (*ParsedParameters, error)

GatherFlagsFromCobraCommand gathers the flags from the cobra command, and parses them according to the parameter description passed in params. The result is a map of parameter names to parsed values.

If onlyProvided is true, only parameters that are provided by the user are returned (i.e. not the default values).

If a parameter cannot be parsed correctly, or is missing even though it is not optional, an error is returned.

The required argument checks that all the required parameter definitions are present. The provided argument only checks that the provided flags are passed. Prefix is prepended to all flag names.

func (*ParameterDefinitions) GatherFlagsFromStringList added in v0.4.36

func (pds *ParameterDefinitions) GatherFlagsFromStringList(
	args []string,
	onlyProvided bool,
	ignoreRequired bool,
	prefix string,
	parseOptions ...ParseStepOption,
) (*ParsedParameters, []string, error)

GatherFlagsFromStringList parses command line arguments into a ParsedParameters map. It accepts a slice of string arguments, bools to control required/provided flag handling, and a prefix to prepend to flag names.

It returns the parsed parameters map, any non-flag arguments, and any error encountered during parsing.

onlyProvided controls whether to only include flags that were explicitly provided on the command line. If false, default values will be included for any flags that were not provided.

ignoreRequired controls whether required flags are enforced. If true, missing required flags will not trigger an error.

prefix allows prepending a string to flag names to namespace them. For example, a prefix of "user" would namespace flags like "--name" to "--user-name". This allows reuse of a flag set across different sub-commands. The prefix has "-" appended automatically.

func (*ParameterDefinitions) GatherFlagsFromViper added in v0.4.36

func (pds *ParameterDefinitions) GatherFlagsFromViper(
	onlyProvided bool,
	prefix string,
	options ...ParseStepOption,
) (*ParsedParameters, error)

func (*ParameterDefinitions) GatherParametersFromMap added in v0.4.36

func (pds *ParameterDefinitions) GatherParametersFromMap(
	m map[string]interface{},
	onlyProvided bool,
	options ...ParseStepOption,
) (*ParsedParameters, error)

GatherParametersFromMap gathers parameter values from a map.

For each ParameterDefinition, it checks if a matching value is present in the map:

- If the parameter is missing and required, an error is returned. - If the parameter is missing and optional, the default value is used. - If the value is provided, it is validated against the definition.

Values are looked up by parameter name, as well as short flag if provided.

The returned map contains the gathered parameter values, with defaults filled in for any missing optional parameters.

func (*ParameterDefinitions) GetArguments added in v0.4.36

func (pds *ParameterDefinitions) GetArguments() *ParameterDefinitions

GetArguments returns a new ParameterDefinitions containing only the argument parameters. The parameter definitions are not cloned.

func (*ParameterDefinitions) GetDefaultValue added in v0.4.36

func (pds *ParameterDefinitions) GetDefaultValue(key string, defaultValue interface{}) interface{}

func (*ParameterDefinitions) GetFlags added in v0.4.36

func (pds *ParameterDefinitions) GetFlags() *ParameterDefinitions

GetFlags returns a new ParameterDefinitions containing only the flag parameters. The parameter definitions are not cloned.

func (*ParameterDefinitions) InitializeDefaultsFromMap added in v0.4.36

func (pds *ParameterDefinitions) InitializeDefaultsFromMap(
	ps map[string]interface{},
) error

func (*ParameterDefinitions) InitializeDefaultsFromStruct added in v0.4.36

func (pds *ParameterDefinitions) InitializeDefaultsFromStruct(
	s interface{},
) error

InitializeDefaultsFromStruct initializes the parameters definitions from a struct. Each field in the struct annotated with tag `glazed.parameter` will be used to set the default value of the corresponding definition in `parameterDefinitions`. If no `ParameterDefinition` is found for a field, an error is returned. This is the inverse of InitializeStructFromDefaults.

func (*ParameterDefinitions) InitializeStructFromDefaults added in v0.4.36

func (pds *ParameterDefinitions) InitializeStructFromDefaults(s interface{}) error

InitializeStructFromDefaults initializes a struct from a map of parameter definitions.

Each field in the struct annotated with tag `glazed.parameter` will be set to the default value of the corresponding `ParameterDefinition`. If no `ParameterDefinition` is found for a field, an error is returned.

func (*ParameterDefinitions) MarshalYAML added in v0.4.36

func (pds *ParameterDefinitions) MarshalYAML() (interface{}, error)

func (*ParameterDefinitions) Merge added in v0.4.36

Merge merges the parameter definitions from m into p. It clones each parameter definition before adding it to p so that updates to p do not affect m.

func (*ParameterDefinitions) ParsedParametersFromDefaults added in v0.5.9

func (pds *ParameterDefinitions) ParsedParametersFromDefaults() *ParsedParameters

ParsedParametersFromDefaults uses the parameter definitions default values to create a ParsedParameters object.

func (*ParameterDefinitions) ToList added in v0.5.9

func (pds *ParameterDefinitions) ToList() []*ParameterDefinition

func (*ParameterDefinitions) UnmarshalYAML added in v0.4.36

func (pds *ParameterDefinitions) UnmarshalYAML(value *yaml.Node) error

type ParameterDefinitionsOption added in v0.4.36

type ParameterDefinitionsOption func(*ParameterDefinitions)

func WithParameterDefinitionList added in v0.4.36

func WithParameterDefinitionList(parameterDefinitions []*ParameterDefinition) ParameterDefinitionsOption

func WithParameterDefinitions added in v0.4.36

func WithParameterDefinitions(parameterDefinitions *ParameterDefinitions) ParameterDefinitionsOption

type ParameterType

type ParameterType string
const (
	ParameterTypeString ParameterType = "string"

	ParameterTypeStringFromFile  ParameterType = "stringFromFile"
	ParameterTypeStringFromFiles ParameterType = "stringFromFiles"

	// ParameterTypeFile and ParameterTypeFileList are a more elaborate version that loads and parses
	// the file content and returns a list of FileData objects (or a single object in the case
	// of ParameterTypeFile).
	ParameterTypeFile     ParameterType = "file"
	ParameterTypeFileList ParameterType = "fileList"

	ParameterTypeObjectListFromFile  ParameterType = "objectListFromFile"
	ParameterTypeObjectListFromFiles ParameterType = "objectListFromFiles"
	ParameterTypeObjectFromFile      ParameterType = "objectFromFile"
	ParameterTypeStringListFromFile  ParameterType = "stringListFromFile"
	ParameterTypeStringListFromFiles ParameterType = "stringListFromFiles"

	// ParameterTypeKeyValue signals either a string with comma separate key-value options,
	// or when beginning with @, a file with key-value options
	ParameterTypeKeyValue ParameterType = "keyValue"

	ParameterTypeInteger     ParameterType = "int"
	ParameterTypeFloat       ParameterType = "float"
	ParameterTypeBool        ParameterType = "bool"
	ParameterTypeDate        ParameterType = "date"
	ParameterTypeStringList  ParameterType = "stringList"
	ParameterTypeIntegerList ParameterType = "intList"
	ParameterTypeFloatList   ParameterType = "floatList"
	ParameterTypeChoice      ParameterType = "choice"
	ParameterTypeChoiceList  ParameterType = "choiceList"
)

func (ParameterType) IsFile added in v0.4.36

func (p ParameterType) IsFile() bool

func (ParameterType) IsKeyValue added in v0.4.36

func (p ParameterType) IsKeyValue() bool

func (ParameterType) IsList added in v0.4.36

func (p ParameterType) IsList() bool

IsList returns true if the parameter has to be parsed from a list of strings, not if its value is actually a list.

func (ParameterType) IsObject added in v0.4.36

func (p ParameterType) IsObject() bool

func (ParameterType) IsObjectList added in v0.4.36

func (c ParameterType) IsObjectList() bool

func (ParameterType) NeedsFileContent added in v0.4.36

func (p ParameterType) NeedsFileContent(value string) bool

NeedsFileContent returns true if the parameter type is one that loads one or more files, when provided with the given value. This slightly odd API is because some types like ParameterTypeKeyValue can be either a string or a file. A beginning character of @ indicates a file.

func (ParameterType) NeedsMultipleFileContent added in v0.4.36

func (p ParameterType) NeedsMultipleFileContent() bool

NeedsMultipleFileContent returns true if the parameter type is one that loads multiple files.

type ParseStep added in v0.4.36

type ParseStep struct {
	Source   string
	Value    interface{}
	Metadata map[string]interface{}
}

func NewParseStep added in v0.4.36

func NewParseStep(options ...ParseStepOption) ParseStep

type ParseStepOption added in v0.4.36

type ParseStepOption func(*ParseStep)

func WithParseStepMetadata added in v0.4.36

func WithParseStepMetadata(metadata map[string]interface{}) ParseStepOption

func WithParseStepSource added in v0.4.36

func WithParseStepSource(source string) ParseStepOption

func WithParseStepValue added in v0.4.36

func WithParseStepValue(value interface{}) ParseStepOption

type ParsedParameter added in v0.4.36

type ParsedParameter struct {
	Value               interface{}
	ParameterDefinition *ParameterDefinition
	// Log contains a history of the parsing steps that were taken to arrive at the value.
	// Last step is the final value.
	Log []ParseStep
}

func (*ParsedParameter) Clone added in v0.4.36

func (p *ParsedParameter) Clone() *ParsedParameter

func (*ParsedParameter) GetInterfaceValue added in v0.4.36

func (p *ParsedParameter) GetInterfaceValue() (interface{}, error)

GetInterfaceValue returns the value as an interface{}. If the type of the parameter is a list, it will return a []interface{}. If the type is an object, it will return a map[string]interface{}. If the type is a list of objects, it will return a []interface{} of map[string]interface{}.

func (*ParsedParameter) Merge added in v0.4.36

func (p *ParsedParameter) Merge(v *ParsedParameter, options ...ParseStepOption)

func (*ParsedParameter) RenderValue added in v0.5.9

func (p *ParsedParameter) RenderValue() (string, error)

func (*ParsedParameter) Set added in v0.4.36

func (p *ParsedParameter) Set(value interface{}, log ...ParseStep)

Set sets the value of the parsedParameter, and manually updates the log

func (*ParsedParameter) Update added in v0.4.36

func (p *ParsedParameter) Update(value interface{}, options ...ParseStepOption)

Update sets the value of the parsedParameter, and appends a new parseStep.

func (*ParsedParameter) UpdateWithLog added in v0.4.36

func (p *ParsedParameter) UpdateWithLog(value interface{}, log ...ParseStep)

UpdateWithLog sets the value of the parsedParameter, and appends the given log.

type ParsedParameters added in v0.4.36

type ParsedParameters struct {
	*orderedmap.OrderedMap[string, *ParsedParameter]
}

func NewParsedParameters added in v0.4.36

func NewParsedParameters(options ...ParsedParametersOption) *ParsedParameters

func (*ParsedParameters) Clone added in v0.4.36

func (p *ParsedParameters) Clone() *ParsedParameters

func (*ParsedParameters) ForEach added in v0.4.36

func (p *ParsedParameters) ForEach(f func(key string, value *ParsedParameter))

ForEach applies the passed function to each key-value pair from oldest to newest in ParsedParameters.

func (*ParsedParameters) ForEachE added in v0.4.36

func (p *ParsedParameters) ForEachE(f func(key string, value *ParsedParameter) error) error

ForEachE applies the passed function (that returns an error) to each pair in ParsedParameters. It stops at, and returns, the first error encountered.

func (*ParsedParameters) GetValue added in v0.4.36

func (p *ParsedParameters) GetValue(key string) interface{}

func (*ParsedParameters) InitializeStruct added in v0.4.36

func (p *ParsedParameters) InitializeStruct(s interface{}) error

InitializeStruct initializes a struct from a ParsedParameters map.

It iterates through the struct fields looking for those tagged with "glazed.parameter". For each tagged field, it will lookup the corresponding parameter value in the ParsedParameters map and set the field's value.

If the tag open `from_json` is appended to `glazed.parameter` and the parameter value is a string, bytes, rawMessage or FileData, the value is parsed from json.

If the tag contains a wildcard, the function will match parameter names against the wildcard pattern and store the matches in a map in the destination field. The map can be of any type, as long as it is a map of strings. The same logic as for normal fields will be applied to the map entries.

Struct fields that are pointers to other structs are handled recursively.

Struct fields that are pointers will be dereferenced. If the pointer is nil, a new value will be allocated and set.

s should be a pointer to the struct to initialize.

ps is the ParsedParameters map to lookup parameter values from.

Example struct:

type CreateIndexSettings struct {
	Index               string               `glazed.parameter:"index"`
	Settings            *IndexSettings       `glazed.parameter:"settings,from_json"`
	Mappings            *parameters.FileData `glazed.parameter:"mappings"`
	Aliases             *map[string]Alias    `glazed.parameter:"aliases,from_json"`
	WaitForActiveShards string               `glazed.parameter:"wait_for_active_shards"`
	ApiKeys             map[string]string    `glazed.parameter:"*_api_key"`
}

Corresponding ParameterDefinitions:

parameters.NewParameterDefinition(
	"index",
	parameters.ParameterTypeString,
	parameters.WithHelp("Name of the index to create"),
	parameters.WithRequired(true),
),
parameters.NewParameterDefinition(
	"settings",
	parameters.ParameterTypeFile,
	parameters.WithHelp("JSON file containing index settings"),
),
parameters.NewParameterDefinition(
	"mappings",
	parameters.ParameterTypeFile,
	parameters.WithHelp("JSON file containing index mappings"),
),
parameters.NewParameterDefinition(
	"aliases",
	parameters.ParameterTypeFile,
	parameters.WithHelp("JSON file containing index aliases"),
),
parameters.NewParameterDefinition(
	"wait_for_active_shards",
	parameters.ParameterTypeString,
	parameters.WithHelp("Set the number of active shards to wait for before the operation returns."),
),
parameters.NewParameterDefinition(
	"openai_api_key",
	parameters.ParameterTypeString,
	parameters.WithHelp("OpenAI API key"),
),
parameters.NewParameterDefinition(
	"google_api_key",
	parameters.ParameterTypeString,
	parameters.WithHelp("Google API key"),
),

Returns an error if: - s is not a pointer to a struct - A tagged field does not have a matching parameter value in ps - Failed to set the value of a field

func (*ParsedParameters) Merge added in v0.4.36

Merge is actually more complex than it seems, other takes precedence. If the key already exists in the map, we actually merge the ParsedParameter themselves, by appending the entire history of the other parameter to the current one.

func (*ParsedParameters) MergeAsDefault added in v0.4.36

func (p *ParsedParameters) MergeAsDefault(other *ParsedParameters, options ...ParseStepOption) *ParsedParameters

MergeAsDefault only sets the value if the key does not already exist in the map.

func (*ParsedParameters) MustUpdateValue added in v0.5.9

func (p *ParsedParameters) MustUpdateValue(
	key string,
	v interface{},
	options ...ParseStepOption,
) error

func (*ParsedParameters) SetAsDefault added in v0.4.36

func (p *ParsedParameters) SetAsDefault(
	key string, pd *ParameterDefinition, v interface{},
	options ...ParseStepOption)

SetAsDefault sets the current value of the parameter if no value has yet been set.

func (*ParsedParameters) ToInterfaceMap added in v0.4.36

func (p *ParsedParameters) ToInterfaceMap() (map[string]interface{}, error)

ToInterfaceMap converts ParsedParameters to map[string]interface{} by converting each ParsedParameter's value to interface{}. It returns an error if it fails to convert any ParsedParameter's value.

func (*ParsedParameters) ToMap added in v0.4.36

func (p *ParsedParameters) ToMap() map[string]interface{}

ToMap converts ParsedParameters to map[string]interface{} by assigning each ParsedParameter's value to its key.

func (*ParsedParameters) Update added in v0.4.36

func (p *ParsedParameters) Update(
	key string, pp *ParsedParameter,
)

func (*ParsedParameters) UpdateExistingValue added in v0.4.36

func (p *ParsedParameters) UpdateExistingValue(
	key string, v interface{},
	options ...ParseStepOption,
) bool

UpdateExistingValue updates the value of an existing parameter, and returns true if the parameter existed. If the parameter did not exist, it returns false.

func (*ParsedParameters) UpdateValue added in v0.4.36

func (p *ParsedParameters) UpdateValue(
	key string, pd *ParameterDefinition,
	v interface{},
	options ...ParseStepOption,
)

func (*ParsedParameters) UpdateWithLog added in v0.4.36

func (p *ParsedParameters) UpdateWithLog(
	key string, pd *ParameterDefinition,
	v interface{},
	log ...ParseStep,
)

type ParsedParametersOption added in v0.4.36

type ParsedParametersOption func(*ParsedParameters)

func WithParsedParameter added in v0.4.36

func WithParsedParameter(pd *ParameterDefinition, key string, value interface{}) ParsedParametersOption

Jump to

Keyboard shortcuts

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