File: util.go

package info (click to toggle)
golang-github-influxdata-toml 0.0~git20160905.0.ad49a5c-1.1
  • links: PTS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 256 kB
  • sloc: makefile: 14
file content (79 lines) | stat: -rw-r--r-- 1,724 bytes parent folder | download | duplicates (3)
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
package toml

import (
	"go/ast"
	"reflect"
	"strings"
	"unicode"
)

// toCamelCase returns a copy of the string s with all Unicode letters mapped to their camel case.
// It will convert to upper case previous letter of '_' and first letter, and remove letter of '_'.
func toCamelCase(s string) string {
	if s == "" {
		return ""
	}
	result := make([]rune, 0, len(s))
	upper := false
	for _, r := range s {
		if r == '_' {
			upper = true
			continue
		}
		if upper {
			result = append(result, unicode.ToUpper(r))
			upper = false
			continue
		}
		result = append(result, r)
	}
	result[0] = unicode.ToUpper(result[0])
	return string(result)
}

const (
	fieldTagName = "toml"
)

func findField(rv reflect.Value, name string) (field reflect.Value, fieldName string, found bool) {
	switch rv.Kind() {
	case reflect.Struct:
		rt := rv.Type()
		for i := 0; i < rt.NumField(); i++ {
			ft := rt.Field(i)
			if !ast.IsExported(ft.Name) {
				continue
			}
			if col, _ := extractTag(ft.Tag.Get(fieldTagName)); col == name {
				return rv.Field(i), ft.Name, true
			}
		}
		for _, name := range []string{
			strings.Title(name),
			toCamelCase(name),
			strings.ToUpper(name),
		} {
			if field := rv.FieldByName(name); field.IsValid() {
				return field, name, true
			}
		}
	case reflect.Map:
		return reflect.New(rv.Type().Elem()).Elem(), name, true
	}
	return field, "", false
}

func extractTag(tag string) (col, rest string) {
	tags := strings.SplitN(tag, ",", 2)
	if len(tags) == 2 {
		return strings.TrimSpace(tags[0]), strings.TrimSpace(tags[1])
	}
	return strings.TrimSpace(tags[0]), ""
}

func tableName(prefix, name string) string {
	if prefix != "" {
		return prefix + string(tableSeparator) + name
	}
	return name
}