/
content_text.go
68 lines (60 loc) · 1.57 KB
/
content_text.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
package builtin
import (
"bytes"
"context"
"fmt"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/zclconf/go-cty/cty"
"github.com/blackstork-io/fabric/plugin"
)
func makeTextContentProvider() *plugin.ContentProvider {
return &plugin.ContentProvider{
ContentFunc: genTextContent,
Args: hcldec.ObjectSpec{
"value": &hcldec.AttrSpec{
Name: "value",
Type: cty.String,
Required: true,
},
},
}
}
func genTextContent(ctx context.Context, params *plugin.ProvideContentParams) (*plugin.ContentResult, hcl.Diagnostics) {
value := params.Args.GetAttr("value")
if value.IsNull() {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Failed to parse arguments",
Detail: "value is required",
}}
}
text, err := genTextContentText(value.AsString(), params.DataContext)
if err != nil {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Failed to render text",
Detail: err.Error(),
}}
}
return &plugin.ContentResult{
Content: &plugin.ContentElement{
Markdown: text,
},
}, nil
}
func genTextContentText(text string, datactx plugin.MapData) (string, error) {
tmpl, err := template.New("text").Funcs(sprig.FuncMap()).Parse(text)
if err != nil {
return "", fmt.Errorf("failed to parse text template: %w", err)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, datactx.Any())
if err != nil {
return "", fmt.Errorf("failed to execute text template: %w", err)
}
return strings.TrimSpace(buf.String()), nil
}