|
4 | 4 | package component // import "go.opentelemetry.io/collector/component"
|
5 | 5 |
|
6 | 6 | import (
|
| 7 | + "fmt" |
7 | 8 | "reflect"
|
| 9 | + "regexp" |
8 | 10 |
|
9 | 11 | "go.uber.org/multierr"
|
10 | 12 |
|
@@ -110,6 +112,45 @@ func callValidateIfPossible(v reflect.Value) error {
|
110 | 112 | // Type is the component type as it is used in the config.
|
111 | 113 | type Type string
|
112 | 114 |
|
| 115 | +// String returns the string representation of the type. |
| 116 | +func (t Type) String() string { |
| 117 | + return string(t) |
| 118 | +} |
| 119 | + |
| 120 | +// typeRegexp is used to validate the type of a component. |
| 121 | +// A type must start with an ASCII alphabetic character and |
| 122 | +// can only contain ASCII alphanumeric characters and '_'. |
| 123 | +// This must be kept in sync with the regex in cmd/mdatagen/validate.go. |
| 124 | +var typeRegexp = regexp.MustCompile(`^[a-zA-Z][0-9a-zA-Z_]*$`) |
| 125 | + |
| 126 | +// NewType creates a type. It returns an error if the type is invalid. |
| 127 | +// A type must |
| 128 | +// - have at least one character, |
| 129 | +// - start with an ASCII alphabetic character and |
| 130 | +// - can only contain ASCII alphanumeric characters and '_'. |
| 131 | +func NewType(ty string) (Type, error) { |
| 132 | + if len(ty) == 0 { |
| 133 | + return Type(""), fmt.Errorf("id must not be empty") |
| 134 | + } |
| 135 | + if !typeRegexp.MatchString(ty) { |
| 136 | + return Type(""), fmt.Errorf("invalid character(s) in type %q", ty) |
| 137 | + } |
| 138 | + return Type(ty), nil |
| 139 | +} |
| 140 | + |
| 141 | +// MustNewType creates a type. It panics if the type is invalid. |
| 142 | +// A type must |
| 143 | +// - have at least one character, |
| 144 | +// - start with an ASCII alphabetic character and |
| 145 | +// - can only contain ASCII alphanumeric characters and '_'. |
| 146 | +func MustNewType(strType string) Type { |
| 147 | + ty, err := NewType(strType) |
| 148 | + if err != nil { |
| 149 | + panic(err) |
| 150 | + } |
| 151 | + return ty |
| 152 | +} |
| 153 | + |
113 | 154 | // DataType is a special Type that represents the data types supported by the collector. We currently support
|
114 | 155 | // collecting metrics, traces and logs, this can expand in the future.
|
115 | 156 | type DataType = Type
|
|
0 commit comments