utils.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. "text/tabwriter"
  14. "github.com/syncthing/syncthing/lib/config"
  15. "github.com/urfave/cli"
  16. )
  17. func responseToBArray(response *http.Response) ([]byte, error) {
  18. bytes, err := ioutil.ReadAll(response.Body)
  19. if err != nil {
  20. return nil, err
  21. }
  22. return bytes, response.Body.Close()
  23. }
  24. func emptyPost(url string) cli.ActionFunc {
  25. return func(c *cli.Context) error {
  26. client := c.App.Metadata["client"].(*APIClient)
  27. _, err := client.Post(url, "")
  28. return err
  29. }
  30. }
  31. func dumpOutput(url string) cli.ActionFunc {
  32. return func(c *cli.Context) error {
  33. client := c.App.Metadata["client"].(*APIClient)
  34. response, err := client.Get(url)
  35. if err != nil {
  36. return err
  37. }
  38. return prettyPrintResponse(c, response)
  39. }
  40. }
  41. func newTableWriter() *tabwriter.Writer {
  42. writer := new(tabwriter.Writer)
  43. writer.Init(os.Stdout, 0, 8, 0, '\t', 0)
  44. return writer
  45. }
  46. func getConfig(c *APIClient) (config.Configuration, error) {
  47. cfg := config.Configuration{}
  48. response, err := c.Get("system/config")
  49. if err != nil {
  50. return cfg, err
  51. }
  52. bytes, err := responseToBArray(response)
  53. if err != nil {
  54. return cfg, err
  55. }
  56. err = json.Unmarshal(bytes, &cfg)
  57. if err == nil {
  58. return cfg, err
  59. }
  60. return cfg, nil
  61. }
  62. func expects(n int, actionFunc cli.ActionFunc) cli.ActionFunc {
  63. return func(ctx *cli.Context) error {
  64. if ctx.NArg() != n {
  65. plural := ""
  66. if n != 1 {
  67. plural = "s"
  68. }
  69. return fmt.Errorf("expected %d argument%s, got %d", n, plural, ctx.NArg())
  70. }
  71. return actionFunc(ctx)
  72. }
  73. }
  74. func prettyPrintJSON(data interface{}) error {
  75. enc := json.NewEncoder(os.Stdout)
  76. enc.SetIndent("", " ")
  77. return enc.Encode(data)
  78. }
  79. func prettyPrintResponse(c *cli.Context, response *http.Response) error {
  80. bytes, err := responseToBArray(response)
  81. if err != nil {
  82. return err
  83. }
  84. var data interface{}
  85. if err := json.Unmarshal(bytes, &data); err != nil {
  86. return err
  87. }
  88. // TODO: Check flag for pretty print format
  89. return prettyPrintJSON(data)
  90. }