aboutsummaryrefslogtreecommitdiff
path: root/opts.go
blob: c7ab697daa1be4ddc7fe901e748a109402a684dd (plain) (blame)
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
package opts

type ArgMode int

const (
	None ArgMode = iota
	Required
	Optional
)

type Flag struct {
	Key   rune
	Value string
}

type LongOpt struct {
	Short rune
	Long  string
	Arg   ArgMode
}

func Get(args []string, optstr string) (flags []Flag, optind int, err error) {
	argmap := make(map[rune]bool)

	rs := []rune(optstr)
	for i, r := range rs {
		if r != ':' {
			argmap[r] = false
		} else if i > 0 {
			argmap[rs[i-1]] = true
		}
	}

	for i := 1; i < len(args); i++ {
		arg := args[i]
		if len(arg) == 0 || arg == "-" || arg[0] != '-' {
			optind = i
			return
		} else if arg == "--" {
			optind = i + 1
			return
		}

		rs := []rune(arg[1:])
	outer:
		for j, r := range rs {
			argp, ok := argmap[r]
			if !ok {
				return nil, 0, ErrBadOption(r)
			}

			switch {
			case argp && j < len(rs)-1:
				s := string(rs[j+1:])
				flags = append(flags, Flag{r, s})
				break outer
			case argp:
				i++
				if i >= len(args) {
					return nil, 0, ErrNoArgument(r)
				}
				flags = append(flags, Flag{r, args[i]})
				break outer
			}
			flags = append(flags, Flag{Key: r})
		}
	}

	optind = len(args)
	return
}