summaryrefslogtreecommitdiff
path: root/parsefuncs.go
blob: 793e7328a13d268fe74cd8629f51781c938a3d15 (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
// SPDX-FileCopyrightText: 2020 Ethel Morgan
//
// SPDX-License-Identifier: MIT

package flag

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
)

var (
	// ErrRequired provides a canonical "you must set this flag" error message.
	ErrRequired = errors.New("must not be empty")
)

func RequiredString(raw string) (interface{}, error) {
	if raw == "" {
		return nil, ErrRequired
	}
	return raw, nil
}

func StringEnum(values ...string) ParseFunc {
	return func(raw string) (interface{}, error) {
		for _, value := range values {
			if value == raw {
				return raw, nil
			}
		}
		return raw, fmt.Errorf("must be one of %q", values)
	}
}

func IntList(raw string) (interface{}, error) {
	var ints []int

	if raw == "" {
		return ints, nil
	}

	for _, raw := range strings.Split(raw, ",") {
		i, err := strconv.Atoi(raw)
		if err != nil {
			return ints, err
		}
		ints = append(ints, i)
	}

	return ints, nil
}