protofmt.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright (C) 2016 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. // +build ignore
  7. package main
  8. import (
  9. "bufio"
  10. "flag"
  11. "fmt"
  12. "io"
  13. "log"
  14. "os"
  15. "regexp"
  16. "strings"
  17. "text/tabwriter"
  18. )
  19. func main() {
  20. flag.Parse()
  21. file := flag.Arg(0)
  22. in, err := os.Open(file)
  23. if err != nil {
  24. log.Fatal(err)
  25. }
  26. out, err := os.Create(file + ".tmp")
  27. if err != nil {
  28. log.Fatal(err)
  29. }
  30. if err := formatProto(in, out); err != nil {
  31. log.Fatal(err)
  32. }
  33. if err := os.Rename(file+".tmp", file); err != nil {
  34. log.Fatal(err)
  35. }
  36. }
  37. func formatProto(in io.Reader, out io.Writer) error {
  38. sc := bufio.NewScanner(in)
  39. lineExp := regexp.MustCompile(`([^=]+)\s+([^=\s]+?)\s*=(.+)`)
  40. var tw *tabwriter.Writer
  41. for sc.Scan() {
  42. line := sc.Text()
  43. if strings.HasPrefix(line, "//") {
  44. if _, err := fmt.Fprintln(out, line); err != nil {
  45. return err
  46. }
  47. continue
  48. }
  49. ms := lineExp.FindStringSubmatch(line)
  50. for i := range ms {
  51. ms[i] = strings.TrimSpace(ms[i])
  52. }
  53. if len(ms) == 4 && ms[1] != "option" {
  54. typ := strings.Join(strings.Fields(ms[1]), " ")
  55. name := ms[2]
  56. id := ms[3]
  57. if tw == nil {
  58. tw = tabwriter.NewWriter(out, 4, 4, 1, ' ', 0)
  59. }
  60. if typ == "" {
  61. // We're in an enum
  62. fmt.Fprintf(tw, "\t%s\t= %s\n", name, id)
  63. } else {
  64. // Message
  65. fmt.Fprintf(tw, "\t%s\t%s\t= %s\n", typ, name, id)
  66. }
  67. } else {
  68. if tw != nil {
  69. if err := tw.Flush(); err != nil {
  70. return err
  71. }
  72. tw = nil
  73. }
  74. if _, err := fmt.Fprintln(out, line); err != nil {
  75. return err
  76. }
  77. }
  78. }
  79. return nil
  80. }