| 1 | // Copyright 2026 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package otel |
| 6 | |
| 7 | import ( |
| 8 | "fmt" |
| 9 | |
| 10 | "golang.org/x/tools/internal/event/keys" |
| 11 | "golang.org/x/tools/internal/event/label" |
| 12 | ) |
| 13 | |
| 14 | // labelToAttribute converts a label to an OTLP attribute. |
| 15 | // It returns false if the label has no value. |
| 16 | func labelToAttribute(l label.Label) (otlpAttribute, bool) { |
| 17 | key := l.Key() |
| 18 | var v otlpAttributeValue |
| 19 | |
| 20 | switch key := key.(type) { |
| 21 | case *keys.Int: |
| 22 | v = otlpAttributeValue{IntValue: varOf(intAsString(key.From(l)))} |
| 23 | case *keys.Uint: |
| 24 | v = otlpAttributeValue{IntValue: varOf(intAsString(key.From(l)))} |
| 25 | case *keys.Float: |
| 26 | v = otlpAttributeValue{DoubleValue: varOf(key.From(l))} |
| 27 | case *keys.String: |
| 28 | v = otlpAttributeValue{StringValue: varOf(key.From(l))} |
| 29 | case *keys.Error: |
| 30 | if err := key.From(l); err != nil { |
| 31 | v = otlpAttributeValue{StringValue: varOf(err.Error())} |
| 32 | } |
| 33 | case *keys.Value: |
| 34 | v = otlpAttributeValue{StringValue: varOf(fmt.Sprint(key.From(l)))} |
| 35 | default: |
| 36 | if l.Valid() { |
| 37 | v = otlpAttributeValue{StringValue: varOf(fmt.Sprint(l))} |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | hasValue := v.StringValue != nil || v.IntValue != nil || v.DoubleValue != nil |
| 42 | return otlpAttribute{Key: key.Name(), Value: v}, hasValue |
| 43 | } |
| 44 | |
| 45 | // TODO(adonovan): use go1.26 new(expr) |
| 46 | func varOf[T any](x T) *T { return &x } |