github.com/nikron/prototool@v1.3.0/internal/format/transformer.go (about) 1 // Copyright (c) 2018 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 package format 22 23 import ( 24 "bytes" 25 "fmt" 26 "strings" 27 28 "github.com/emicklei/proto" 29 "github.com/uber/prototool/internal/text" 30 "go.uber.org/zap" 31 ) 32 33 type transformer struct { 34 logger *zap.Logger 35 fix bool 36 } 37 38 func newTransformer(options ...TransformerOption) *transformer { 39 transformer := &transformer{ 40 logger: zap.NewNop(), 41 } 42 for _, option := range options { 43 option(transformer) 44 } 45 return transformer 46 } 47 48 func (t *transformer) Transform(filename string, data []byte) ([]byte, []*text.Failure, error) { 49 descriptor, err := proto.NewParser(bytes.NewReader(data)).Parse() 50 if err != nil { 51 return nil, nil, err 52 } 53 descriptor.Filename = filename 54 55 firstPassVisitor := newFirstPassVisitor(filename, t.fix) 56 for _, element := range descriptor.Elements { 57 element.Accept(firstPassVisitor) 58 } 59 failures := firstPassVisitor.Do() 60 buffer := bytes.NewBuffer(nil) 61 buffer.Write(firstPassVisitor.Bytes()) 62 63 syntaxVersion := 2 64 if firstPassVisitor.Syntax != nil && firstPassVisitor.Syntax.Value != "" { 65 switch firstPassVisitor.Syntax.Value { 66 case "proto2": 67 // nothing 68 case "proto3": 69 syntaxVersion = 3 70 default: 71 return nil, nil, fmt.Errorf("unknown syntax: %s", firstPassVisitor.Syntax.Value) 72 } 73 } 74 75 mainVisitor := newMainVisitor(syntaxVersion == 2) 76 for _, element := range descriptor.Elements { 77 element.Accept(mainVisitor) 78 } 79 failures = append(failures, mainVisitor.Do()...) 80 buffer.Write(mainVisitor.Bytes()) 81 82 text.SortFailures(failures) 83 84 // TODO: expensive 85 s := strings.TrimSpace(buffer.String()) 86 if len(s) > 0 { 87 return []byte(s + "\n"), failures, nil 88 } 89 return nil, failures, nil 90 }