github.com/0chain/gosdk@v1.17.11/zboxcore/allocationchange/renameobject.go (about) 1 package allocationchange 2 3 import ( 4 "path" 5 6 "github.com/0chain/errors" 7 "github.com/0chain/gosdk/core/common" 8 "github.com/0chain/gosdk/core/pathutil" 9 "github.com/0chain/gosdk/zboxcore/fileref" 10 ) 11 12 type RenameFileChange struct { 13 change 14 ObjectTree fileref.RefEntity 15 NewName string 16 } 17 18 func (ch *RenameFileChange) ProcessChange(rootRef *fileref.Ref, _ map[string]string) (err error) { 19 parentPath := path.Dir(ch.ObjectTree.GetPath()) 20 fields, err := common.GetPathFields(parentPath) 21 if err != nil { 22 return 23 } 24 dirRef := rootRef 25 for i := 0; i < len(fields); i++ { 26 found := false 27 for _, child := range dirRef.Children { 28 if child.GetName() == fields[i] { 29 dirRef = child.(*fileref.Ref) 30 found = true 31 break 32 } 33 } 34 if !found { 35 err = errors.New("invalid_reference_path", "Invalid reference path from the blobber") 36 return 37 } 38 } 39 40 found := false 41 var affectedRef *fileref.Ref 42 for i, child := range dirRef.Children { 43 if child.GetPath() == ch.ObjectTree.GetPath() { 44 dirRef.RemoveChild(i) 45 46 if ch.ObjectTree.GetType() == fileref.FILE { 47 affectedRef = &(ch.ObjectTree.(*fileref.FileRef)).Ref 48 } else { 49 affectedRef = ch.ObjectTree.(*fileref.Ref) 50 } 51 52 affectedRef.Path = pathutil.Join(parentPath, ch.NewName) 53 affectedRef.Name = ch.NewName 54 affectedRef.HashToBeComputed = true 55 56 dirRef.AddChild(ch.ObjectTree) 57 found = true 58 break 59 } 60 } 61 62 if !found { 63 err = errors.New("file_not_found", "Object to rename not found in blobber") 64 return 65 } 66 ch.processChildren(affectedRef) 67 return 68 } 69 70 func (ch *RenameFileChange) processChildren(curRef *fileref.Ref) { 71 for _, childRefEntity := range curRef.Children { 72 var childRef *fileref.Ref 73 if childRefEntity.GetType() == fileref.FILE { 74 childRef = &(childRefEntity.(*fileref.FileRef)).Ref 75 } else { 76 childRef = childRefEntity.(*fileref.Ref) 77 } 78 childRef.HashToBeComputed = true 79 childRef.Path = pathutil.Join(curRef.Path, childRef.Name) 80 if childRefEntity.GetType() == fileref.DIRECTORY { 81 ch.processChildren(childRef) 82 } 83 } 84 } 85 86 func (n *RenameFileChange) GetAffectedPath() []string { 87 if n.ObjectTree != nil { 88 return []string{n.ObjectTree.GetPath()} 89 } 90 return nil 91 } 92 93 func (n *RenameFileChange) GetSize() int64 { 94 return int64(0) 95 }