util.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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, valueOnly 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. if !valueOnly {
  30. fmt.Println(k)
  31. }
  32. fmt.Println(v)
  33. }
  34. func addHexPrefix(s string) string {
  35. ns := make([]byte, len(s)*2)
  36. for i := 0; i < len(s); i += 2 {
  37. ns[i*2] = '\\'
  38. ns[i*2+1] = 'x'
  39. ns[i*2+2] = s[i]
  40. ns[i*2+3] = s[i+1]
  41. }
  42. return string(ns)
  43. }
  44. func argify(s string) []string {
  45. r := regexp.MustCompile(`"(?:[^"\\]|\\.)*"|'[^']*'|[^'"\s]\S*[^'"\s]?`)
  46. args := r.FindAllString(s, -1)
  47. for i := range args {
  48. if len(args[i]) == 0 {
  49. continue
  50. }
  51. if args[i][0] == '\'' {
  52. // 'single-quoted string'
  53. args[i] = args[i][1 : len(args)-1]
  54. } else if args[i][0] == '"' {
  55. // "double quoted string"
  56. if _, err := fmt.Sscanf(args[i], "%q", &args[i]); err != nil {
  57. ExitWithError(ExitInvalidInput, err)
  58. }
  59. }
  60. }
  61. return args
  62. }
  63. func commandCtx(cmd *cobra.Command) (context.Context, context.CancelFunc) {
  64. timeOut, err := cmd.Flags().GetDuration("command-timeout")
  65. if err != nil {
  66. ExitWithError(ExitError, err)
  67. }
  68. return context.WithTimeout(context.Background(), timeOut)
  69. }