-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy.go
More file actions
38 lines (33 loc) · 1.28 KB
/
copy.go
File metadata and controls
38 lines (33 loc) · 1.28 KB
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
package protopatch
import "google.golang.org/protobuf/proto"
func Copy(base proto.Message, targetPath, replacementPath string, opts ...Option) error {
return copyWithSetup(base, targetPath, replacementPath, newSetup(opts...))
}
func copyWithSetup(base proto.Message, targetPath, replacementPath string, setup *setup) error {
if targetPath == replacementPath { // set value pointed by path to itself
return setToItself(base, targetPath, setup)
}
var replacementValue any
if replacementPath == "" { // replacement path refers to base message
replacementValue = proto.Clone(base)
} else if last := Path(replacementPath).Last(); !last.IsFirst() { // replacement path has more than 1 element
replacementContainer, err := access(MessageContainer(base), last.PrecedingPath(), setup)
if err != nil {
return err
}
replacementValue, err = replacementContainer.GetCopy(last.Value())
if err != nil {
return NewErrInPath(string(last.PrecedingPath()), err)
}
} else { // path has only 1 element
replacementContainer, err := transformContainer(MessageContainer(base), setup)
if err != nil {
return err
}
replacementValue, err = replacementContainer.GetCopy(replacementPath)
if err != nil {
return err
}
}
return setWithSetup(base, targetPath, replacementValue, setup)
}