-
Notifications
You must be signed in to change notification settings - Fork 6
/
files.go
84 lines (75 loc) · 2.15 KB
/
files.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
// SPDX-License-Identifier: GPL-3.0
// this package contains ipfs helper functions
package ipfs
import (
"context"
"fmt"
"io"
"os"
"github.com/ipfs/boxo/files"
"github.com/ipfs/boxo/path"
"github.com/ipfs/go-cid"
iface "github.com/ipfs/kubo/core/coreiface"
"google.golang.org/protobuf/proto"
)
// Adds a file (or a directory) from the local filesystem to IPFS
func AddFsFile(node iface.CoreAPI, pth string) (path.ImmutablePath, error) {
stats, err := os.Stat(pth)
if err != nil {
return path.ImmutablePath{}, err
}
serialFile, err := files.NewSerialFile(pth, false, stats)
if err != nil {
return path.ImmutablePath{}, err
}
return node.Unixfs().Add(context.Background(), serialFile)
}
// Saves an IPFS file or directory represented by the given files.Node to the specified local file system path.
func GetFsFile(node iface.CoreAPI, file files.Node, path path.Path, savePath string) error {
file, err := node.Unixfs().Get(context.Background(), path)
if err != nil {
return err
}
return files.WriteTo(file, savePath)
}
// Adds a file from a protobuf slice to IPFS
func AddProtobufFile(node iface.CoreAPI, msg proto.Message) (cid.Cid, error) {
bytes, err := proto.Marshal(msg)
if err != nil {
return cid.Cid{}, err
}
path, err := node.Unixfs().Add(context.Background(), files.NewBytesFile(bytes))
if err != nil {
return cid.Cid{}, err
}
return path.RootCid(), nil
}
func AddBytes(node iface.CoreAPI, msg []byte) (cid.Cid, error) {
path, err := node.Unixfs().Add(context.Background(), files.NewBytesFile(msg))
if err != nil {
return cid.Cid{}, err
}
return path.RootCid(), nil
}
func GetBytes(node iface.CoreAPI, cid cid.Cid) ([]byte, error) {
fileNode, err := node.Unixfs().Get(context.Background(), path.FromCid(cid))
if err != nil {
return nil, err
}
file, ok := fileNode.(files.File)
if !ok {
return nil, fmt.Errorf("Supplied CID (%s) not a file", cid.String())
}
bytes, err := io.ReadAll(file)
if err != nil {
return nil, err
}
return bytes, nil
}
func GetProtobufFile(node iface.CoreAPI, cid cid.Cid, msg proto.Message) error {
bytes, err := GetBytes(node, cid)
if err != nil {
return err
}
return proto.Unmarshal(bytes, msg)
}