File: options.go

package info (click to toggle)
elvish 0.21.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,372 kB
  • sloc: javascript: 236; sh: 130; python: 104; makefile: 88; xml: 9
file content (47 lines) | stat: -rw-r--r-- 1,297 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package eval

import (
	"reflect"

	"src.elv.sh/pkg/eval/vals"
	"src.elv.sh/pkg/parse"
)

// UnknownOption is thrown by a native function when called with an unknown option.
type UnknownOption struct {
	OptName string
}

// Error implements the error interface.
func (e UnknownOption) Error() string {
	return "unknown option: " + parse.Quote(e.OptName)
}

// RawOptions is the type of an argument a Go-native function can take to
// declare that it wants to parse options itself. See the doc of NewGoFn for
// details.
type RawOptions map[string]any

// Takes a raw option map and a pointer to a struct, and populate the struct
// with options. A field named FieldName corresponds to the option named
// field-name. Options that don't have corresponding fields in the struct causes
// an error.
//
// Similar to vals.ScanMapToGo, but requires rawOpts to contain a subset of keys
// supported by the struct.
func scanOptions(rawOpts RawOptions, ptr any) error {
	_, keyIdx := vals.StructFieldsInfo(reflect.TypeOf(ptr).Elem())
	structValue := reflect.ValueOf(ptr).Elem()
	for k, v := range rawOpts {
		fieldIdx, ok := keyIdx[k]
		if !ok {
			return UnknownOption{k}
		}

		err := vals.ScanToGo(v, structValue.Field(fieldIdx).Addr().Interface())
		if err != nil {
			return err
		}
	}
	return nil
}