- Notifications
You must be signed in to change notification settings - Fork30
A pure Python protobuf parser
License
criccomini/proto-schema-parser
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Protobuf Schema Parser is a pure-Python library that parses and writes Protobuf schemas to and from an abstract syntax tree (AST).
The library usesproto_schema_parser.parser.Parser to parse theCST into an AST. Theproto_schema_parser.generator.Generator class converts the AST back into a CST (a Protobuf schema string).
The lexer and parser are autogenerated fromBuf's ANTLRlexer and parser grammar files.
- ✅ proto2 and proto3 support
- ✅ protobuf editions support (edition 2023, edition 2024)
- ✅ message, field, enum, optional, required, repeated
- ✅ import, package, oneof, map, and option
- ✅ group and extend (in proto2)
- ✅ service, rpc, and stream
- ✅ line and block comment preservation
Install the package via pip:
pip install proto-schema-parser
To parse a protobuf schema, create aParser object and call theparse method:
fromproto_schema_parser.parserimportParsertext="""syntax = "proto3";message SearchRequest { string query = 1; int32 page_number = 2; int32 result_per_page = 3;}"""result=Parser().parse(text)
This will return an AST object (ast.File) representing the parsed protobuf schema.
File(syntax='proto3',file_elements=[Message(name='SearchRequest',elements=[Field(name='query',number=1,type='string',cardinality=None,options=[]),Field(name='page_number',number=2,type='int32',cardinality=None,options=[]),Field(name='result_per_page',number=3,type='int32',cardinality=None,options=[])])])
To write the AST back to a protobuf schema, create aGenerator object and call thegenerate method:
fromproto_schema_parser.generatorimportGeneratorproto=Generator().generate(result)
Theproto variable now contains the string:
syntax="proto3";messageSearchRequest {stringquery=1;int32page_number=2;int32result_per_page=3;}
The library also supportsprotobuf editions, which provide more flexibility than proto2/proto3 syntax:
fromproto_schema_parser.parserimportParserfromproto_schema_parser.generatorimportGenerator# Parse a protobuf file using edition syntaxtext="""edition = "2023";message SearchRequest { string query = 1; int32 page_number = 2;}"""result=Parser().parse(text)# result.edition will be "2023"# result.syntax will be None# Generate back to protobuf formatproto=Generator().generate(result)
Supported editions:
edition = "2023";-Edition 2023 specedition = "2024";-Edition 2024 spec
I welcome contributions!
- Submit a PR and I'll review it as soon as I can.
- Open an issue if you find a bug or have a feature request.
Protobuf Schema Parser is licensed under theMIT license.
About
A pure Python protobuf parser
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.