File: protofmt.go

package info (click to toggle)
syncthing 0.14.18%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 7,388 kB
  • ctags: 4,608
  • sloc: xml: 781; sh: 271; makefile: 45
file content (90 lines) | stat: -rw-r--r-- 1,749 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Copyright (C) 2016 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.

// +build ignore

package main

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"regexp"
	"strings"
	"text/tabwriter"
)

func main() {
	flag.Parse()
	file := flag.Arg(0)
	in, err := os.Open(file)
	if err != nil {
		log.Fatal(err)
	}
	out, err := os.Create(file + ".tmp")
	if err != nil {
		log.Fatal(err)
	}

	if err := formatProto(in, out); err != nil {
		log.Fatal(err)
	}
	in.Close()
	out.Close()
	if err := os.Rename(file+".tmp", file); err != nil {
		log.Fatal(err)
	}
}

func formatProto(in io.Reader, out io.Writer) error {
	sc := bufio.NewScanner(in)
	lineExp := regexp.MustCompile(`([^=]+)\s+([^=\s]+?)\s*=(.+)`)
	var tw *tabwriter.Writer
	for sc.Scan() {
		line := sc.Text()
		if strings.HasPrefix(line, "//") {
			if _, err := fmt.Fprintln(out, line); err != nil {
				return err
			}
			continue
		}

		ms := lineExp.FindStringSubmatch(line)
		for i := range ms {
			ms[i] = strings.TrimSpace(ms[i])
		}
		if len(ms) == 4 && ms[1] != "option" {
			typ := strings.Join(strings.Fields(ms[1]), " ")
			name := ms[2]
			id := ms[3]
			if tw == nil {
				tw = tabwriter.NewWriter(out, 4, 4, 1, ' ', 0)
			}
			if typ == "" {
				// We're in an enum
				fmt.Fprintf(tw, "\t%s\t= %s\n", name, id)
			} else {
				// Message
				fmt.Fprintf(tw, "\t%s\t%s\t= %s\n", typ, name, id)
			}
		} else {
			if tw != nil {
				if err := tw.Flush(); err != nil {
					return err
				}
				tw = nil
			}
			if _, err := fmt.Fprintln(out, line); err != nil {
				return err
			}
		}
	}

	return nil
}