forked from OpenBazaar/openbazaar-go
/
add.go
82 lines (77 loc) · 1.81 KB
/
add.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
package ipfs
import (
"errors"
"github.com/ipfs/go-ipfs/commands"
"github.com/ipfs/go-ipfs/core/coreunix"
"path"
)
var addErr = errors.New(`Add directory failed`)
// Resursively add a directory to IPFS and return the root hash
func AddDirectory(ctx commands.Context, fpath string) (rootHash string, err error) {
_, root := path.Split(fpath)
args := []string{"add", "-r", fpath}
req, cmd, err := NewRequest(ctx, args)
if err != nil {
return "", err
}
res := commands.NewResponse(req)
cmd.PreRun(req)
cmd.Run(req, res)
for r := range res.Output().(<-chan interface{}) {
if r.(*coreunix.AddedObject).Name == root {
rootHash = r.(*coreunix.AddedObject).Hash
}
}
cmd.PostRun(req, res)
if res.Error() != nil {
return "", res.Error()
}
if rootHash == "" {
return "", addErr
}
return rootHash, nil
}
func AddFile(ctx commands.Context, fpath string) (string, error) {
args := []string{"add", fpath}
req, cmd, err := NewRequest(ctx, args)
if err != nil {
return "", err
}
res := commands.NewResponse(req)
cmd.PreRun(req)
cmd.Run(req, res)
var fileHash string
for r := range res.Output().(<-chan interface{}) {
fileHash = r.(*coreunix.AddedObject).Hash
}
cmd.PostRun(req, res)
if res.Error() != nil {
return "", res.Error()
}
if fileHash == "" {
return "", addErr
}
return fileHash, nil
}
func GetHash(ctx commands.Context, fpath string) (string, error) {
args := []string{"add", "-n", fpath}
req, cmd, err := NewRequest(ctx, args)
if err != nil {
return "", err
}
res := commands.NewResponse(req)
cmd.PreRun(req)
cmd.Run(req, res)
var fileHash string
for r := range res.Output().(<-chan interface{}) {
fileHash = r.(*coreunix.AddedObject).Hash
}
cmd.PostRun(req, res)
if res.Error() != nil {
return "", res.Error()
}
if fileHash == "" {
return "", addErr
}
return fileHash, nil
}