-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpointer.go
More file actions
78 lines (62 loc) · 1.19 KB
/
pointer.go
File metadata and controls
78 lines (62 loc) · 1.19 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package rig
import (
"errors"
"flag"
"fmt"
"reflect"
)
type pointerFlag struct {
Value PointerValue
Var reflect.Value
}
func (p pointerFlag) String() string {
if p.Value.IsNil() {
return "<nil>"
}
return p.Value.String()
}
func (p *pointerFlag) Set(s string) error {
if !p.Value.IsNil() {
return p.Value.Set(s)
}
t := p.Var.Type().Elem().Elem()
v := reflect.New(t)
p.Var.Elem().Set(v)
p.Value = noopInstanciator{
Value: p.Value.New(v.Interface()),
}
return p.Set(s)
}
type noopInstanciator struct {
flag.Value
}
func (noopInstanciator) New(interface{}) flag.Value {
panic(errors.New("not implemented"))
}
func (noopInstanciator) IsNil() bool {
return false
}
type PointerValue interface {
flag.Value
New(interface{}) flag.Value
IsNil() bool
}
func Pointer(f *Flag, v interface{}) *Flag {
iv, ok := f.Value.(PointerValue)
if !ok {
panic(fmt.Errorf("%T does not implement the rig.PointerValue interface", f.Value))
}
return &Flag{
Value: &pointerFlag{
Value: iv,
Var: reflect.ValueOf(v),
},
Name: f.Name,
Env: f.Env,
Usage: f.Usage,
TypeHint: f.TypeHint,
Required: f.Required,
set: f.set,
defaultValue: f.defaultValue,
}
}