File: args.go

package info (click to toggle)
golang-gopkg-alecthomas-kingpin.v3 3.0~git20180227.b8d601d-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 420 kB
  • sloc: makefile: 6
file content (60 lines) | stat: -rw-r--r-- 1,299 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
48
49
50
51
52
53
54
55
56
57
58
59
60
package kingpin

type argGroup struct {
	args []*Clause
}

func newArgGroup() *argGroup {
	return &argGroup{}
}

func (a *argGroup) have() bool {
	return len(a.args) > 0
}

// GetArg gets an argument definition.
//
// This allows existing arguments to be modified after definition but before parsing. Useful for
// modular applications.
func (a *argGroup) GetArg(name string) *Clause {
	for _, arg := range a.args {
		if arg.name == name {
			return arg
		}
	}
	return nil
}

func (a *argGroup) Arg(name, help string) *Clause {
	arg := NewClause(name, help)
	a.args = append(a.args, arg)
	return arg
}

func (a *argGroup) init() error {
	required := 0
	seen := map[string]struct{}{}
	previousArgMustBeLast := false
	for i, arg := range a.args {
		if previousArgMustBeLast {
			return TError("Args() can't be followed by another argument '{{.Arg0}}'", V{"Arg0": arg.name})
		}
		if arg.consumesRemainder() {
			previousArgMustBeLast = true
		}
		if _, ok := seen[arg.name]; ok {
			return TError("duplicate argument '{{.Arg0}}'", V{"Arg0": arg.name})
		}
		seen[arg.name] = struct{}{}
		if arg.required && required != i {
			return TError("required arguments found after non-required")
		}
		if arg.required {
			required++
		}
		if err := arg.init(); err != nil {
			return err
		}
	}
	return nil
}