github.com/yoheimuta/protolint@v0.49.8-0.20240515023657-4ecaebb7575d/internal/linter/file/protoFile.go (about) 1 package file 2 3 import ( 4 "os" 5 6 protoparser "github.com/yoheimuta/go-protoparser/v4" 7 "github.com/yoheimuta/go-protoparser/v4/parser" 8 ) 9 10 // ProtoFile is a Protocol Buffer file. 11 type ProtoFile struct { 12 // The path to the .proto file. 13 // Must be absolute. 14 // Must be cleaned. 15 path string 16 // The path to display in output. 17 // This will be relative to the working directory, or the absolute path 18 // if the file was outside the working directory. 19 displayPath string 20 } 21 22 // NewProtoFile creates a new proto file. 23 func NewProtoFile( 24 path string, 25 displayPath string, 26 ) ProtoFile { 27 return ProtoFile{ 28 path: path, 29 displayPath: displayPath, 30 } 31 } 32 33 // Parse parses a Protocol Buffer file. 34 func (f ProtoFile) Parse( 35 debug bool, 36 ) (_ *parser.Proto, err error) { 37 reader, err := os.Open(f.path) 38 if err != nil { 39 return nil, err 40 } 41 defer func() { 42 closeErr := reader.Close() 43 if err != nil { 44 return 45 } 46 if closeErr != nil { 47 err = closeErr 48 } 49 }() 50 51 proto, err := protoparser.Parse( 52 reader, 53 protoparser.WithFilename(f.displayPath), 54 protoparser.WithBodyIncludingComments(true), 55 protoparser.WithDebug(debug), 56 ) 57 if err != nil { 58 return nil, err 59 } 60 return proto, nil 61 } 62 63 // Path returns the path to the .proto file. 64 func (f ProtoFile) Path() string { 65 return f.path 66 } 67 68 // DisplayPath returns the path to display in output. 69 func (f ProtoFile) DisplayPath() string { 70 return f.displayPath 71 }