summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/agent/discovery/sd/model/tags.go
blob: e36f0b8f53b45c66b0de664d9f9dfe45e0bc3c30 (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
74
75
76
77
78
79
80
81
// SPDX-License-Identifier: GPL-3.0-or-later

package model

import (
	"fmt"
	"sort"
	"strings"
)

type Base struct {
	tags Tags
}

func (b *Base) Tags() Tags {
	if b.tags == nil {
		b.tags = NewTags()
	}
	return b.tags
}

type Tags map[string]struct{}

func NewTags() Tags {
	return Tags{}
}

func (t Tags) Merge(tags Tags) {
	for tag := range tags {
		if strings.HasPrefix(tag, "-") {
			delete(t, tag[1:])
		} else {
			t[tag] = struct{}{}
		}
	}
}

func (t Tags) String() string {
	ts := make([]string, 0, len(t))
	for key := range t {
		ts = append(ts, key)
	}
	sort.Strings(ts)
	return fmt.Sprintf("{%s}", strings.Join(ts, ", "))
}

func ParseTags(line string) (Tags, error) {
	words := strings.Fields(line)
	if len(words) == 0 {
		return NewTags(), nil
	}

	tags := NewTags()
	for _, tag := range words {
		if !isTagWordValid(tag) {
			return nil, fmt.Errorf("tags '%s' contains tag '%s' with forbidden symbol", line, tag)
		}
		tags[tag] = struct{}{}
	}
	return tags, nil
}

func isTagWordValid(word string) bool {
	// valid:
	// ^[a-zA-Z][a-zA-Z0-9=_.]*$
	word = strings.TrimPrefix(word, "-")
	if len(word) == 0 {
		return false
	}
	for i, b := range word {
		switch {
		default:
			return false
		case b >= 'a' && b <= 'z':
		case b >= 'A' && b <= 'Z':
		case b >= '0' && b <= '9' && i > 0:
		case (b == '=' || b == '_' || b == '.') && i > 0:
		}
	}
	return true
}