forked from whyrusleeping/ipfs-embedded-shell
/
object.go
123 lines (101 loc) · 2.56 KB
/
object.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package embeddedShell
import (
"errors"
"fmt"
core "github.com/ipfs/go-ipfs/core"
dag "github.com/ipfs/go-ipfs/merkledag"
dagutils "github.com/ipfs/go-ipfs/merkledag/utils"
path "github.com/ipfs/go-ipfs/path"
ft "github.com/ipfs/go-ipfs/unixfs"
)
func (s *Shell) NewObject(template string) (string, error) {
node := new(dag.ProtoNode)
switch template {
case "":
break
case "unixfs-dir":
node.SetData(ft.FolderPBData())
default:
return "", fmt.Errorf("unknown template %s", template)
}
c, err := s.node.DAG.Add(node)
if err != nil {
return "", err
}
return c.String(), nil
}
// TODO: extract all this logic from the core/commands/object.go to avoid dupe code
func (s *Shell) Patch(root, action string, args ...string) (string, error) {
p, err := path.ParsePath(root)
if err != nil {
return "", err
}
nd, err := core.Resolve(s.ctx, s.node.Namesys, s.node.Resolver, p)
if err != nil {
return "", err
}
rootnd, ok := nd.(*dag.ProtoNode)
if !ok {
return "", errors.New("could not cast Node to ProtoNode")
}
insertpath := args[0]
childhash := args[1]
childpath, err := path.ParsePath(childhash)
if err != nil {
return "", err
}
nnode, err := core.Resolve(s.ctx, s.node.Namesys, s.node.Resolver, childpath)
if err != nil {
return "", err
}
e := dagutils.NewDagEditor(rootnd, s.node.DAG)
switch action {
case "add-link":
err := e.InsertNodeAtPath(s.ctx, insertpath, nnode, nil)
if err != nil {
return "", err
}
_, err = e.Finalize(s.node.DAG)
if err != nil {
return "", err
}
return e.GetNode().Cid().String(), nil
default:
return "", fmt.Errorf("unsupported action (impl not complete)")
}
}
//TODO: hrm, maybe this interface could be better
func (s *Shell) PatchLink(root, npath, childhash string, create bool) (string, error) {
p, err := path.ParsePath(root)
if err != nil {
return "", err
}
nd, err := core.Resolve(s.ctx, s.node.Namesys, s.node.Resolver, p)
if err != nil {
return "", err
}
rootnd, ok := nd.(*dag.ProtoNode)
if !ok {
return "", errors.New("could not cast Node to ProtoNode")
}
childpath, err := path.ParsePath(childhash)
if err != nil {
return "", err
}
nnode, err := core.Resolve(s.ctx, s.node.Namesys, s.node.Resolver, childpath)
if err != nil {
return "", err
}
e := dagutils.NewDagEditor(rootnd, s.node.DAG)
err = e.InsertNodeAtPath(s.ctx, npath, nnode, func() *dag.ProtoNode {
return dag.NodeWithData(ft.FolderPBData())
})
if err != nil {
return "", err
}
_, err = e.Finalize(s.node.DAG)
if err != nil {
return "", err
}
return e.GetNode().Cid().String(), nil
}