protofmt.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. in.Close()
  34. out.Close()
  35. if err := os.Rename(file+".tmp", file); err != nil {
  36. log.Fatal(err)
  37. }
  38. }
  39. func formatProto(in io.Reader, out io.Writer) error {
  40. sc := bufio.NewScanner(in)
  41. lineExp := regexp.MustCompile(`([^=]+)\s+([^=\s]+?)\s*=(.+)`)
  42. var tw *tabwriter.Writer
  43. for sc.Scan() {
  44. line := sc.Text()
  45. if strings.HasPrefix(line, "//") {
  46. if _, err := fmt.Fprintln(out, line); err != nil {
  47. return err
  48. }
  49. continue
  50. }
  51. ms := lineExp.FindStringSubmatch(line)
  52. for i := range ms {
  53. ms[i] = strings.TrimSpace(ms[i])
  54. }
  55. if len(ms) == 4 && ms[1] != "option" {
  56. typ := strings.Join(strings.Fields(ms[1]), " ")
  57. name := ms[2]
  58. id := ms[3]
  59. if tw == nil {
  60. tw = tabwriter.NewWriter(out, 4, 4, 1, ' ', 0)
  61. }
  62. if typ == "" {
  63. // We're in an enum
  64. fmt.Fprintf(tw, "\t%s\t= %s\n", name, id)
  65. } else {
  66. // Message
  67. fmt.Fprintf(tw, "\t%s\t%s\t= %s\n", typ, name, id)
  68. }
  69. } else {
  70. if tw != nil {
  71. if err := tw.Flush(); err != nil {
  72. return err
  73. }
  74. tw = nil
  75. }
  76. if _, err := fmt.Fprintln(out, line); err != nil {
  77. return err
  78. }
  79. }
  80. }
  81. return nil
  82. }