/
data_txt.go
55 lines (50 loc) · 1.17 KB
/
data_txt.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
package builtin
import (
"context"
"io"
"os"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/zclconf/go-cty/cty"
"github.com/blackstork-io/fabric/plugin"
)
func makeTXTDataSource() *plugin.DataSource {
return &plugin.DataSource{
DataFunc: fetchTXTData,
Args: hcldec.ObjectSpec{
"path": &hcldec.AttrSpec{
Name: "path",
Type: cty.String,
Required: true,
},
},
}
}
func fetchTXTData(ctx context.Context, params *plugin.RetrieveDataParams) (plugin.Data, hcl.Diagnostics) {
path := params.Args.GetAttr("path")
if path.IsNull() || path.AsString() == "" {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Failed to parse arguments",
Detail: "path is required",
}}
}
f, err := os.Open(path.AsString())
if err != nil {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Failed to open txt file",
Detail: err.Error(),
}}
}
defer f.Close()
data, err := io.ReadAll(f)
if err != nil {
return nil, hcl.Diagnostics{{
Severity: hcl.DiagError,
Summary: "Failed to read txt file",
Detail: err.Error(),
}}
}
return plugin.StringData(string(data)), nil
}