writers.tagGroup   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
package writers
2
3
import (
4
	"fmt"
5
	"github.com/vvval/go-metadata-scanner/vars"
6
	"os"
7
	"strings"
8
)
9
10
type Writer interface {
11
	Open(filename string, headers []string) error
12
	Close() error
13
	Write(file *vars.File) error
14
}
15
16
type BaseWriter struct {
17
	file     *os.File
18
	filename string
19
	headers  []string
20
}
21
22
func NewWriter(filename string, headers []string) BaseWriter {
23
	return BaseWriter{
24
		filename: filename,
25
		headers:  headers,
26
	}
27
}
28
29
func openFile(filename string) (*os.File, error) {
30
	file, err := os.Create(filename)
31
	if err != nil {
32
		return nil, err
33
	}
34
35
	return file, nil
36
}
37
38
func closeFile(file *os.File) {
39
	if file != nil {
40
		file.Close()
41
	}
42
}
43
44
func tagsByGroups(f *vars.File, groups []string) map[string]map[string]string {
45
	tags := make(map[string]map[string]string)
46
	for tag, value := range f.Tags() {
47
		for _, group := range groups {
48
			if groupPrefixMatch(tag, group) {
49
				tagGroup := tagGroup(tag)
50
				if _, ok := tags[tagGroup]; !ok {
51
					tags[tagGroup] = make(map[string]string)
52
				}
53
54
				tags[tagGroup][tagName(tag)] = fmt.Sprintf("%v", value)
55
			}
56
		}
57
	}
58
59
	return tags
60
}
61
62
func groupPrefixMatch(tag, group string) bool {
63
	return strings.HasPrefix(strings.ToLower(tag), strings.ToLower(group)+":")
64
}
65
66
func tagGroup(tag string) string {
67
	return tag[:groupSeparatorPos(tag)]
68
}
69
70
func tagName(tag string) string {
71
	return tag[groupSeparatorPos(tag)+1:]
72
}
73
74
func groupSeparatorPos(tag string) int {
75
	return strings.Index(tag, ":")
76
}
77