1package pflag
2
3import (
4	"fmt"
5	"strconv"
6)
7
8// -- count Value
9type countValue int
10
11func newCountValue(val int, p *int) *countValue {
12	*p = val
13	return (*countValue)(p)
14}
15
16func (i *countValue) Set(s string) error {
17	v, err := strconv.ParseInt(s, 0, 64)
18	// -1 means that no specific value was passed, so increment
19	if v == -1 {
20		*i = countValue(*i + 1)
21	} else {
22		*i = countValue(v)
23	}
24	return err
25}
26
27func (i *countValue) Type() string {
28	return "count"
29}
30
31func (i *countValue) String() string { return fmt.Sprintf("%v", *i) }
32
33func countConv(sval string) (interface{}, error) {
34	i, err := strconv.Atoi(sval)
35	if err != nil {
36		return nil, err
37	}
38	return i, nil
39}
40
41// GetCount return the int value of a flag with the given name
42func (f *FlagSet) GetCount(name string) (int, error) {
43	val, err := f.getFlagType(name, "count", countConv)
44	if err != nil {
45		return 0, err
46	}
47	return val.(int), nil
48}
49
50// CountVar defines a count flag with specified name, default value, and usage string.
51// The argument p points to an int variable in which to store the value of the flag.
52// A count flag will add 1 to its value evey time it is found on the command line
53func (f *FlagSet) CountVar(p *int, name string, usage string) {
54	f.CountVarP(p, name, "", usage)
55}
56
57// CountVarP is like CountVar only take a shorthand for the flag name.
58func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
59	flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
60	flag.NoOptDefVal = "-1"
61}
62
63// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set
64func CountVar(p *int, name string, usage string) {
65	CommandLine.CountVar(p, name, usage)
66}
67
68// CountVarP is like CountVar only take a shorthand for the flag name.
69func CountVarP(p *int, name, shorthand string, usage string) {
70	CommandLine.CountVarP(p, name, shorthand, usage)
71}
72
73// Count defines a count flag with specified name, default value, and usage string.
74// The return value is the address of an int variable that stores the value of the flag.
75// A count flag will add 1 to its value evey time it is found on the command line
76func (f *FlagSet) Count(name string, usage string) *int {
77	p := new(int)
78	f.CountVarP(p, name, "", usage)
79	return p
80}
81
82// CountP is like Count only takes a shorthand for the flag name.
83func (f *FlagSet) CountP(name, shorthand string, usage string) *int {
84	p := new(int)
85	f.CountVarP(p, name, shorthand, usage)
86	return p
87}
88
89// Count like Count only the flag is placed on the CommandLine isntead of a given flag set
90func Count(name string, usage string) *int {
91	return CommandLine.CountP(name, "", usage)
92}
93
94// CountP is like Count only takes a shorthand for the flag name.
95func CountP(name, shorthand string, usage string) *int {
96	return CommandLine.CountP(name, shorthand, usage)
97}
98