Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add get block to car cli #230

Merged
merged 4 commits into from
Sep 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}