Skip to content

Commit

Permalink
add get block to car cli (#230)
Browse files Browse the repository at this point in the history
add `get block` to car cli for extracting an individual block by CID from a car
  • Loading branch information
willscott authored Sep 12, 2021
1 parent 4469377 commit 5390c33
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 18 deletions.
42 changes: 24 additions & 18 deletions v2/cmd/car/car.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@ func main() {
Name: "car",
Usage: "Utility for working with car files",
Commands: []*cli.Command{
{
Name: "detach-index",
Usage: "Detach an index to a detached file",
Action: DetachCar,
},
{
Name: "filter",
Aliases: []string{"f"},
Usage: "Filter the CIDs in a car",
Action: FilterCar,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "cid-file",
Usage: "A file to read CIDs from",
TakesFile: true,
},
},
},
{
Name: "get-block",
Aliases: []string{"gb"},
Usage: "Get a block out of a car",
Action: GetCarBlock,
},
{
Name: "index",
Aliases: []string{"i"},
Expand All @@ -27,30 +51,12 @@ func main() {
},
},
},
{
Name: "detach-index",
Usage: "Detach an index to a detached file",
Action: DetachCar,
},
{
Name: "list",
Aliases: []string{"l"},
Usage: "List the CIDs in a car",
Action: ListCar,
},
{
Name: "filter",
Aliases: []string{"f"},
Usage: "Filter the CIDs in a car",
Action: FilterCar,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "cid-file",
Usage: "A file to read CIDs from",
TakesFile: true,
},
},
},
},
}

Expand Down
45 changes: 45 additions & 0 deletions v2/cmd/car/get.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package main

import (
"fmt"
"os"

"github.com/ipfs/go-cid"
"github.com/ipld/go-car/v2/blockstore"
"github.com/urfave/cli/v2"
)

// GetCarBlock is a command to get a block out of a car
func GetCarBlock(c *cli.Context) error {
if c.Args().Len() < 2 {
return fmt.Errorf("usage: car get-block <file.car> <block cid> [output file]")
}

bs, err := blockstore.OpenReadOnly(c.Args().Get(0))
if err != nil {
return err
}

// string to CID
blkCid, err := cid.Parse(c.Args().Get(1))
if err != nil {
return err
}

blk, err := bs.Get(blkCid)
if err != nil {
return err
}

outStream := os.Stdout
if c.Args().Len() >= 3 {
outStream, err = os.Create(c.Args().Get(2))
if err != nil {
return err
}
defer outStream.Close()
}

_, err = outStream.Write(blk.RawData())
return err
}

0 comments on commit 5390c33

Please sign in to comment.