-
Notifications
You must be signed in to change notification settings - Fork 60
/
shortener.go
633 lines (557 loc) · 15.9 KB
/
shortener.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
package main
import (
"bufio"
"bytes"
"fmt"
"go/format"
"go/token"
"os"
"os/exec"
"reflect"
"regexp"
"strings"
"github.com/dave/dst"
"github.com/dave/dst/decorator"
log "github.com/sirupsen/logrus"
)
var (
// Strings to look for to identify generated files
generatedTerms = []string{
"do not edit",
"generated by",
"automatically regenerated",
}
// Go directives (should be ignored)
goDirectiveLine = regexp.MustCompile(`\s*//\s*go:.*`)
)
// The maximum number of shortening "rounds" that we'll allow. The shortening
// process should converge quickly, but we have this here as a safety mechanism to
// prevent loops that prevent termination.
const maxRounds = 20
// ShortenerConfig stores the configuration options exposed by a Shortener instance.
type ShortenerConfig struct {
MaxLen int // Max target width for each line
TabLen int // Width of a tab character
KeepAnnotations bool // Whether to keep annotations in final result (for debugging only)
ShortenComments bool // Whether to shorten comments
ReformatTags bool // Whether to reformat struct tags in addition to shortening long lines
IgnoreGenerated bool // Whether to ignore generated files
DotFile string // Path to write dot-formatted output to (for debugging only)
ChainSplitDots bool // Whether to split chain methods by putting dots at ends of lines
// Formatter that will be run before and after main shortening process. If empty,
// defaults to goimports (if found), otherwise gofmt.
BaseFormatterCmd string
}
// Shortener shortens a single go file according to a small set of user style
// preferences.
type Shortener struct {
config ShortenerConfig
// Some extra params around the base formatter generated from the BaseFormatterCmd
// argument in the config.
baseFormatter string
baseFormatterArgs []string
}
// NewShortener creates a new shortener instance from the provided config.
func NewShortener(config ShortenerConfig) *Shortener {
var formatterComponents []string
if config.BaseFormatterCmd == "" {
_, err := exec.LookPath("goimports")
if err != nil {
formatterComponents = []string{"gofmt"}
} else {
formatterComponents = []string{"goimports"}
}
} else {
formatterComponents = strings.Split(config.BaseFormatterCmd, " ")
}
s := &Shortener{
config: config,
baseFormatter: formatterComponents[0],
}
if len(formatterComponents) > 1 {
s.baseFormatterArgs = formatterComponents[1:]
} else {
s.baseFormatterArgs = []string{}
}
return s
}
// Shorten shortens the provided golang file content bytes.
func (s *Shortener) Shorten(contents []byte) ([]byte, error) {
if s.config.IgnoreGenerated && s.isGenerated(contents) {
return contents, nil
}
round := 0
var err error
// Do initial, non-line-length-aware formatting
contents, err = s.formatSrc(contents)
if err != nil {
return nil, fmt.Errorf("Error formatting source: %+v", err)
}
for {
log.Debugf("Starting round %d", round)
// Annotate all long lines
lines := strings.Split(string(contents), "\n")
annotatedLines, linesToShorten := s.annotateLongLines(lines)
var stop bool
if linesToShorten == 0 {
if round == 0 {
if !s.config.ReformatTags {
stop = true
} else if !HasMultiKeyTags(lines) {
stop = true
}
} else {
stop = true
}
}
if stop {
log.Debug("Nothing more to shorten or reformat, stopping")
break
}
contents = []byte(strings.Join(annotatedLines, "\n"))
// Generate AST
result, err := decorator.Parse(contents)
if err != nil {
return nil, err
}
if s.config.DotFile != "" {
dotFile, err := os.Create(s.config.DotFile)
if err != nil {
return nil, err
}
defer dotFile.Close()
log.Debugf("Writing dot file output to %s", s.config.DotFile)
err = CreateDot(result, dotFile)
if err != nil {
return nil, err
}
}
// Shorten the file starting at the top-level declarations
for _, decl := range result.Decls {
s.formatNode(decl)
}
// Materialize output
output := bytes.NewBuffer([]byte{})
err = decorator.Fprint(output, result)
if err != nil {
return nil, fmt.Errorf("Error parsing source: %+v", err)
}
contents = output.Bytes()
round++
if round > maxRounds {
log.Debugf("Hit max rounds, stopping")
break
}
}
if !s.config.KeepAnnotations {
contents = s.removeAnnotations(contents)
}
if s.config.ShortenComments {
contents = s.shortenCommentsFunc(contents)
}
// Do final round of non-line-length-aware formatting after we've fixed up the comments
contents, err = s.formatSrc(contents)
if err != nil {
return nil, fmt.Errorf("Error formatting source: %+v", err)
}
return contents, nil
}
// formatSrc formats the provided source bytes using the configured "base" formatter (typically
// goimports or gofmt).
func (s *Shortener) formatSrc(contents []byte) ([]byte, error) {
if s.baseFormatter == "gofmt" {
return format.Source(contents)
}
cmd := exec.Command(s.baseFormatter, s.baseFormatterArgs...)
stdinPipe, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
outBuffer := &bytes.Buffer{}
cmd.Stdout = outBuffer
if err = cmd.Start(); err != nil {
return nil, err
}
_, err = stdinPipe.Write(contents)
if err != nil {
return nil, err
}
stdinPipe.Close()
err = cmd.Wait()
if err != nil {
return nil, err
}
return outBuffer.Bytes(), nil
}
// annotateLongLines adds specially-formatted comments to all eligible lines that are longer than
// the configured target length. If a line already has one of these comments from a previous
// shortening round, then the comment contents are updated.
func (s *Shortener) annotateLongLines(lines []string) ([]string, int) {
annotatedLines := []string{}
linesToShorten := 0
prevLen := -1
for _, line := range lines {
length := s.lineLen(line)
if prevLen > -1 {
if length <= s.config.MaxLen {
// Shortening successful, remove previous annotation
annotatedLines = annotatedLines[:len(annotatedLines)-1]
} else if length < prevLen {
// Replace annotation with new length
annotatedLines[len(annotatedLines)-1] = CreateAnnotation(length)
linesToShorten++
}
} else if !s.isComment(line) && length > s.config.MaxLen {
annotatedLines = append(
annotatedLines,
CreateAnnotation(length),
)
linesToShorten++
}
annotatedLines = append(annotatedLines, line)
prevLen = ParseAnnotation(line)
}
return annotatedLines, linesToShorten
}
// removeAnnotations removes all comments that were added by the annotateLongLines
// function above.
func (s *Shortener) removeAnnotations(contents []byte) []byte {
cleanedLines := []string{}
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
if !IsAnnotation(line) {
cleanedLines = append(cleanedLines, line)
}
}
return []byte(strings.Join(cleanedLines, "\n"))
}
// shortenCommentsFunc attempts to shorten long comments in the provided source. As noted
// in the repo README, this functionality has some quirks and is disabled by default.
func (s *Shortener) shortenCommentsFunc(contents []byte) []byte {
cleanedLines := []string{}
words := []string{} // all words in a contiguous sequence of long comments
prefix := ""
lines := strings.Split(string(contents), "\n")
for _, line := range lines {
if s.isComment(line) && !IsAnnotation(line) &&
!s.isGoDirective(line) &&
s.lineLen(line) > s.config.MaxLen {
start := strings.Index(line, "//")
prefix = line[0:(start + 2)]
trimmedLine := strings.Trim(line[(start+2):], " ")
currLineWords := strings.Split(trimmedLine, " ")
words = append(words, currLineWords...)
} else {
// Reflow the accumulated `words` before appending the unprocessed `line`.
currLineLen := 0
currLineWords := []string{}
maxCommentLen := s.config.MaxLen - s.lineLen(prefix)
for _, word := range words {
if currLineLen > 0 && currLineLen+1+len(word) > maxCommentLen {
cleanedLines = append(
cleanedLines,
fmt.Sprintf(
"%s %s",
prefix,
strings.Join(currLineWords, " "),
),
)
currLineWords = []string{}
currLineLen = 0
}
currLineWords = append(currLineWords, word)
currLineLen += 1 + len(word)
}
if currLineLen > 0 {
cleanedLines = append(
cleanedLines,
fmt.Sprintf(
"%s %s",
prefix,
strings.Join(currLineWords, " "),
),
)
}
words = []string{}
cleanedLines = append(cleanedLines, line)
}
}
return []byte(strings.Join(cleanedLines, "\n"))
}
// lineLen gets the width of the provided line after tab expansion.
func (s *Shortener) lineLen(line string) int {
length := 0
for _, char := range line {
if char == '\t' {
length += s.config.TabLen
} else {
length++
}
}
return length
}
// isComment determines whether the provided line is a non-block comment.
func (s *Shortener) isComment(line string) bool {
return strings.HasPrefix(strings.Trim(line, " \t"), "//")
}
// isGoDirective determines whether the provided line is a go directive, e.g. for go generate.
func (s *Shortener) isGoDirective(line string) bool {
return goDirectiveLine.MatchString(line)
}
// formatNode formats the provided AST node. The appropriate helper function is called
// based on whether the node is a declaration, expression, statement, or spec.
func (s *Shortener) formatNode(node dst.Node) {
switch n := node.(type) {
case dst.Decl:
log.Debugf("Processing declaration: %+v", n)
s.formatDecl(n)
case dst.Expr:
log.Debugf("Processing expression: %+v", n)
s.formatExpr(n, false, false)
case dst.Stmt:
log.Debugf("Processing statement: %+v", n)
s.formatStmt(n)
case dst.Spec:
log.Debugf("Processing spec: %+v", n)
s.formatSpec(n, false)
default:
log.Debugf(
"Got a node type that can't be shortened: %+v",
reflect.TypeOf(n),
)
}
}
// formatDecl formats an AST declaration node. These include function declarations,
// imports, and constants.
func (s *Shortener) formatDecl(decl dst.Decl) {
switch d := decl.(type) {
case *dst.FuncDecl:
if HasAnnotationRecursive(decl) {
if d.Type != nil && d.Type.Params != nil {
s.formatFieldList(d.Type.Params)
}
}
s.formatStmt(d.Body)
case *dst.GenDecl:
for _, spec := range d.Specs {
s.formatSpec(spec, HasAnnotation(decl))
}
default:
log.Debugf(
"Got a declaration type that can't be shortened: %+v",
reflect.TypeOf(d),
)
}
}
// formatFieldList formats a field list in a function declaration.
func (s *Shortener) formatFieldList(fieldList *dst.FieldList) {
for f, field := range fieldList.List {
if f == 0 {
field.Decorations().Before = dst.NewLine
} else {
field.Decorations().Before = dst.None
}
field.Decorations().After = dst.NewLine
}
}
// formatStmt formats an AST statement node. Among other examples, these include assignments,
// case clauses, for statements, if statements, and select statements.
func (s *Shortener) formatStmt(stmt dst.Stmt) {
// Explicitly check for nil statements
stmtType := reflect.TypeOf(stmt)
if reflect.ValueOf(stmt) == reflect.Zero(stmtType) {
return
}
shouldShorten := HasAnnotation(stmt)
switch st := stmt.(type) {
case *dst.AssignStmt:
for _, expr := range st.Rhs {
s.formatExpr(expr, shouldShorten, false)
}
case *dst.BlockStmt:
for _, stmt := range st.List {
s.formatStmt(stmt)
}
case *dst.CaseClause:
if shouldShorten {
for _, arg := range st.List {
arg.Decorations().After = dst.NewLine
s.formatExpr(arg, false, false)
}
}
for _, stmt := range st.Body {
s.formatStmt(stmt)
}
case *dst.CommClause:
for _, stmt := range st.Body {
s.formatStmt(stmt)
}
case *dst.DeclStmt:
s.formatDecl(st.Decl)
case *dst.DeferStmt:
s.formatExpr(st.Call, shouldShorten, false)
case *dst.ExprStmt:
s.formatExpr(st.X, shouldShorten, false)
case *dst.ForStmt:
s.formatStmt(st.Body)
case *dst.GoStmt:
s.formatExpr(st.Call, shouldShorten, false)
case *dst.IfStmt:
s.formatExpr(st.Cond, shouldShorten, false)
s.formatStmt(st.Body)
case *dst.RangeStmt:
s.formatStmt(st.Body)
case *dst.ReturnStmt:
for _, expr := range st.Results {
s.formatExpr(expr, shouldShorten, false)
}
case *dst.SelectStmt:
s.formatStmt(st.Body)
case *dst.SwitchStmt:
s.formatStmt(st.Body)
default:
if shouldShorten {
log.Debugf(
"Got a statement type that can't be shortened: %+v",
reflect.TypeOf(st),
)
}
}
}
// formatExpr formats an AST expression node. These include uniary and binary expressions, function
// literals, and key/value pair statements, among others.
func (s *Shortener) formatExpr(expr dst.Expr, force bool, isChain bool) {
shouldShorten := force || HasAnnotation(expr)
switch e := expr.(type) {
case *dst.BinaryExpr:
if (e.Op == token.LAND || e.Op == token.LOR) && shouldShorten {
if e.Y.Decorations().Before == dst.NewLine {
s.formatExpr(e.X, force, isChain)
} else {
e.Y.Decorations().Before = dst.NewLine
}
} else {
s.formatExpr(e.X, shouldShorten, isChain)
s.formatExpr(e.Y, shouldShorten, isChain)
}
case *dst.CallExpr:
_, ok := e.Fun.(*dst.SelectorExpr)
if ok &&
s.config.ChainSplitDots &&
(shouldShorten || HasAnnotationRecursive(e)) &&
(isChain || s.chainLength(e) > 1) {
e.Decorations().After = dst.NewLine
for _, arg := range e.Args {
s.formatExpr(arg, false, true)
}
s.formatExpr(e.Fun, shouldShorten, true)
} else {
shortenChildArgs := shouldShorten || HasAnnotationRecursive(e)
for a, arg := range e.Args {
if shortenChildArgs {
if a == 0 {
arg.Decorations().Before = dst.NewLine
} else {
arg.Decorations().After = dst.None
}
arg.Decorations().After = dst.NewLine
}
s.formatExpr(arg, false, isChain)
}
s.formatExpr(e.Fun, shouldShorten, isChain)
}
case *dst.CompositeLit:
if shouldShorten {
for i, element := range e.Elts {
if i == 0 {
element.Decorations().Before = dst.NewLine
}
element.Decorations().After = dst.NewLine
}
}
for _, element := range e.Elts {
s.formatExpr(element, false, isChain)
}
case *dst.FuncLit:
s.formatStmt(e.Body)
case *dst.FuncType:
if shouldShorten {
s.formatFieldList(e.Params)
}
case *dst.InterfaceType:
for _, method := range e.Methods.List {
if HasAnnotation(method) {
s.formatExpr(method.Type, true, isChain)
}
}
case *dst.KeyValueExpr:
s.formatExpr(e.Value, shouldShorten, isChain)
case *dst.SelectorExpr:
s.formatExpr(e.X, shouldShorten, isChain)
case *dst.StructType:
if s.config.ReformatTags {
FormatStructTags(e.Fields)
}
case *dst.UnaryExpr:
s.formatExpr(e.X, shouldShorten, isChain)
default:
if shouldShorten {
log.Debugf(
"Got an expression type that can't be shortened: %+v",
reflect.TypeOf(e),
)
}
}
}
// formatSpec formats an AST spec node. These include type specifications, among other things.
func (s *Shortener) formatSpec(spec dst.Spec, force bool) {
shouldShorten := HasAnnotation(spec) || force
switch sp := spec.(type) {
case *dst.ValueSpec:
for _, expr := range sp.Values {
s.formatExpr(expr, shouldShorten, false)
}
case *dst.TypeSpec:
s.formatExpr(sp.Type, false, false)
default:
if shouldShorten {
log.Debugf(
"Got a spec type that can't be shortened: %+v",
reflect.TypeOf(sp),
)
}
}
}
// isGenerated checks whether the provided file bytes are from a generated file.
// This is done by looking for a set of typically-used strings in the first 5 lines.
func (s *Shortener) isGenerated(contents []byte) bool {
scanner := bufio.NewScanner(bytes.NewBuffer(contents))
for i := 0; scanner.Scan(); i++ {
if i >= 5 {
return false
}
for _, term := range generatedTerms {
if strings.Contains(strings.ToLower(scanner.Text()), term) {
return true
}
}
}
return false
}
// chainLength determines the length of the function call chain in an expression.
func (s *Shortener) chainLength(callExpr *dst.CallExpr) int {
numCalls := 1
currCall := callExpr
for {
selectorExpr, ok := currCall.Fun.(*dst.SelectorExpr)
if !ok {
break
}
currCall, ok = selectorExpr.X.(*dst.CallExpr)
if !ok {
break
}
numCalls++
}
return numCalls
}