go.etcd.io/etcd@v3.3.27+incompatible/etcdctl/ctlv3/command/util.go (about) 1 // Copyright 2015 The etcd Authors 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 15 package command 16 17 import ( 18 "context" 19 "encoding/hex" 20 "fmt" 21 "regexp" 22 23 pb "github.com/coreos/etcd/mvcc/mvccpb" 24 25 "github.com/spf13/cobra" 26 ) 27 28 func printKV(isHex bool, valueOnly bool, kv *pb.KeyValue) { 29 k, v := string(kv.Key), string(kv.Value) 30 if isHex { 31 k = addHexPrefix(hex.EncodeToString(kv.Key)) 32 v = addHexPrefix(hex.EncodeToString(kv.Value)) 33 } 34 if !valueOnly { 35 fmt.Println(k) 36 } 37 fmt.Println(v) 38 } 39 40 func addHexPrefix(s string) string { 41 ns := make([]byte, len(s)*2) 42 for i := 0; i < len(s); i += 2 { 43 ns[i*2] = '\\' 44 ns[i*2+1] = 'x' 45 ns[i*2+2] = s[i] 46 ns[i*2+3] = s[i+1] 47 } 48 return string(ns) 49 } 50 51 func argify(s string) []string { 52 r := regexp.MustCompile(`"(?:[^"\\]|\\.)*"|'[^']*'|[^'"\s]\S*[^'"\s]?`) 53 args := r.FindAllString(s, -1) 54 for i := range args { 55 if len(args[i]) == 0 { 56 continue 57 } 58 if args[i][0] == '\'' { 59 // 'single-quoted string' 60 args[i] = args[i][1 : len(args)-1] 61 } else if args[i][0] == '"' { 62 // "double quoted string" 63 if _, err := fmt.Sscanf(args[i], "%q", &args[i]); err != nil { 64 ExitWithError(ExitInvalidInput, err) 65 } 66 } 67 } 68 return args 69 } 70 71 func commandCtx(cmd *cobra.Command) (context.Context, context.CancelFunc) { 72 timeOut, err := cmd.Flags().GetDuration("command-timeout") 73 if err != nil { 74 ExitWithError(ExitError, err) 75 } 76 return context.WithTimeout(context.Background(), timeOut) 77 }