utils.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // Copyright (C) 2014 Audrius Butkevičius
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "regexp"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "text/tabwriter"
  14. "unicode"
  15. "github.com/AudriusButkevicius/cli"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. )
  19. func responseToBArray(response *http.Response) []byte {
  20. defer response.Body.Close()
  21. bytes, err := ioutil.ReadAll(response.Body)
  22. if err != nil {
  23. die(err)
  24. }
  25. return bytes
  26. }
  27. func die(vals ...interface{}) {
  28. if len(vals) > 1 || vals[0] != nil {
  29. os.Stderr.WriteString(fmt.Sprintln(vals...))
  30. os.Exit(1)
  31. }
  32. }
  33. func wrappedHTTPPost(url string) func(c *cli.Context) {
  34. return func(c *cli.Context) {
  35. httpPost(c, url, "")
  36. }
  37. }
  38. func prettyPrintJSON(json map[string]interface{}) {
  39. writer := newTableWriter()
  40. remap := make(map[string]interface{})
  41. for k, v := range json {
  42. key, ok := jsonAttributeLabels[k]
  43. if !ok {
  44. key = firstUpper(k)
  45. }
  46. remap[key] = v
  47. }
  48. jsonKeys := make([]string, 0, len(remap))
  49. for key := range remap {
  50. jsonKeys = append(jsonKeys, key)
  51. }
  52. sort.Strings(jsonKeys)
  53. for _, k := range jsonKeys {
  54. var value string
  55. rvalue := remap[k]
  56. switch rvalue.(type) {
  57. case int, int16, int32, int64, uint, uint16, uint32, uint64, float32, float64:
  58. value = fmt.Sprintf("%.0f", rvalue)
  59. default:
  60. value = fmt.Sprint(rvalue)
  61. }
  62. if value == "" {
  63. continue
  64. }
  65. fmt.Fprintln(writer, k+":\t"+value)
  66. }
  67. writer.Flush()
  68. }
  69. func firstUpper(str string) string {
  70. for i, v := range str {
  71. return string(unicode.ToUpper(v)) + str[i+1:]
  72. }
  73. return ""
  74. }
  75. func newTableWriter() *tabwriter.Writer {
  76. writer := new(tabwriter.Writer)
  77. writer.Init(os.Stdout, 0, 8, 0, '\t', 0)
  78. return writer
  79. }
  80. func getMyID(c *cli.Context) string {
  81. response := httpGet(c, "system/status")
  82. data := make(map[string]interface{})
  83. json.Unmarshal(responseToBArray(response), &data)
  84. return data["myID"].(string)
  85. }
  86. func getConfig(c *cli.Context) config.Configuration {
  87. response := httpGet(c, "system/config")
  88. config := config.Configuration{}
  89. json.Unmarshal(responseToBArray(response), &config)
  90. return config
  91. }
  92. func setConfig(c *cli.Context, cfg config.Configuration) {
  93. body, err := json.Marshal(cfg)
  94. die(err)
  95. response := httpPost(c, "system/config", string(body))
  96. if response.StatusCode != 200 {
  97. die("Unexpected status code", response.StatusCode)
  98. }
  99. }
  100. func parseBool(input string) bool {
  101. val, err := strconv.ParseBool(input)
  102. if err != nil {
  103. die(input + " is not a valid value for a boolean")
  104. }
  105. return val
  106. }
  107. func parseInt(input string) int {
  108. val, err := strconv.ParseInt(input, 0, 64)
  109. if err != nil {
  110. die(input + " is not a valid value for an integer")
  111. }
  112. return int(val)
  113. }
  114. func parseUint(input string) int {
  115. val, err := strconv.ParseUint(input, 0, 64)
  116. if err != nil {
  117. die(input + " is not a valid value for an unsigned integer")
  118. }
  119. return int(val)
  120. }
  121. func parsePort(input string) int {
  122. port := parseUint(input)
  123. if port < 1 || port > 65535 {
  124. die(input + " is not a valid port\nExpected value between 1 and 65535")
  125. }
  126. return port
  127. }
  128. func validAddress(input string) {
  129. tokens := strings.Split(input, ":")
  130. if len(tokens) != 2 {
  131. die(input + " is not a valid value for an address\nExpected format <ip or hostname>:<port>")
  132. }
  133. matched, err := regexp.MatchString("^[a-zA-Z0-9]+([-a-zA-Z0-9.]+[-a-zA-Z0-9]+)?$", tokens[0])
  134. die(err)
  135. if !matched {
  136. die(input + " is not a valid value for an address\nExpected format <ip or hostname>:<port>")
  137. }
  138. parsePort(tokens[1])
  139. }
  140. func parseDeviceID(input string) protocol.DeviceID {
  141. device, err := protocol.DeviceIDFromString(input)
  142. if err != nil {
  143. die(input + " is not a valid device id")
  144. }
  145. return device
  146. }