Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/pkg/river/encoding/attribute.go
4095 views
1
package encoding
2
3
import (
4
"encoding/json"
5
"fmt"
6
"strings"
7
8
"github.com/grafana/agent/pkg/river/internal/rivertags"
9
"github.com/grafana/agent/pkg/river/internal/value"
10
)
11
12
// attributeField represents a JSON representation of a river attribute.
13
type attributeField struct {
14
field `json:",omitempty"`
15
valField riverField
16
}
17
18
func newAttribute(val value.Value, f rivertags.Field) (*attributeField, error) {
19
af := &attributeField{}
20
return af, af.convertAttribute(val, f)
21
}
22
23
func (af *attributeField) hasValue() bool {
24
if af == nil || af.valField == nil {
25
return false
26
}
27
return af.valField.hasValue()
28
}
29
30
// MarshalJSON implements json marshaller.
31
func (af *attributeField) MarshalJSON() ([]byte, error) {
32
if af.valField == nil {
33
return nil, fmt.Errorf("the value of the attribute field is nil")
34
}
35
36
if af.valField.hasValue() {
37
af.field.Value = af.valField
38
} else {
39
return nil, fmt.Errorf("attribute field did not have any valid values")
40
}
41
42
type temp attributeField
43
return json.Marshal((*temp)(af))
44
}
45
46
func (af *attributeField) convertAttribute(val value.Value, f rivertags.Field) error {
47
if !f.IsAttr() {
48
return fmt.Errorf("convertAttribute requires a field that is an attribute got %T", val.Interface())
49
}
50
if !val.Reflect().IsValid() {
51
return nil
52
}
53
af.Type = attrType
54
af.Name = strings.Join(f.Name, ".")
55
56
rv, err := convertRiverValue(val)
57
if err != nil {
58
return err
59
}
60
if !rv.hasValue() {
61
return nil
62
}
63
af.valField = rv
64
return nil
65
}
66
67