-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.go
51 lines (43 loc) · 1.2 KB
/
export.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
package filclient
import (
"context"
"fmt"
"os"
"github.com/ipfs/go-blockservice"
"github.com/ipfs/go-cid"
offline "github.com/ipfs/go-ipfs-exchange-offline"
files "github.com/ipfs/go-ipfs-files"
"github.com/ipfs/go-merkledag"
unixfile "github.com/ipfs/go-unixfs/file"
"github.com/ipld/go-car"
)
// Exports the provided CID to a file
// The content must already exist in the blockstore before calling this function
func (client *Client) ExportToFile(ctx context.Context, c cid.Cid, path string, exportAsCAR bool) error {
// Save output file
dservOffline := merkledag.NewDAGService(blockservice.New(client.bs, offline.Exchange(client.bs)))
dnode, err := dservOffline.Get(ctx, c)
if err != nil {
return err
}
if exportAsCAR {
// Write file as car file
file, err := os.Create(path)
if err != nil {
return err
}
car.WriteCar(ctx, dservOffline, []cid.Cid{c}, file)
fmt.Println("Saved .car output to", path)
} else {
// Otherwise write file as UnixFS File
ufsFile, err := unixfile.NewUnixfsFile(ctx, dservOffline, dnode)
if err != nil {
return err
}
if err := files.WriteTo(ufsFile, path); err != nil {
return err
}
fmt.Println("Saved output to", path)
}
return nil
}