From 845a4d47ce37cfe51e285e78430aa363dbbf1a59 Mon Sep 17 00:00:00 2001 From: Ben Johnson Date: Fri, 21 Mar 2014 22:56:17 -0600 Subject: [PATCH] Add 'bolt buckets'. --- cmd/bolt/main.go | 32 ++++++++++++++++++++++++++++++++ cmd/bolt/main_test.go | 22 ++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/cmd/bolt/main.go b/cmd/bolt/main.go index 387ffa4..cfb9765 100644 --- a/cmd/bolt/main.go +++ b/cmd/bolt/main.go @@ -36,6 +36,11 @@ func NewApp() *cli.App { Usage: "Retrieve a list of all keys in a bucket", Action: KeysCommand, }, + { + Name: "buckets", + Usage: "Retrieves a list of all buckets", + Action: BucketsCommand, + }, { Name: "pages", Usage: "Dumps page information for a database", @@ -151,6 +156,33 @@ func KeysCommand(c *cli.Context) { } } +// BucketsCommand retrieves a list of all buckets. +func BucketsCommand(c *cli.Context) { + path := c.Args().Get(0) + if _, err := os.Stat(path); os.IsNotExist(err) { + fatal(err) + return + } + + db, err := bolt.Open(path, 0600) + if err != nil { + fatal(err) + return + } + defer db.Close() + + err = db.With(func(tx *bolt.Tx) error { + for _, b := range tx.Buckets() { + logger.Println(b.Name()) + } + return nil + }) + if err != nil { + fatal(err) + return + } +} + // PagesCommand prints a list of all pages in a database. func PagesCommand(c *cli.Context) { path := c.Args().Get(0) diff --git a/cmd/bolt/main_test.go b/cmd/bolt/main_test.go index 1884dfa..b755ccd 100644 --- a/cmd/bolt/main_test.go +++ b/cmd/bolt/main_test.go @@ -114,6 +114,28 @@ func TestKeysBucketNotFound(t *testing.T) { }) } +// Ensure that a list of buckets can be retrieved. +func TestBuckets(t *testing.T) { + SetTestMode(true) + open(func(db *bolt.DB) { + db.Do(func(tx *bolt.Tx) error { + tx.CreateBucket("woojits") + tx.CreateBucket("widgets") + tx.CreateBucket("whatchits") + return nil + }) + output := run("buckets", db.Path()) + assert.Equal(t, "whatchits\nwidgets\nwoojits", output) + }) +} + +// Ensure that an error is reported if the database is not found. +func TestBucketsDBNotFound(t *testing.T) { + SetTestMode(true) + output := run("buckets", "no/such/db") + assert.Equal(t, "stat no/such/db: no such file or directory", output) +} + // open creates and opens a Bolt database in the temp directory. func open(fn func(*bolt.DB)) { f, _ := ioutil.TempFile("", "bolt-")