mcp-framework/cli/resolve_lookup.go

88 lines
1.8 KiB
Go
Raw Permalink Normal View History

package cli
import (
"errors"
"os"
2026-05-05 10:23:14 +00:00
"forge.lclr.dev/AI/mcp-framework/secretstore"
)
type KeyLookupFunc func(key string) (string, bool, error)
type ResolveLookupOptions struct {
Flag KeyLookupFunc
Env KeyLookupFunc
Config KeyLookupFunc
Secret KeyLookupFunc
}
func ResolveLookup(options ResolveLookupOptions) LookupFunc {
return func(source ValueSource, key string) (string, bool, error) {
switch source {
case SourceFlag:
return runKeyLookup(options.Flag, key)
case SourceEnv:
return runKeyLookup(options.Env, key)
case SourceConfig:
return runKeyLookup(options.Config, key)
case SourceSecret:
return runKeyLookup(options.Secret, key)
case SourceDefault:
return "", false, nil
default:
return "", false, nil
}
}
}
func runKeyLookup(lookup KeyLookupFunc, key string) (string, bool, error) {
if lookup == nil {
return "", false, nil
}
if key == "" {
return "", false, nil
}
return lookup(key)
}
func MapLookup(values map[string]string) KeyLookupFunc {
return func(key string) (string, bool, error) {
value, ok := values[key]
return value, ok, nil
}
}
func EnvLookup(lookup func(string) (string, bool)) KeyLookupFunc {
reader := lookup
if reader == nil {
reader = os.LookupEnv
}
return func(key string) (string, bool, error) {
value, ok := reader(key)
return value, ok, nil
}
}
func ConfigMap(values map[string]string) KeyLookupFunc {
return MapLookup(values)
}
func SecretStore(store secretstore.Store) KeyLookupFunc {
if store == nil {
return nil
}
return func(key string) (string, bool, error) {
value, err := store.GetSecret(key)
switch {
case err == nil:
return value, true, nil
case errors.Is(err, secretstore.ErrNotFound):
return "", false, nil
default:
return "", false, err
}
}
}