util.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. package command
  15. import (
  16. "encoding/hex"
  17. "fmt"
  18. "regexp"
  19. pb "github.com/coreos/etcd/mvcc/mvccpb"
  20. "github.com/spf13/cobra"
  21. "golang.org/x/net/context"
  22. )
  23. func printKV(isHex bool, kv *pb.KeyValue) {
  24. k, v := string(kv.Key), string(kv.Value)
  25. if isHex {
  26. k = addHexPrefix(hex.EncodeToString(kv.Key))
  27. v = addHexPrefix(hex.EncodeToString(kv.Value))
  28. }
  29. fmt.Println(k)
  30. fmt.Println(v)
  31. }
  32. func addHexPrefix(s string) string {
  33. ns := make([]byte, len(s)*2)
  34. for i := 0; i < len(s); i += 2 {
  35. ns[i*2] = '\\'
  36. ns[i*2+1] = 'x'
  37. ns[i*2+2] = s[i]
  38. ns[i*2+3] = s[i+1]
  39. }
  40. return string(ns)
  41. }
  42. func argify(s string) []string {
  43. r := regexp.MustCompile("'.+'|\".+\"|\\S+")
  44. return r.FindAllString(s, -1)
  45. }
  46. func commandCtx(cmd *cobra.Command) (context.Context, context.CancelFunc) {
  47. timeOut, err := cmd.Flags().GetDuration("command-timeout")
  48. if err != nil {
  49. ExitWithError(ExitError, err)
  50. }
  51. return context.WithTimeout(context.Background(), timeOut)
  52. }