-
Notifications
You must be signed in to change notification settings - Fork 44
/
detach.go
73 lines (62 loc) · 1.35 KB
/
detach.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
package main
import (
"fmt"
"io"
"os"
carv2 "github.com/ipld/go-car/v2"
"github.com/ipld/go-car/v2/index"
"github.com/multiformats/go-multihash"
"github.com/urfave/cli/v2"
)
// DetachCar is a command to output the index part of a car.
func DetachCar(c *cli.Context) error {
r, err := carv2.OpenReader(c.Args().Get(0))
if err != nil {
return err
}
defer r.Close()
if !r.Header.HasIndex() {
return fmt.Errorf("no index present")
}
outStream := os.Stdout
if c.Args().Len() >= 2 {
outStream, err = os.Create(c.Args().Get(1))
if err != nil {
return err
}
}
defer outStream.Close()
ir, err := r.IndexReader()
if err != nil {
return err
}
_, err = io.Copy(outStream, ir)
return err
}
// DetachCarList prints a list of what's found in a detached index.
func DetachCarList(c *cli.Context) error {
var err error
inStream := os.Stdin
if c.Args().Len() >= 1 {
inStream, err = os.Open(c.Args().First())
if err != nil {
return err
}
defer inStream.Close()
}
idx, err := index.ReadFrom(inStream)
if err != nil {
return err
}
if iidx, ok := idx.(index.IterableIndex); ok {
err := iidx.ForEach(func(mh multihash.Multihash, offset uint64) error {
fmt.Printf("%s %d\n", mh, offset)
return nil
})
if err != nil {
return err
}
return nil
}
return fmt.Errorf("index of codec %s is not iterable", idx.Codec())
}