util.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package command
  14. import (
  15. "errors"
  16. "io"
  17. "io/ioutil"
  18. "net/url"
  19. "os"
  20. "strings"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  22. )
  23. var (
  24. ErrNoAvailSrc = errors.New("no available argument and stdin")
  25. )
  26. // trimsplit slices s into all substrings separated by sep and returns a
  27. // slice of the substrings between the separator with all leading and trailing
  28. // white space removed, as defined by Unicode.
  29. func trimsplit(s, sep string) []string {
  30. raw := strings.Split(s, ",")
  31. trimmed := make([]string, 0)
  32. for _, r := range raw {
  33. trimmed = append(trimmed, strings.TrimSpace(r))
  34. }
  35. return trimmed
  36. }
  37. func argOrStdin(args []string, stdin io.Reader, i int) (string, error) {
  38. if i < len(args) {
  39. return args[i], nil
  40. }
  41. bytes, err := ioutil.ReadAll(stdin)
  42. if string(bytes) == "" || err != nil {
  43. return "", ErrNoAvailSrc
  44. }
  45. return string(bytes), nil
  46. }
  47. func maybeAddScheme(maybeAddr string) (string, error) {
  48. u, err := url.Parse(maybeAddr)
  49. if err != nil {
  50. return "", err
  51. }
  52. if u.Scheme == "" {
  53. u.Scheme = "http"
  54. }
  55. return u.String(), nil
  56. }
  57. func getPeersFlagValue(c *cli.Context) []string {
  58. peerstr := c.GlobalString("peers")
  59. // Use an environment variable if nothing was supplied on the
  60. // command line
  61. if peerstr == "" {
  62. peerstr = os.Getenv("ETCDCTL_PEERS")
  63. }
  64. // If we still don't have peers, use a default
  65. if peerstr == "" {
  66. peerstr = "127.0.0.1:4001"
  67. }
  68. return strings.Split(peerstr, ",")
  69. }
  70. func getEndpoints(c *cli.Context) ([]string, error) {
  71. eps := getPeersFlagValue(c)
  72. var err error
  73. for i, ep := range eps {
  74. eps[i], err = maybeAddScheme(ep)
  75. if err != nil {
  76. return nil, err
  77. }
  78. }
  79. return eps, nil
  80. }