-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoalign.go
163 lines (152 loc) · 3.83 KB
/
goalign.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package main
import (
"bytes"
"flag"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
var write = flag.Bool("w", false, "Overwrite the existing files.")
func main() {
if err := alignMain(); err != nil {
os.Stderr.WriteString(errors.Wrap(err, "unable to align file").Error())
os.Exit(1)
}
os.Exit(0)
}
func alignMain() error {
flag.Parse()
filename := flag.Arg(0)
return walk(filename, *write)
}
func walk(filename string, write bool) error {
directory, basename := path.Split(filename)
var root string
if directory != "" && basename == "..." {
root = directory
} else if directory == "" && basename == "." {
root = "."
} else {
root = filename
}
var dst io.Writer
if !write {
dst = os.Stdout
}
return filepath.Walk(root, getWalker(dst))
}
func getWalker(dst io.Writer) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
// Ignore errors, directories and non-Go files.
if err != nil || info.IsDir() || !strings.HasSuffix(info.Name(), ".go") {
return nil
}
file, err := os.OpenFile(path, os.O_RDWR, info.Mode())
src, err := ioutil.ReadAll(file)
if err != nil {
return err
}
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, path, src, parser.ParseComments)
for _, decl := range astFile.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
structType, ok := typeSpec.Type.(*ast.StructType)
// TODO: Figure out how fields can be empty.
if !ok || structType.Fields == nil {
continue
}
alignFieldTags(structType.Fields.List)
}
}
// Print the modified file.
if dst == nil {
// Seek to the beginning so that we can write it again later.
if _, err := file.Seek(0, 0); err != nil {
return err
}
dst = file
}
return format.Node(dst, fileSet, astFile)
}
}
func alignFieldTags(fields []*ast.Field) error {
encounteredTags := make([]string, 0)
maxTagLengths := make(map[string]int)
fieldTagNamesToValues := make([]map[string]string, len(fields))
fieldNumTags := make([]int, len(fields))
// Iterate once through to find all the max values.
for i, field := range fields {
if field.Tag == nil {
continue
}
tags := strings.Fields(strings.Trim(field.Tag.Value, "`"))
namesToValues := make(map[string]string)
for _, tag := range tags {
tagName := strings.SplitN(tag, ":", 2)[0]
namesToValues[tagName] = tag
if _, ok := maxTagLengths[tagName]; !ok {
encounteredTags = append(encounteredTags, tagName)
}
prevMax, ok := maxTagLengths[tagName]
if !ok {
maxTagLengths[tagName] = len(tag)
} else if prevMax < len(tag) {
maxTagLengths[tagName] = len(tag)
}
}
fieldTagNamesToValues[i] = namesToValues
fieldNumTags[i] = len(tags)
}
// Pad all the strings according to the max values.
for i, field := range fields {
if field.Tag == nil {
continue
}
// Keep track of the visited number of tags in order to bail early.
visitedTags := 0
tagBuffer := bytes.NewBufferString("`")
for _, key := range encounteredTags {
val, ok := fieldTagNamesToValues[i][key]
if ok {
visitedTags += 1
}
numSpaces := maxTagLengths[key] - len(val)
if _, err := tagBuffer.WriteString(val); err != nil {
return err
}
// Bail early since we don't need to print anymore whitespace.
if visitedTags >= fieldNumTags[i] {
break
}
// Pad the tag.
for i := 0; i < numSpaces; i++ {
if _, err := tagBuffer.WriteString(" "); err != nil {
return err
}
}
// Add space between each tag.
if _, err := tagBuffer.WriteString(" "); err != nil {
return err
}
}
tagBuffer.WriteString("`")
field.Tag.Value = tagBuffer.String()
}
return nil
}