blob: 98d0439f11dd2517674a5581d650093174c04e0a (
plain)
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
56
57
58
59
|
package debian
import (
"errors"
"fmt"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"go.wit.com/lib/config"
)
func SetDebInfoString(pb proto.Message, varname string, varvalue string) error {
// 1. Get the reflection interface for the top-level message (e.g., Package).
msg := pb.ProtoReflect()
descriptor := msg.Descriptor()
// 2. Find the FieldDescriptor for the nested message field (named "debInfo").
// This is the corrected line: call .Fields().ByName().
debInfoFieldDescriptor := descriptor.Fields().ByName("debInfo")
if debInfoFieldDescriptor == nil {
return fmt.Errorf("field 'debInfo' not found in message %s", descriptor.FullName())
}
// 3. From the field descriptor, get the MessageDescriptor for the DebInfo type.
// This gives us the "schema" for the DebInfo message.
debInfoMsgDescriptor := debInfoFieldDescriptor.Message()
if debInfoMsgDescriptor == nil {
// This would happen if the 'debInfo' field was not a message type.
// return ErrFieldNotMessage
return errors.New("debInfo failed to turn into a message?")
}
// 4. Now, find the FieldDescriptor for the target string field (varname)
// WITHIN the DebInfo message's schema.
fieldName := protoreflect.Name(varname)
fieldDescriptor := debInfoMsgDescriptor.Fields().ByName(fieldName)
if fieldDescriptor == nil {
return fmt.Errorf("field '%s' not found in nested message 'debInfo'", varname)
}
// 5. Validate that the target field is a string.
if fieldDescriptor.Kind() != protoreflect.StringKind {
return config.ErrProtoVarNotString
}
// 6. CRITICAL STEP: Get a mutable reference to the actual nested DebInfo message.
// msg.Mutable() is perfect for this. It will:
// a) Get the existing DebInfo message if it's already been set.
// b) Create a NEW, empty DebInfo message if it's currently nil.
// Then, we get the reflection interface for that nested message.
debInfoMsg := msg.Mutable(debInfoFieldDescriptor).Message()
// 7. Prepare the value and SET it on the nested message.
valueToSet := protoreflect.ValueOfString(varvalue)
debInfoMsg.Set(fieldDescriptor, valueToSet)
return nil
}
|