Skip to content

Commit

Permalink
[chore] replace the usage of interface{} with any (open-telemetry#7053)
Browse files Browse the repository at this point in the history
Signed-off-by: Bogdan Drutu <bogdandrutu@gmail.com>
  • Loading branch information
bogdandrutu authored Jan 30, 2023
1 parent 26bd7b2 commit a2f0153
Show file tree
Hide file tree
Showing 41 changed files with 315 additions and 318 deletions.
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ type AuthData interface {
// implementations might define different data types for different
// attributes. While "string" is used most of the time, a key named
// "membership" might return a list of strings.
GetAttribute(string) interface{}
GetAttribute(string) any

// GetAttributes returns the names of all attributes in this authentication
// data.
Expand Down
2 changes: 1 addition & 1 deletion client/doc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ type exampleAuthData struct {
username string
}

func (e *exampleAuthData) GetAttribute(key string) interface{} {
func (e *exampleAuthData) GetAttribute(key string) any {
if key == "username" {
return e.username
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/builder/internal/builder/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func GetModules(cfg Config) error {
return fmt.Errorf("failed to download go modules: %s", failReason)
}

func processAndWrite(cfg Config, tmpl *template.Template, outFile string, tmplParams interface{}) error {
func processAndWrite(cfg Config, tmpl *template.Template, outFile string, tmplParams any) error {
out, err := os.Create(filepath.Clean(filepath.Join(cfg.Distribution.OutputPath, outFile)))
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion component/componenttest/configtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ var configFieldTagRegExp = regexp.MustCompile("^[a-z0-9][a-z0-9_]*$")
// of components and extensions. It is recommended for implementers of components
// to call this function on their tests passing the default configuration of the
// component factory.
func CheckConfigStruct(config interface{}) error {
func CheckConfigStruct(config any) error {
t := reflect.TypeOf(config)
if t.Kind() == reflect.Ptr {
t = t.Elem()
Expand Down
2 changes: 1 addition & 1 deletion component/componenttest/configtest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func TestCheckConfigStruct(t *testing.T) {

tests := []struct {
name string
config interface{}
config any
wantErrMsgSubStr string
}{
{
Expand Down
2 changes: 1 addition & 1 deletion component/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import (
// (e.g. check if a required field is present).
//
// A valid implementation MUST pass the check componenttest.CheckConfigStruct (return nil error).
type Config interface{}
type Config any

// As interface types are only used for static typing, a common idiom to find the reflection Type
// for an interface type Foo is to use a *Foo value.
Expand Down
16 changes: 8 additions & 8 deletions config/configgrpc/configgrpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,10 +363,10 @@ func (gss *GRPCServerSettings) toServerOption(host component.Host, settings comp
return nil, err
}

uInterceptors = append(uInterceptors, func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
uInterceptors = append(uInterceptors, func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {
return authUnaryServerInterceptor(ctx, req, info, handler, authenticator)
})
sInterceptors = append(sInterceptors, func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
sInterceptors = append(sInterceptors, func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return authStreamServerInterceptor(srv, ss, info, handler, authenticator)
})
}
Expand Down Expand Up @@ -406,14 +406,14 @@ func getGRPCCompressionName(compressionType configcompression.CompressionType) (

// enhanceWithClientInformation intercepts the incoming RPC, replacing the incoming context with one that includes
// a client.Info, potentially with the peer's address.
func enhanceWithClientInformation(includeMetadata bool) func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
func enhanceWithClientInformation(includeMetadata bool) func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
return handler(contextWithClient(ctx, includeMetadata), req)
}
}

func enhanceStreamWithClientInformation(includeMetadata bool) func(srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return func(srv interface{}, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
func enhanceStreamWithClientInformation(includeMetadata bool) func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
return handler(srv, wrapServerStream(contextWithClient(ss.Context(), includeMetadata), ss))
}
}
Expand All @@ -437,7 +437,7 @@ func contextWithClient(ctx context.Context, includeMetadata bool) context.Contex
return client.NewContext(ctx, cl)
}

func authUnaryServerInterceptor(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler, server auth.Server) (interface{}, error) {
func authUnaryServerInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler, server auth.Server) (any, error) {
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errMetadataNotFound
Expand All @@ -451,7 +451,7 @@ func authUnaryServerInterceptor(ctx context.Context, req interface{}, _ *grpc.Un
return handler(ctx, req)
}

func authStreamServerInterceptor(srv interface{}, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler, server auth.Server) error {
func authStreamServerInterceptor(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler, server auth.Server) error {
ctx := stream.Context()
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
Expand Down
10 changes: 5 additions & 5 deletions config/configgrpc/configgrpc_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,35 +98,35 @@ func compress(compressor encoding.Compressor, in []byte) ([]byte, error) {

type testPayload struct {
name string
message interface{}
message any
marshaler marshaler
}

type marshaler interface {
marshal(interface{}) ([]byte, error)
marshal(any) ([]byte, error)
}

type logMarshaler struct {
plog.Marshaler
}

func (m *logMarshaler) marshal(e interface{}) ([]byte, error) {
func (m *logMarshaler) marshal(e any) ([]byte, error) {
return m.MarshalLogs(e.(plog.Logs))
}

type traceMarshaler struct {
ptrace.Marshaler
}

func (m *traceMarshaler) marshal(e interface{}) ([]byte, error) {
func (m *traceMarshaler) marshal(e any) ([]byte, error) {
return m.MarshalTraces(e.(ptrace.Traces))
}

type metricsMarshaler struct {
pmetric.Marshaler
}

func (m *metricsMarshaler) marshal(e interface{}) ([]byte, error) {
func (m *metricsMarshaler) marshal(e any) ([]byte, error) {
return m.MarshalMetrics(e.(pmetric.Metrics))
}

Expand Down
14 changes: 7 additions & 7 deletions config/configgrpc/configgrpc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,7 +796,7 @@ func TestStreamInterceptorEnhancesClient(t *testing.T) {
ctx: inCtx,
}

handler := func(srv interface{}, stream grpc.ServerStream) error {
handler := func(srv any, stream grpc.ServerStream) error {
outContext = stream.Context()
return nil
}
Expand Down Expand Up @@ -910,7 +910,7 @@ func TestDefaultUnaryInterceptorAuthSucceeded(t *testing.T) {

return ctx, nil
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
handler := func(ctx context.Context, req any) (any, error) {
handlerCalled = true
cl := client.FromContext(ctx)
assert.Equal(t, "1.2.3.4", cl.Addr.String())
Expand All @@ -936,7 +936,7 @@ func TestDefaultUnaryInterceptorAuthFailure(t *testing.T) {
authCalled = true
return context.Background(), expectedErr
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
handler := func(ctx context.Context, req any) (any, error) {
assert.FailNow(t, "the handler should not have been called on auth failure!")
return nil, nil
}
Expand All @@ -957,7 +957,7 @@ func TestDefaultUnaryInterceptorMissingMetadata(t *testing.T) {
assert.FailNow(t, "the auth func should not have been called!")
return context.Background(), nil
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
handler := func(ctx context.Context, req any) (any, error) {
assert.FailNow(t, "the handler should not have been called!")
return nil, nil
}
Expand All @@ -981,7 +981,7 @@ func TestDefaultStreamInterceptorAuthSucceeded(t *testing.T) {
})
return ctx, nil
}
handler := func(srv interface{}, stream grpc.ServerStream) error {
handler := func(srv any, stream grpc.ServerStream) error {
// ensure that the client information is propagated down to the underlying stream
cl := client.FromContext(stream.Context())
assert.Equal(t, "1.2.3.4", cl.Addr.String())
Expand Down Expand Up @@ -1010,7 +1010,7 @@ func TestDefaultStreamInterceptorAuthFailure(t *testing.T) {
authCalled = true
return context.Background(), expectedErr
}
handler := func(srv interface{}, stream grpc.ServerStream) error {
handler := func(srv any, stream grpc.ServerStream) error {
assert.FailNow(t, "the handler should not have been called on auth failure!")
return nil
}
Expand All @@ -1033,7 +1033,7 @@ func TestDefaultStreamInterceptorMissingMetadata(t *testing.T) {
assert.FailNow(t, "the auth func should not have been called!")
return context.Background(), nil
}
handler := func(srv interface{}, stream grpc.ServerStream) error {
handler := func(srv any, stream grpc.ServerStream) error {
assert.FailNow(t, "the handler should not have been called!")
return nil
}
Expand Down
44 changes: 22 additions & 22 deletions confmap/confmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ func New() *Conf {
return &Conf{k: koanf.New(KeyDelimiter)}
}

// NewFromStringMap creates a confmap.Conf from a map[string]interface{}.
func NewFromStringMap(data map[string]interface{}) *Conf {
// NewFromStringMap creates a confmap.Conf from a map[string]any.
func NewFromStringMap(data map[string]any) *Conf {
p := New()
// Cannot return error because the koanf instance is empty.
_ = p.k.Load(confmap.Provider(data, KeyDelimiter), nil)
Expand Down Expand Up @@ -82,7 +82,7 @@ func (fn unmarshalOptionFunc) apply(set *unmarshalOption) {

// Unmarshal unmarshalls the config into a struct using the given options.
// Tags on the fields of the structure must be properly set.
func (l *Conf) Unmarshal(result interface{}, opts ...UnmarshalOption) error {
func (l *Conf) Unmarshal(result any, opts ...UnmarshalOption) error {
set := unmarshalOption{}
for _, opt := range opts {
opt.apply(&set)
Expand All @@ -97,21 +97,21 @@ type MarshalOption interface {
}

// Marshal encodes the config and merges it into the Conf.
func (l *Conf) Marshal(rawVal interface{}, _ ...MarshalOption) error {
func (l *Conf) Marshal(rawVal any, _ ...MarshalOption) error {
enc := encoder.New(encoderConfig(rawVal))
data, err := enc.Encode(rawVal)
if err != nil {
return err
}
out, ok := data.(map[string]interface{})
out, ok := data.(map[string]any)
if !ok {
return fmt.Errorf("invalid config encoding")
}
return l.Merge(NewFromStringMap(out))
}

// Get can retrieve any value given the key to use.
func (l *Conf) Get(key string) interface{} {
func (l *Conf) Get(key string) any {
return l.k.Get(key)
}

Expand All @@ -128,23 +128,23 @@ func (l *Conf) Merge(in *Conf) error {
}

// Sub returns new Conf instance representing a sub-config of this instance.
// It returns an error is the sub-config is not a map[string]interface{} (use Get()), and an empty Map if none exists.
// It returns an error is the sub-config is not a map[string]any (use Get()), and an empty Map if none exists.
func (l *Conf) Sub(key string) (*Conf, error) {
// Code inspired by the koanf "Cut" func, but returns an error instead of empty map for unsupported sub-config type.
data := l.Get(key)
if data == nil {
return New(), nil
}

if v, ok := data.(map[string]interface{}); ok {
if v, ok := data.(map[string]any); ok {
return NewFromStringMap(v), nil
}

return nil, fmt.Errorf("unexpected sub-config value kind for key:%s value:%v kind:%v)", key, data, reflect.TypeOf(data).Kind())
}

// ToStringMap creates a map[string]interface{} from a Parser.
func (l *Conf) ToStringMap() map[string]interface{} {
// ToStringMap creates a map[string]any from a Parser.
func (l *Conf) ToStringMap() map[string]any {
return maps.Unflatten(l.k.All(), KeyDelimiter)
}

Expand All @@ -155,7 +155,7 @@ func (l *Conf) ToStringMap() map[string]interface{} {
// uniqueness of component IDs (see mapKeyStringToMapKeyTextUnmarshalerHookFunc).
// Decodes time.Duration from strings. Allows custom unmarshaling for structs implementing
// encoding.TextUnmarshaler. Allows custom unmarshaling for structs implementing confmap.Unmarshaler.
func decodeConfig(m *Conf, result interface{}, errorUnused bool) error {
func decodeConfig(m *Conf, result any, errorUnused bool) error {
dc := &mapstructure.DecoderConfig{
ErrorUnused: errorUnused,
Result: result,
Expand All @@ -180,7 +180,7 @@ func decodeConfig(m *Conf, result interface{}, errorUnused bool) error {
// encoderConfig returns a default encoder.EncoderConfig that includes
// an EncodeHook that handles both TextMarshaller and Marshaler
// interfaces.
func encoderConfig(rawVal interface{}) *encoder.EncoderConfig {
func encoderConfig(rawVal any) *encoder.EncoderConfig {
return &encoder.EncoderConfig{
EncodeHook: mapstructure.ComposeDecodeHookFunc(
encoder.TextMarshalerHookFunc(),
Expand All @@ -205,7 +205,7 @@ func encoderConfig(rawVal interface{}) *encoder.EncoderConfig {
// we want an unmarshaled Config to be equivalent to
// Config{Thing: &SomeStruct{}} instead of Config{Thing: nil}
func expandNilStructPointersHookFunc() mapstructure.DecodeHookFuncValue {
return func(from reflect.Value, to reflect.Value) (interface{}, error) {
return func(from reflect.Value, to reflect.Value) (any, error) {
// ensure we are dealing with map to map comparison
if from.Kind() == reflect.Map && to.Kind() == reflect.Map {
toElem := to.Type().Elem()
Expand All @@ -229,13 +229,13 @@ func expandNilStructPointersHookFunc() mapstructure.DecodeHookFuncValue {
}

// mapKeyStringToMapKeyTextUnmarshalerHookFunc returns a DecodeHookFuncType that checks that a conversion from
// map[string]interface{} to map[encoding.TextUnmarshaler]interface{} does not overwrite keys,
// map[string]any to map[encoding.TextUnmarshaler]any does not overwrite keys,
// when UnmarshalText produces equal elements from different strings (e.g. trims whitespaces).
//
// This is needed in combination with ComponentID, which may produce equal IDs for different strings,
// and an error needs to be returned in that case, otherwise the last equivalent ID overwrites the previous one.
func mapKeyStringToMapKeyTextUnmarshalerHookFunc() mapstructure.DecodeHookFuncType {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
return func(f reflect.Type, t reflect.Type, data any) (any, error) {
if f.Kind() != reflect.Map || f.Key().Kind() != reflect.String {
return data, nil
}
Expand All @@ -249,7 +249,7 @@ func mapKeyStringToMapKeyTextUnmarshalerHookFunc() mapstructure.DecodeHookFuncTy
}

m := reflect.MakeMap(reflect.MapOf(t.Key(), reflect.TypeOf(true)))
for k := range data.(map[string]interface{}) {
for k := range data.(map[string]any) {
tKey := reflect.New(t.Key())
if err := tKey.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(k)); err != nil {
return nil, err
Expand All @@ -266,8 +266,8 @@ func mapKeyStringToMapKeyTextUnmarshalerHookFunc() mapstructure.DecodeHookFuncTy

// Provides a mechanism for individual structs to define their own unmarshal logic,
// by implementing the Unmarshaler interface.
func unmarshalerHookFunc(result interface{}) mapstructure.DecodeHookFuncValue {
return func(from reflect.Value, to reflect.Value) (interface{}, error) {
func unmarshalerHookFunc(result any) mapstructure.DecodeHookFuncValue {
return func(from reflect.Value, to reflect.Value) (any, error) {
if !to.CanAddr() {
return from.Interface(), nil
}
Expand All @@ -283,7 +283,7 @@ func unmarshalerHookFunc(result interface{}) mapstructure.DecodeHookFuncValue {
return from.Interface(), nil
}

if _, ok = from.Interface().(map[string]interface{}); !ok {
if _, ok = from.Interface().(map[string]any); !ok {
return from.Interface(), nil
}

Expand All @@ -292,7 +292,7 @@ func unmarshalerHookFunc(result interface{}) mapstructure.DecodeHookFuncValue {
unmarshaler = reflect.New(to.Type()).Interface().(Unmarshaler)
}

if err := unmarshaler.Unmarshal(NewFromStringMap(from.Interface().(map[string]interface{}))); err != nil {
if err := unmarshaler.Unmarshal(NewFromStringMap(from.Interface().(map[string]any))); err != nil {
return nil, err
}

Expand All @@ -302,9 +302,9 @@ func unmarshalerHookFunc(result interface{}) mapstructure.DecodeHookFuncValue {

// marshalerHookFunc returns a DecodeHookFuncValue that checks structs that aren't
// the original to see if they implement the Marshaler interface.
func marshalerHookFunc(orig interface{}) mapstructure.DecodeHookFuncValue {
func marshalerHookFunc(orig any) mapstructure.DecodeHookFuncValue {
origType := reflect.TypeOf(orig)
return func(from reflect.Value, _ reflect.Value) (interface{}, error) {
return func(from reflect.Value, _ reflect.Value) (any, error) {
if from.Kind() != reflect.Struct {
return from.Interface(), nil
}
Expand Down
Loading

0 comments on commit a2f0153

Please sign in to comment.