summaryrefslogtreecommitdiff
path: root/vendor/github.com/pborman/getopt/enum.go
blob: ee4cf95020d1879d1f43e0bece8a73b6c26b3098 (plain)
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
// Copyright 2013 Google Inc.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package getopt

import "errors"

type enumValue string

var enumValues = make(map[*enumValue]map[string]struct{})

func (s *enumValue) Set(value string, opt Option) error {
	es, ok := enumValues[s]
	if !ok || es == nil {
		return errors.New("this option has no values")
	}
	if _, ok := es[value]; !ok {
		return errors.New("invalid value: " + value)
	}
	*s = enumValue(value)
	return nil
}

func (s *enumValue) String() string {
	return string(*s)
}

// Enum creates an option that can only be set to one of the enumerated strings
// passed in values.  Passing nil or an empty slice results in an option that
// will always fail.
func Enum(name rune, values []string, helpvalue ...string) *string {
	return CommandLine.Enum(name, values, helpvalue...)
}

func (s *Set) Enum(name rune, values []string, helpvalue ...string) *string {
	var p string
	s.EnumVarLong(&p, "", name, values, helpvalue...)
	return &p
}

func EnumLong(name string, short rune, values []string, helpvalue ...string) *string {
	return CommandLine.EnumLong(name, short, values, helpvalue...)
}

func (s *Set) EnumLong(name string, short rune, values []string, helpvalue ...string) *string {
	var p string
	s.EnumVarLong(&p, name, short, values, helpvalue...)
	return &p
}

// EnumVar creates an enum option that defaults to the starting value of *p.
// If *p is not found in values then a reset of this option will fail.
func EnumVar(p *string, name rune, values []string, helpvalue ...string) Option {
	return CommandLine.EnumVar(p, name, values, helpvalue...)
}

func (s *Set) EnumVar(p *string, name rune, values []string, helpvalue ...string) Option {
	return s.EnumVarLong(p, "", name, values, helpvalue...)
}

func EnumVarLong(p *string, name string, short rune, values []string, helpvalue ...string) Option {
	return CommandLine.EnumVarLong(p, name, short, values, helpvalue...)
}

func (s *Set) EnumVarLong(p *string, name string, short rune, values []string, helpvalue ...string) Option {
	m := make(map[string]struct{})
	for _, v := range values {
		m[v] = struct{}{}
	}
	enumValues[(*enumValue)(p)] = m
	return s.VarLong((*enumValue)(p), name, short, helpvalue...)
}