From 25dacb34be1d950462e52d338ad1ef157cddd6e1 Mon Sep 17 00:00:00 2001 From: Mustafa Elbehery Date: Mon, 29 Jan 2024 20:18:55 +0100 Subject: [PATCH] fix cli cmds panics Signed-off-by: Mustafa Elbehery --- cmd/bbolt/main.go | 9 +++++++++ cmd/bbolt/main_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/cmd/bbolt/main.go b/cmd/bbolt/main.go index f76cd82c4..5bc0161e2 100644 --- a/cmd/bbolt/main.go +++ b/cmd/bbolt/main.go @@ -60,6 +60,9 @@ var ( // ErrKeyNotFound is returned when a key is not found. ErrKeyNotFound = errors.New("key not found") + + // ErrNotEnoughArgs is returned with a cmd is being executed with fewer arguments. + ErrNotEnoughArgs = errors.New("not enough arguments") ) func main() { @@ -908,6 +911,9 @@ func (cmd *keysCommand) Run(args ...string) error { // Require database path and bucket. relevantArgs := fs.Args() + if len(relevantArgs) < 2 { + return ErrNotEnoughArgs + } path, buckets := relevantArgs[0], relevantArgs[1:] if path == "" { return ErrPathRequired @@ -993,6 +999,9 @@ func (cmd *getCommand) Run(args ...string) error { // Require database path, bucket and key. relevantArgs := fs.Args() + if len(relevantArgs) < 3 { + return ErrNotEnoughArgs + } path, buckets := relevantArgs[0], relevantArgs[1:len(relevantArgs)-1] key, err := parseBytes(relevantArgs[len(relevantArgs)-1], parseFormat) if err != nil { diff --git a/cmd/bbolt/main_test.go b/cmd/bbolt/main_test.go index 7d0cfd249..d43c03619 100644 --- a/cmd/bbolt/main_test.go +++ b/cmd/bbolt/main_test.go @@ -397,6 +397,33 @@ func TestCompactCommand_Run(t *testing.T) { } } +func TestCommands_Run_NoArgs(t *testing.T) { + testCases := []struct { + name string + cmd string + expErr error + }{ + { + name: "get", + cmd: "get", + expErr: main.ErrNotEnoughArgs, + }, + { + name: "keys", + cmd: "keys", + expErr: main.ErrNotEnoughArgs, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + m := NewMain() + err := m.Run(tc.cmd) + require.ErrorIs(t, err, main.ErrNotEnoughArgs) + }) + } +} + func fillBucket(b *bolt.Bucket, prefix []byte) error { n := 10 + rand.Intn(50) for i := 0; i < n; i++ {