forked from open-telemetry/opentelemetry-collector-contrib
/
template.go
72 lines (63 loc) · 1.82 KB
/
template.go
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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package docsgen // import "github.com/open-telemetry/opentelemetry-collector-contrib/cmd/configschema/docsgen/docsgen"
import (
"fmt"
"strings"
"text/template"
)
func tableTemplate() (*template.Template, error) {
return template.New("table").Option("missingkey=zero").Funcs(
template.FuncMap{
"join": join,
"mkAnchor": mkAnchor,
"isCompoundField": isCompoundField,
"isDuration": isDuration,
},
).Parse(tableTemplateStr)
}
func isCompoundField(kind string) bool {
return kind == "struct" || kind == "ptr"
}
func join(s string) string {
return strings.ReplaceAll(s, "\n", " ")
}
// mkAnchor takes a name and a type (e.g. "configtls.ClientConfig") and
// returns a string suitable for use as a markdown anchor.
func mkAnchor(name, typ string) string {
if isDuration(typ) {
return "time-Duration"
}
idx := strings.IndexRune(typ, '.')
// strip "configtls." from e.g. "configtls.ClientConfig"
typeStripped := typ[idx+1:]
concat := fmt.Sprintf("%s-%s", name, typeStripped)
asterisksRemoved := strings.ReplaceAll(concat, "*", "")
dotsToDashes := strings.ReplaceAll(asterisksRemoved, ".", "-")
return strings.ReplaceAll(dotsToDashes, "_", "-")
}
func isDuration(s string) bool {
return s == "time.Duration"
}
const tableTemplateStr = `### {{ mkAnchor .Name .Type }}
| Name | Field Info | Default | Docs |
| ---- | --------- | ------- | ---- |
{{ range .Fields -}}
| {{ .Name }} |
{{- if .Type -}}
{{- $anchor := mkAnchor .Name .Type -}}
{{- if isCompoundField .Kind -}}
[{{ $anchor }}](#{{ $anchor }})
{{- else -}}
{{- if isDuration .Type -}}
[{{ $anchor }}](#{{ $anchor }})
{{- else -}}
{{ .Type }}
{{- end -}}
{{- end -}}
{{- else -}}
{{ .Kind }}
{{- end -}}
| {{ .Default }} | {{ join .Doc }} |
{{ end }}
`