-
Notifications
You must be signed in to change notification settings - Fork 42
/
examples.go
91 lines (75 loc) · 2.38 KB
/
examples.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package tfbridge
import (
"bytes"
"os"
"path/filepath"
"text/template"
"github.com/pulumi/pulumi-terraform-bridge/v3/pkg/tfbridge/info"
)
// HclExampler represents a supplemental HCL example for a given resource or function.
type HclExampler = info.HclExampler
// LocalFileHclExample represents a supplemental HCL example that is on a relative path within the Pulumi provider repo.
type LocalFileHclExample struct {
// Token is the Pulumi identifier for the resource or function to which the example pertains, e.g.
// "provider:module/getFoo:getFoo" (function), or
// "provider:module/bar:Bar" (resource)
Token string
// Title is title of the example, e.g. "Basic Something", "Advanced Something with Something Else".
Title string
// RelativePath is the path to the file in the Pulumi repo relative to the repo root.
RelativePath string
}
// InlineHclExample represents a literal HCL example and is primarily used for testing the Bridge.
type InlineHclExample struct {
// Token is the Pulumi identifier for the resource or function to which the example pertains, e.g.
// "provider:module/getFoo:getFoo" (function), or
// "provider:module/bar:Bar" (resource)
Token string
// Title is title of the example, e.g. "Basic Something", "Advanced Something with Something Else".
Title string
// Contents is the HCL that comprises the example with no surrounding Markdown constructs (e.g. ```hcl`).
Contents string
}
func (e LocalFileHclExample) GetToken() string {
return e.Token
}
func (e LocalFileHclExample) GetMarkdown() (string, error) {
absPath, err := filepath.Abs(e.RelativePath)
if err != nil {
return "", err
}
fileBytes, err := os.ReadFile(absPath)
if err != nil {
return "", err
}
return renderTemplate(e.Title, string(fileBytes))
}
func (e InlineHclExample) GetToken() string {
return e.Token
}
func (e InlineHclExample) GetMarkdown() (string, error) {
return renderTemplate(e.Title, e.Contents)
}
func renderTemplate(title, contents string) (string, error) {
tmpl := `### {{ .Title }}
{{ .CodeFences }}hcl
{{ .Contents }}
{{ .CodeFences }}
`
outputTemplate, _ := template.New("dummy").Parse(tmpl)
data := struct {
CodeFences string
Title string
Contents string
}{
CodeFences: "```",
Title: title,
Contents: contents,
}
var buf = bytes.Buffer{}
err := outputTemplate.Execute(&buf, data)
if err != nil {
return "", err
}
return buf.String(), nil
}