forked from pachyderm/pachyderm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protofix.go
108 lines (86 loc) · 2.04 KB
/
protofix.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package protofix
import (
"bufio"
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
)
func FixAllPBGOFilesInDirectory(rootPath string) {
filepath.Walk(rootPath, func(path string, f os.FileInfo, err error) error {
if strings.HasSuffix(f.Name(), ".pb.go") {
fmt.Printf("Repairing %v\n", path)
repairFile(path)
}
return nil
})
}
func RevertAllPBGOFilesInDirectory(rootPath string) {
filepath.Walk(rootPath, func(path string, f os.FileInfo, err error) error {
if f == nil {
return nil
}
if strings.HasSuffix(f.Name(), ".pb.go") {
fmt.Printf("Reverting %v\n", path)
args := []string{"checkout", path}
_, err := exec.Command("git", args...).Output()
if err != nil {
fmt.Printf("Error reverting %v : %v\n", path, err)
os.Exit(1)
}
}
return nil
})
}
func repairedFileBytes(filename string) []byte {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
fmt.Println(err)
return nil
}
n := &walker{}
ast.Walk(n, f)
var buf bytes.Buffer
config := &printer.Config{Mode: printer.UseSpaces + printer.TabIndent, Tabwidth: 8, Indent: 0}
config.Fprint(&buf, fset, f)
scanner := bufio.NewScanner(&buf)
var out bytes.Buffer
for scanner.Scan() {
// this is retarded
line := scanner.Text()
if !strings.Contains(line, "grpc.SupportPackageIsVersion1") {
out.WriteString(line + "\n")
}
}
return out.Bytes()
}
func repairFile(filename string) {
newFileContents := repairedFileBytes(filename)
ioutil.WriteFile(filename, newFileContents, 0644)
}
func repairDeclaration(node ast.Node) {
switch node := node.(type) {
case *ast.Field:
if len(node.Names) > 0 {
declName := node.Names[0].Name
if strings.HasSuffix(declName, "Id") {
normalized := strings.TrimSuffix(declName, "Id")
node.Names[0] = ast.NewIdent(fmt.Sprintf("%vID", normalized))
}
}
}
}
type walker struct {
}
func (w *walker) Visit(node ast.Node) ast.Visitor {
repairDeclaration(node)
return w
}