This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 283
/
add.go
96 lines (83 loc) · 2.06 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package ipfs
import (
"context"
"gx/ipfs/QmQmhotPUzVrMEWNK3x1R5jQ5ZHWyL7tVUrmRPjrBrvyCb/go-ipfs-files"
"gx/ipfs/QmXLwxifxwfc2bAwq6rdjbYqAsGzWsDE9RM5TWMGtykyj6/interface-go-ipfs-core/options"
"io"
"io/ioutil"
"math/rand"
"os"
"strconv"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/coreapi"
"github.com/ipfs/go-ipfs/core/coreunix"
_ "github.com/ipfs/go-ipfs/core/mock"
)
// Recursively add a directory to IPFS and return the root hash
func AddDirectory(n *core.IpfsNode, root string) (rootHash string, err error) {
api, err := coreapi.NewCoreAPI(n)
if err != nil {
return "", err
}
stat, err := os.Lstat(root)
if err != nil {
return "", err
}
f, err := files.NewSerialFile(root, false, stat)
if err != nil {
return "", err
}
opts := []options.UnixfsAddOption{
options.Unixfs.CidVersion(0),
options.Unixfs.Pin(true),
options.Unixfs.Wrap(true),
}
pth, err := api.Unixfs().Add(context.Background(), files.ToDir(f), opts...)
if err != nil {
return "", err
}
return pth.Root().String(), nil
}
func AddFile(n *core.IpfsNode, file string) (string, error) {
return addAndPin(n, file)
}
func GetHashOfFile(n *core.IpfsNode, fpath string) (string, error) {
return AddFile(n, fpath)
}
func GetHash(n *core.IpfsNode, reader io.Reader) (string, error) {
f, err := ioutil.TempFile("", strconv.Itoa(rand.Int()))
if err != nil {
return "", err
}
b, err := ioutil.ReadAll(reader)
if err != nil {
return "", err
}
_, err = f.Write(b)
if err != nil {
return "", err
}
defer f.Close()
return GetHashOfFile(n, f.Name())
}
func addAndPin(n *core.IpfsNode, root string) (rootHash string, err error) {
defer n.Blockstore.PinLock().Unlock()
stat, err := os.Lstat(root)
if err != nil {
return "", err
}
f, err := files.NewSerialFile(root, false, stat)
if err != nil {
return "", err
}
defer f.Close()
fileAdder, err := coreunix.NewAdder(n.Context(), n.Pinning, n.Blockstore, n.DAG)
if err != nil {
return "", err
}
node, err := fileAdder.AddAllAndPin(f)
if err != nil {
return "", err
}
return node.Cid().String(), nil
}