File: multitag.go

package info (click to toggle)
golang-github-svent-go-flags 1-2
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 224 kB
  • sloc: sh: 13; makefile: 7
file content (96 lines) | stat: -rw-r--r-- 1,272 bytes parent folder | download | duplicates (2)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package flags

import (
	"strconv"
)

type multiTag struct {
	value string
	cache map[string][]string
}

func newMultiTag(v string) multiTag {
	return multiTag{
		value: v,
	}
}

func (x *multiTag) scan() map[string][]string {
	v := x.value

	ret := make(map[string][]string)

	// This is mostly copied from reflect.StructTAg.Get
	for v != "" {
		i := 0

		// Skip whitespace
		for i < len(v) && v[i] == ' ' {
			i++
		}

		v = v[i:]

		if v == "" {
			break
		}

		// Scan to colon to find key
		i = 0

		for i < len(v) && v[i] != ' ' && v[i] != ':' && v[i] != '"' {
			i++
		}

		if i+1 >= len(v) || v[i] != ':' || v[i+1] != '"' {
			break
		}

		name := v[:i]
		v = v[i+1:]

		// Scan quoted string to find value
		i = 1

		for i < len(v) && v[i] != '"' {
			if v[i] == '\\' {
				i++
			}
			i++
		}

		if i >= len(v) {
			break
		}

		val, _ := strconv.Unquote(v[:i+1])
		v = v[i+1:]

		ret[name] = append(ret[name], val)
	}

	return ret
}

func (x *multiTag) cached() map[string][]string {
	if x.cache == nil {
		x.cache = x.scan()
	}

	return x.cache
}

func (x *multiTag) Get(key string) string {
	c := x.cached()

	if v, ok := c[key]; ok {
		return v[len(v)-1]
	}

	return ""
}

func (x *multiTag) GetMany(key string) []string {
	c := x.cached()
	return c[key]
}