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/couchbase/vellum/regexp" 22 "github.com/spf13/cobra" 23) 24 25var grepCmd = &cobra.Command{ 26 Use: "grep", 27 Short: "Grep runs regular expression searches over the contents of this " + 28 "vellum FST file.", 29 Long: `Grep runs regular expression searches over the contents of this ` + 30 `vellum FST file.`, 31 PreRunE: func(cmd *cobra.Command, args []string) error { 32 if len(args) < 1 { 33 return fmt.Errorf("path is required") 34 } 35 if len(args) > 1 { 36 query = args[1] 37 } 38 39 return nil 40 }, 41 RunE: func(cmd *cobra.Command, args []string) error { 42 fst, err := vellum.Open(args[0]) 43 if err != nil { 44 return err 45 } 46 r, err := regexp.New(query) 47 if err != nil { 48 return err 49 } 50 var startKeyB, endKeyB []byte 51 if startKey != "" { 52 startKeyB = []byte(startKey) 53 } 54 if endKey != "" { 55 endKeyB = []byte(endKey) 56 } 57 itr, err := fst.Search(r, startKeyB, endKeyB) 58 for err == nil { 59 key, val := itr.Current() 60 fmt.Printf("%s - %d\n", key, val) 61 err = itr.Next() 62 } 63 64 return nil 65 }, 66} 67 68func init() { 69 RootCmd.AddCommand(grepCmd) 70 grepCmd.Flags().StringVar(&startKey, "start", "", "start key inclusive") 71 grepCmd.Flags().StringVar(&endKey, "end", "", "end key inclusive") 72} 73