mirror of
https://github.com/davidallendj/configurator.git
synced 2025-12-20 03:27:02 -07:00
Moved internal/ to pkg/ to make building external plugins possible
This commit is contained in:
parent
075b1a1f7f
commit
7361ec739f
19 changed files with 4 additions and 3 deletions
57
pkg/util/params.go
Normal file
57
pkg/util/params.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package util
|
||||
|
||||
import (
|
||||
"slices"
|
||||
|
||||
"golang.org/x/exp/maps"
|
||||
)
|
||||
|
||||
// Params are accessible in generator.Generate().
|
||||
type Params map[string]any
|
||||
type Option func(Params)
|
||||
|
||||
// Extract all parameters from the options passed as map[string]any.
|
||||
func GetParams(opts ...Option) Params {
|
||||
params := Params{}
|
||||
for _, opt := range opts {
|
||||
opt(params)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
// Test if an option is present in params
|
||||
func (p *Params) OptionExists(params Params, opt string) bool {
|
||||
var k []string = maps.Keys(params)
|
||||
return slices.Contains(k, opt)
|
||||
}
|
||||
|
||||
// Assert that the options exists within the params map
|
||||
func AssertOptionsExist(params Params, opts ...string) []string {
|
||||
foundKeys := []string{}
|
||||
for k := range params {
|
||||
index := slices.IndexFunc(opts, func(s string) bool {
|
||||
return s == k
|
||||
})
|
||||
if index >= 0 {
|
||||
foundKeys = append(foundKeys, k)
|
||||
}
|
||||
}
|
||||
return foundKeys
|
||||
}
|
||||
|
||||
func WithDefault[T any](v T) Option {
|
||||
return func(p Params) {
|
||||
p["default"] = v
|
||||
}
|
||||
}
|
||||
|
||||
// Syntactic sugar generic function to get parameter from util.Params.
|
||||
func Get[T any](params Params, key string, opts ...Option) *T {
|
||||
if v, ok := params[key].(T); ok {
|
||||
return &v
|
||||
}
|
||||
if defaultValue, ok := params["default"].(T); ok {
|
||||
return &defaultValue
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue