diff --git a/ipld/car/cmd/car/car.go b/ipld/car/cmd/car/car.go index c66232f7d..70c9eb32a 100644 --- a/ipld/car/cmd/car/car.go +++ b/ipld/car/cmd/car/car.go @@ -153,6 +153,11 @@ func main1() int { Usage: "Write output as a v1 or v2 format car", }, }, + Subcommands: []*cli.Command{{ + Name: "create", + Usage: "Write out a detached index", + Action: CreateIndex, + }}, }, { Name: "inspect", diff --git a/ipld/car/cmd/car/index.go b/ipld/car/cmd/car/index.go index 031df2ada..fc6bd5d61 100644 --- a/ipld/car/cmd/car/index.go +++ b/ipld/car/cmd/car/index.go @@ -166,3 +166,45 @@ func IndexCar(c *cli.Context) error { _, err = index.WriteTo(idx, outStream) return err } + +// CreateIndex is a command to write out an index of the CAR file +func CreateIndex(c *cli.Context) error { + r, err := carv2.OpenReader(c.Args().Get(0)) + if err != nil { + return err + } + defer r.Close() + + outStream := os.Stdout + if c.Args().Len() >= 2 { + outStream, err = os.Create(c.Args().Get(1)) + if err != nil { + return err + } + } + defer outStream.Close() + + var mc multicodec.Code + if err := mc.Set(c.String("codec")); err != nil { + return err + } + idx, err := index.New(mc) + if err != nil { + return err + } + + dr, err := r.DataReader() + if err != nil { + return err + } + + if err := carv2.LoadIndex(idx, dr); err != nil { + return err + } + + if _, err := index.WriteTo(idx, outStream); err != nil { + return err + } + + return nil +} diff --git a/ipld/car/cmd/car/testdata/script/index-create.txt b/ipld/car/cmd/car/testdata/script/index-create.txt new file mode 100644 index 000000000..bfdfe65c1 --- /dev/null +++ b/ipld/car/cmd/car/testdata/script/index-create.txt @@ -0,0 +1,3 @@ +car index create ${INPUTS}/sample-v1.car sample-v1.car.idx +car detach-index ${INPUTS}/sample-wrapped-v2.car sample-wrapped-v2.car.idx +cmp sample-v1.car.idx sample-wrapped-v2.car.idx