1//  Copyright (c) 2017 Couchbase, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// 		http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package cmd
16
17import (
18	"fmt"
19
20	"github.com/couchbase/vellum"
21	"github.com/spf13/cobra"
22)
23
24var startKey string
25var endKey string
26
27var rangeCmd = &cobra.Command{
28	Use:   "range",
29	Short: "Range iterates over the contents of this vellum FST file",
30	Long:  `Range iterates over the contents of this vellum FST file.  You can optionally specify start/end keys after the filename.`,
31	PreRunE: func(cmd *cobra.Command, args []string) error {
32		if len(args) < 1 {
33			return fmt.Errorf("path is required")
34		}
35		return nil
36	},
37	RunE: func(cmd *cobra.Command, args []string) error {
38		fst, err := vellum.Open(args[0])
39		if err != nil {
40			return err
41		}
42		var startKeyB, endKeyB []byte
43		if startKey != "" {
44			startKeyB = []byte(startKey)
45		}
46		if endKey != "" {
47			endKeyB = []byte(endKey)
48		}
49		itr, err := fst.Iterator(startKeyB, endKeyB)
50		for err == nil {
51			key, val := itr.Current()
52			fmt.Printf("%s - %d\n", key, val)
53			err = itr.Next()
54		}
55
56		return nil
57	},
58}
59
60func init() {
61	RootCmd.AddCommand(rangeCmd)
62	rangeCmd.Flags().StringVar(&startKey, "start", "", "start key inclusive")
63	rangeCmd.Flags().StringVar(&endKey, "end", "", "end key inclusive")
64}
65