1// Copyright 2009 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package pflag
6
7import (
8	goflag "flag"
9	"fmt"
10	"reflect"
11	"strings"
12)
13
14var _ = fmt.Print
15
16// flagValueWrapper implements pflag.Value around a flag.Value.  The main
17// difference here is the addition of the Type method that returns a string
18// name of the type.  As this is generally unknown, we approximate that with
19// reflection.
20type flagValueWrapper struct {
21	inner    goflag.Value
22	flagType string
23}
24
25// We are just copying the boolFlag interface out of goflag as that is what
26// they use to decide if a flag should get "true" when no arg is given.
27type goBoolFlag interface {
28	goflag.Value
29	IsBoolFlag() bool
30}
31
32func wrapFlagValue(v goflag.Value) Value {
33	// If the flag.Value happens to also be a pflag.Value, just use it directly.
34	if pv, ok := v.(Value); ok {
35		return pv
36	}
37
38	pv := &flagValueWrapper{
39		inner: v,
40	}
41
42	t := reflect.TypeOf(v)
43	if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr {
44		t = t.Elem()
45	}
46
47	pv.flagType = strings.TrimSuffix(t.Name(), "Value")
48	return pv
49}
50
51func (v *flagValueWrapper) String() string {
52	return v.inner.String()
53}
54
55func (v *flagValueWrapper) Set(s string) error {
56	return v.inner.Set(s)
57}
58
59func (v *flagValueWrapper) Type() string {
60	return v.flagType
61}
62
63// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag
64// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei
65// with both `-v` and `--v` in flags. If the golang flag was more than a single
66// character (ex: `verbose`) it will only be accessible via `--verbose`
67func PFlagFromGoFlag(goflag *goflag.Flag) *Flag {
68	// Remember the default value as a string; it won't change.
69	flag := &Flag{
70		Name:  goflag.Name,
71		Usage: goflag.Usage,
72		Value: wrapFlagValue(goflag.Value),
73		// Looks like golang flags don't set DefValue correctly  :-(
74		//DefValue: goflag.DefValue,
75		DefValue: goflag.Value.String(),
76	}
77	// Ex: if the golang flag was -v, allow both -v and --v to work
78	if len(flag.Name) == 1 {
79		flag.Shorthand = flag.Name
80	}
81	if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() {
82		flag.NoOptDefVal = "true"
83	}
84	return flag
85}
86
87// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet
88func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) {
89	if f.Lookup(goflag.Name) != nil {
90		return
91	}
92	newflag := PFlagFromGoFlag(goflag)
93	f.AddFlag(newflag)
94}
95
96// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet
97func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
98	if newSet == nil {
99		return
100	}
101	newSet.VisitAll(func(goflag *goflag.Flag) {
102		f.AddGoFlag(goflag)
103	})
104}
105