utils.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "net/http"
  12. "os"
  13. "github.com/syncthing/syncthing/lib/config"
  14. "github.com/urfave/cli"
  15. )
  16. func responseToBArray(response *http.Response) ([]byte, error) {
  17. bytes, err := ioutil.ReadAll(response.Body)
  18. if err != nil {
  19. return nil, err
  20. }
  21. return bytes, response.Body.Close()
  22. }
  23. func emptyPost(url string) cli.ActionFunc {
  24. return func(c *cli.Context) error {
  25. client := c.App.Metadata["client"].(*APIClient)
  26. _, err := client.Post(url, "")
  27. return err
  28. }
  29. }
  30. func dumpOutput(url string) cli.ActionFunc {
  31. return func(c *cli.Context) error {
  32. client := c.App.Metadata["client"].(*APIClient)
  33. response, err := client.Get(url)
  34. if err != nil {
  35. return err
  36. }
  37. return prettyPrintResponse(c, response)
  38. }
  39. }
  40. func getConfig(c *APIClient) (config.Configuration, error) {
  41. cfg := config.Configuration{}
  42. response, err := c.Get("system/config")
  43. if err != nil {
  44. return cfg, err
  45. }
  46. bytes, err := responseToBArray(response)
  47. if err != nil {
  48. return cfg, err
  49. }
  50. err = json.Unmarshal(bytes, &cfg)
  51. if err == nil {
  52. return cfg, err
  53. }
  54. return cfg, nil
  55. }
  56. func expects(n int, actionFunc cli.ActionFunc) cli.ActionFunc {
  57. return func(ctx *cli.Context) error {
  58. if ctx.NArg() != n {
  59. plural := ""
  60. if n != 1 {
  61. plural = "s"
  62. }
  63. return fmt.Errorf("expected %d argument%s, got %d", n, plural, ctx.NArg())
  64. }
  65. return actionFunc(ctx)
  66. }
  67. }
  68. func prettyPrintJSON(data interface{}) error {
  69. enc := json.NewEncoder(os.Stdout)
  70. enc.SetIndent("", " ")
  71. return enc.Encode(data)
  72. }
  73. func prettyPrintResponse(c *cli.Context, response *http.Response) error {
  74. bytes, err := responseToBArray(response)
  75. if err != nil {
  76. return err
  77. }
  78. var data interface{}
  79. if err := json.Unmarshal(bytes, &data); err != nil {
  80. return err
  81. }
  82. // TODO: Check flag for pretty print format
  83. return prettyPrintJSON(data)
  84. }