usage.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright (C) 2014 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 http://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "bytes"
  9. "flag"
  10. "fmt"
  11. "io"
  12. "text/tabwriter"
  13. )
  14. func optionTable(w io.Writer, rows [][]string) {
  15. tw := tabwriter.NewWriter(w, 2, 4, 2, ' ', 0)
  16. for _, row := range rows {
  17. for i, cell := range row {
  18. if i > 0 {
  19. tw.Write([]byte("\t"))
  20. }
  21. tw.Write([]byte(cell))
  22. }
  23. tw.Write([]byte("\n"))
  24. }
  25. tw.Flush()
  26. }
  27. func usageFor(fs *flag.FlagSet, usage string, extra string) func() {
  28. return func() {
  29. var b bytes.Buffer
  30. b.WriteString("Usage:\n " + usage + "\n")
  31. var options [][]string
  32. fs.VisitAll(func(f *flag.Flag) {
  33. var opt = " -" + f.Name
  34. if f.DefValue != "false" {
  35. opt += "=" + fmt.Sprintf(`"%s"`, f.DefValue)
  36. }
  37. options = append(options, []string{opt, f.Usage})
  38. })
  39. if len(options) > 0 {
  40. b.WriteString("\nOptions:\n")
  41. optionTable(&b, options)
  42. }
  43. fmt.Println(b.String())
  44. if len(extra) > 0 {
  45. fmt.Println(extra)
  46. }
  47. }
  48. }