func patchMsg(input, patch *data.DynamicMessage, indent int, sheetName string) bool { return patch.IterateFieldDesc(func(fd *pbmeta.FieldDescriptor) bool { if fd.Type() == pbprotos.FieldDescriptorProto_TYPE_MESSAGE { if fd.IsRepeated() { // 顶级的消息肯定是repeated的, 因此直接进入 if indent == 0 { nextInputMsgArray := input.GetRepeatedMessage(fd) nextPatchMsgArray := patch.GetRepeatedMessage(fd) if len(nextInputMsgArray) != len(nextPatchMsgArray) { log.Errorf("patch rows diff from input msg") return false } // 相同的行数才可以进去继续迭代 for index, nextInputMsg := range nextInputMsgArray { patchMsg(nextInputMsg, nextPatchMsgArray[index], indent+1, sheetName) } } else { // 直接替换值数组 pathMsgArray := patch.GetRepeatedMessage(fd) input.ClearFieldValue(fd) for _, msg := range pathMsgArray { input.AddRepeatedMessage(fd, msg) } } } else { nextInputMsg := input.GetMessage(fd) nextPatchMsg := patch.GetMessage(fd) patchMsg(nextInputMsg, nextPatchMsg, indent+1, sheetName) } } else { if fd.IsRepeated() { log.Infof("patch repeated field: '%s' = '%s'", fd.Name(), patch.GetRepeatedValue(fd)) // 直接用patch的覆盖多值 input.ClearFieldValue(fd) for _, v := range patch.GetRepeatedValue(fd) { input.AddRepeatedValue(fd, v) } } else { v, _ := patch.GetValue(fd) log.Infof("patch field: '%s' = '%s'", fd.Name(), v) // 单值设置 input.SetValue(fd, v) } } return true }) return true }
func writeString(msg *data.DynamicMessage, indent int) string { var out bytes.Buffer for i := 0; i < msg.Desc.FieldCount(); i++ { fd := msg.Desc.Field(i) if i > 0 { out.WriteString(" ") } if fd.Type() == pbprotos.FieldDescriptorProto_TYPE_MESSAGE { if fd.IsRepeated() { // 多结构 if msgList := msg.GetRepeatedMessage(fd); msgList != nil { for _, msg := range msgList { msgStr := makeMsg(msg, indent+1) if msgStr != "" { out.WriteString(fmt.Sprintf("%s %s", fd.Name(), msgStr)) if indent == 0 { out.WriteString("\n") } else { out.WriteString(" ") } } } continue } } else { // 单结构 if msg := msg.GetMessage(fd); msg != nil { msgStr := makeMsg(msg, indent+1) if msgStr != "" { out.WriteString(fmt.Sprintf("%s %s", fd.Name(), msgStr)) } continue } } } else { // 多值 if fd.IsRepeated() { if valuelist := msg.GetRepeatedValue(fd); valuelist != nil { for vIndex, value := range valuelist { if vIndex > 0 { out.WriteString(" ") } out.WriteString(makeValue(fd, value)) } continue } } else { // 单值 if value, ok := msg.GetValue(fd); ok { out.WriteString(makeValue(fd, value)) continue } } } } return out.String() }