avrotize 2.21.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. avrotize/__init__.py +66 -0
  2. avrotize/__main__.py +6 -0
  3. avrotize/_version.py +34 -0
  4. avrotize/asn1toavro.py +160 -0
  5. avrotize/avrotize.py +152 -0
  6. avrotize/avrotocpp/CMakeLists.txt.jinja +77 -0
  7. avrotize/avrotocpp/build.bat.jinja +7 -0
  8. avrotize/avrotocpp/build.sh.jinja +7 -0
  9. avrotize/avrotocpp/dataclass_body.jinja +108 -0
  10. avrotize/avrotocpp/vcpkg.json.jinja +21 -0
  11. avrotize/avrotocpp.py +483 -0
  12. avrotize/avrotocsharp/README.md.jinja +166 -0
  13. avrotize/avrotocsharp/class_test.cs.jinja +266 -0
  14. avrotize/avrotocsharp/dataclass_core.jinja +293 -0
  15. avrotize/avrotocsharp/enum_test.cs.jinja +20 -0
  16. avrotize/avrotocsharp/project.csproj.jinja +30 -0
  17. avrotize/avrotocsharp/project.sln.jinja +34 -0
  18. avrotize/avrotocsharp/run_coverage.ps1.jinja +98 -0
  19. avrotize/avrotocsharp/run_coverage.sh.jinja +149 -0
  20. avrotize/avrotocsharp/testproject.csproj.jinja +19 -0
  21. avrotize/avrotocsharp.py +1180 -0
  22. avrotize/avrotocsv.py +121 -0
  23. avrotize/avrotodatapackage.py +173 -0
  24. avrotize/avrotodb.py +1383 -0
  25. avrotize/avrotogo/go_enum.jinja +12 -0
  26. avrotize/avrotogo/go_helpers.jinja +31 -0
  27. avrotize/avrotogo/go_struct.jinja +151 -0
  28. avrotize/avrotogo/go_test.jinja +47 -0
  29. avrotize/avrotogo/go_union.jinja +38 -0
  30. avrotize/avrotogo.py +476 -0
  31. avrotize/avrotographql.py +197 -0
  32. avrotize/avrotoiceberg.py +210 -0
  33. avrotize/avrotojava/class_test.java.jinja +212 -0
  34. avrotize/avrotojava/enum_test.java.jinja +21 -0
  35. avrotize/avrotojava/testproject.pom.jinja +54 -0
  36. avrotize/avrotojava.py +2156 -0
  37. avrotize/avrotojs.py +250 -0
  38. avrotize/avrotojsons.py +481 -0
  39. avrotize/avrotojstruct.py +345 -0
  40. avrotize/avrotokusto.py +364 -0
  41. avrotize/avrotomd/README.md.jinja +49 -0
  42. avrotize/avrotomd.py +137 -0
  43. avrotize/avrotools.py +168 -0
  44. avrotize/avrotoparquet.py +208 -0
  45. avrotize/avrotoproto.py +359 -0
  46. avrotize/avrotopython/dataclass_core.jinja +241 -0
  47. avrotize/avrotopython/enum_core.jinja +87 -0
  48. avrotize/avrotopython/pyproject_toml.jinja +18 -0
  49. avrotize/avrotopython/test_class.jinja +97 -0
  50. avrotize/avrotopython/test_enum.jinja +23 -0
  51. avrotize/avrotopython.py +626 -0
  52. avrotize/avrotorust/dataclass_enum.rs.jinja +74 -0
  53. avrotize/avrotorust/dataclass_struct.rs.jinja +204 -0
  54. avrotize/avrotorust/dataclass_union.rs.jinja +105 -0
  55. avrotize/avrotorust.py +435 -0
  56. avrotize/avrotots/class_core.ts.jinja +140 -0
  57. avrotize/avrotots/class_test.ts.jinja +77 -0
  58. avrotize/avrotots/enum_core.ts.jinja +46 -0
  59. avrotize/avrotots/gitignore.jinja +34 -0
  60. avrotize/avrotots/index.ts.jinja +0 -0
  61. avrotize/avrotots/package.json.jinja +23 -0
  62. avrotize/avrotots/tsconfig.json.jinja +21 -0
  63. avrotize/avrotots.py +687 -0
  64. avrotize/avrotoxsd.py +344 -0
  65. avrotize/cddltostructure.py +1841 -0
  66. avrotize/commands.json +3496 -0
  67. avrotize/common.py +834 -0
  68. avrotize/constants.py +87 -0
  69. avrotize/csvtoavro.py +132 -0
  70. avrotize/datapackagetoavro.py +76 -0
  71. avrotize/dependencies/cpp/vcpkg/vcpkg.json +19 -0
  72. avrotize/dependencies/cs/net90/dependencies.csproj +29 -0
  73. avrotize/dependencies/go/go121/go.mod +6 -0
  74. avrotize/dependencies/java/jdk21/pom.xml +91 -0
  75. avrotize/dependencies/python/py312/requirements.txt +13 -0
  76. avrotize/dependencies/rust/stable/Cargo.toml +17 -0
  77. avrotize/dependencies/typescript/node22/package.json +16 -0
  78. avrotize/dependency_resolver.py +348 -0
  79. avrotize/dependency_version.py +432 -0
  80. avrotize/generic/generic.avsc +57 -0
  81. avrotize/jsonstoavro.py +2167 -0
  82. avrotize/jsonstostructure.py +2864 -0
  83. avrotize/jstructtoavro.py +878 -0
  84. avrotize/kstructtoavro.py +93 -0
  85. avrotize/kustotoavro.py +455 -0
  86. avrotize/openapitostructure.py +717 -0
  87. avrotize/parquettoavro.py +157 -0
  88. avrotize/proto2parser.py +498 -0
  89. avrotize/proto3parser.py +403 -0
  90. avrotize/prototoavro.py +382 -0
  91. avrotize/prototypes/any.avsc +19 -0
  92. avrotize/prototypes/api.avsc +106 -0
  93. avrotize/prototypes/duration.avsc +20 -0
  94. avrotize/prototypes/field_mask.avsc +18 -0
  95. avrotize/prototypes/struct.avsc +60 -0
  96. avrotize/prototypes/timestamp.avsc +20 -0
  97. avrotize/prototypes/type.avsc +253 -0
  98. avrotize/prototypes/wrappers.avsc +117 -0
  99. avrotize/structuretocddl.py +597 -0
  100. avrotize/structuretocpp/CMakeLists.txt.jinja +76 -0
  101. avrotize/structuretocpp/build.bat.jinja +3 -0
  102. avrotize/structuretocpp/build.sh.jinja +3 -0
  103. avrotize/structuretocpp/dataclass_body.jinja +50 -0
  104. avrotize/structuretocpp/vcpkg.json.jinja +11 -0
  105. avrotize/structuretocpp.py +697 -0
  106. avrotize/structuretocsharp/class_test.cs.jinja +180 -0
  107. avrotize/structuretocsharp/dataclass_core.jinja +156 -0
  108. avrotize/structuretocsharp/enum_test.cs.jinja +36 -0
  109. avrotize/structuretocsharp/json_structure_converters.cs.jinja +399 -0
  110. avrotize/structuretocsharp/program.cs.jinja +49 -0
  111. avrotize/structuretocsharp/project.csproj.jinja +17 -0
  112. avrotize/structuretocsharp/project.sln.jinja +34 -0
  113. avrotize/structuretocsharp/testproject.csproj.jinja +18 -0
  114. avrotize/structuretocsharp/tuple_converter.cs.jinja +121 -0
  115. avrotize/structuretocsharp.py +2295 -0
  116. avrotize/structuretocsv.py +365 -0
  117. avrotize/structuretodatapackage.py +659 -0
  118. avrotize/structuretodb.py +1125 -0
  119. avrotize/structuretogo/go_enum.jinja +12 -0
  120. avrotize/structuretogo/go_helpers.jinja +26 -0
  121. avrotize/structuretogo/go_interface.jinja +18 -0
  122. avrotize/structuretogo/go_struct.jinja +187 -0
  123. avrotize/structuretogo/go_test.jinja +70 -0
  124. avrotize/structuretogo.py +729 -0
  125. avrotize/structuretographql.py +502 -0
  126. avrotize/structuretoiceberg.py +355 -0
  127. avrotize/structuretojava/choice_core.jinja +34 -0
  128. avrotize/structuretojava/class_core.jinja +23 -0
  129. avrotize/structuretojava/enum_core.jinja +18 -0
  130. avrotize/structuretojava/equals_hashcode.jinja +30 -0
  131. avrotize/structuretojava/pom.xml.jinja +26 -0
  132. avrotize/structuretojava/tuple_core.jinja +49 -0
  133. avrotize/structuretojava.py +938 -0
  134. avrotize/structuretojs/class_core.js.jinja +33 -0
  135. avrotize/structuretojs/enum_core.js.jinja +10 -0
  136. avrotize/structuretojs/package.json.jinja +12 -0
  137. avrotize/structuretojs/test_class.js.jinja +84 -0
  138. avrotize/structuretojs/test_enum.js.jinja +58 -0
  139. avrotize/structuretojs/test_runner.js.jinja +45 -0
  140. avrotize/structuretojs.py +657 -0
  141. avrotize/structuretojsons.py +498 -0
  142. avrotize/structuretokusto.py +639 -0
  143. avrotize/structuretomd/README.md.jinja +204 -0
  144. avrotize/structuretomd.py +322 -0
  145. avrotize/structuretoproto.py +764 -0
  146. avrotize/structuretopython/dataclass_core.jinja +363 -0
  147. avrotize/structuretopython/enum_core.jinja +45 -0
  148. avrotize/structuretopython/map_alias.jinja +21 -0
  149. avrotize/structuretopython/pyproject_toml.jinja +23 -0
  150. avrotize/structuretopython/test_class.jinja +103 -0
  151. avrotize/structuretopython/test_enum.jinja +34 -0
  152. avrotize/structuretopython.py +799 -0
  153. avrotize/structuretorust/dataclass_enum.rs.jinja +63 -0
  154. avrotize/structuretorust/dataclass_struct.rs.jinja +121 -0
  155. avrotize/structuretorust/dataclass_union.rs.jinja +81 -0
  156. avrotize/structuretorust.py +714 -0
  157. avrotize/structuretots/class_core.ts.jinja +78 -0
  158. avrotize/structuretots/enum_core.ts.jinja +6 -0
  159. avrotize/structuretots/gitignore.jinja +8 -0
  160. avrotize/structuretots/index.ts.jinja +1 -0
  161. avrotize/structuretots/package.json.jinja +39 -0
  162. avrotize/structuretots/test_class.ts.jinja +35 -0
  163. avrotize/structuretots/tsconfig.json.jinja +21 -0
  164. avrotize/structuretots.py +740 -0
  165. avrotize/structuretoxsd.py +679 -0
  166. avrotize/xsdtoavro.py +413 -0
  167. avrotize-2.21.1.dist-info/METADATA +1319 -0
  168. avrotize-2.21.1.dist-info/RECORD +171 -0
  169. avrotize-2.21.1.dist-info/WHEEL +4 -0
  170. avrotize-2.21.1.dist-info/entry_points.txt +3 -0
  171. avrotize-2.21.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,359 @@
1
+ import copy
2
+ import json
3
+ import argparse
4
+ import os
5
+ from typing import Literal, NamedTuple, Dict, Any, List
6
+
7
+ indent = ' '
8
+
9
+ Comment = NamedTuple('Comment', [('content', str), ('tags', Dict[str, Any])])
10
+ Oneof = NamedTuple('Oneof', [('comment', 'Comment'), ('name', str), ('fields', List['Field'])])
11
+ Field = NamedTuple('Field', [('comment', 'Comment'), ('label', str), ('type', str), ('key_type', str), ('val_type', str), ('name', str), ('number', int), ('dependencies', List[str])])
12
+ Enum = NamedTuple('Enum', [('comment', 'Comment'), ('name', str), ('fields', Dict[str, 'Field'])])
13
+ Message = NamedTuple('Message', [('comment', 'Comment'), ('name', str), ('fields', List['Field']), ('oneofs', List['Oneof']),
14
+ ('messages', Dict[str, 'Message']), ('enums', Dict[str, 'Enum']), ('dependencies', List[str])])
15
+ Service = NamedTuple('Service', [('name', str), ('functions', Dict[str, 'RpcFunc'])])
16
+ RpcFunc = NamedTuple('RpcFunc', [('name', str), ('in_type', str), ('out_type', str), ('uri', str)])
17
+ ProtoFile = NamedTuple('ProtoFile',
18
+ [('messages', Dict[str, 'Message']), ('enums', Dict[str, 'Enum']),
19
+ ('services', Dict[str, 'Service']), ('imports', List[str]),
20
+ ('options', Dict[str, str]), ('package', str)])
21
+ ProtoFiles = NamedTuple('ProtoFiles', [('files', List['ProtoFile'])])
22
+
23
+ class AvroToProto:
24
+
25
+ def __init__(self) -> None:
26
+ self.naming_mode: Literal['snake', 'pascal', 'camel'] = 'pascal'
27
+ self.allow_optional: bool = False
28
+ self.default_namespace: str = ''
29
+
30
+ def avro_primitive_to_proto_type(self, avro_type: str, dependencies: List[str]) -> str:
31
+ """Map Avro primitive types to Protobuf types."""
32
+ mapping = {
33
+ 'null': 'google.protobuf.Empty', # Special handling may be required
34
+ 'boolean': 'bool',
35
+ 'int': 'int32',
36
+ 'long': 'int64',
37
+ 'float': 'float',
38
+ 'double': 'double',
39
+ 'bytes': 'bytes',
40
+ 'string': 'string',
41
+ }
42
+ # logical types require special handling
43
+ if isinstance(avro_type, dict) and 'logicalType' in avro_type:
44
+ logical_type = avro_type['logicalType']
45
+ if logical_type == 'date':
46
+ return 'string'
47
+ elif logical_type == 'time-millis':
48
+ return 'string'
49
+ elif logical_type == 'timestamp-millis':
50
+ return 'string'
51
+ elif logical_type == 'decimal':
52
+ precision = avro_type['precision']
53
+ scale = avro_type['scale']
54
+ return 'string'
55
+ elif logical_type == 'duration':
56
+ return 'string'
57
+ elif logical_type == 'uuid':
58
+ return 'string'
59
+
60
+ type = mapping.get(avro_type, '')
61
+ if not type:
62
+ dependencies.append(avro_type)
63
+ type = avro_type
64
+ return type
65
+
66
+ def compose_name(self, prefix: str, name: str, naming_mode: Literal['pascal', 'camel', 'snake', 'default', 'field'] = 'default') -> str:
67
+ if naming_mode == 'default':
68
+ naming_mode = self.naming_mode
69
+ if naming_mode == 'field':
70
+ if self.naming_mode == 'pascal':
71
+ naming_mode = 'camel'
72
+ else:
73
+ naming_mode = self.naming_mode
74
+ if naming_mode == 'snake':
75
+ return f"{prefix}_{name}"
76
+ if naming_mode == 'pascal':
77
+ return f"{prefix[0].upper()+prefix[1:] if prefix else ''}{name[0].upper()+name[1:] if name else ''}"
78
+ if naming_mode == 'camel':
79
+ return f"{prefix[0].lower()+prefix[1:] if prefix else ''}{name[0].upper()+name[1:] if name else ''}"
80
+ return prefix+name
81
+
82
+ def convert_field(self, message: Message, avro_field: dict, index: int, proto_files: ProtoFiles) -> Field | Oneof | Enum | Message:
83
+ """Convert an Avro field to a Protobuf field."""
84
+ field_type = avro_field['type']
85
+ field_name = avro_field['name'] if 'name' in avro_field else self.compose_name(field_type.split('.')[-1],'value', 'field') if isinstance(field_type, str) else self.compose_name(f"_{index}", 'value', 'field')
86
+ if 'doc' in avro_field:
87
+ comment = Comment(avro_field["doc"], {})
88
+ else:
89
+ comment = Comment('',{})
90
+
91
+ return self.convert_field_type(message, field_name, field_type, comment, index, proto_files)
92
+
93
+ def convert_record_type(self, avro_record: dict, comment: Comment, proto_files: ProtoFiles) -> Message:
94
+ """Convert an Avro record to a Protobuf message."""
95
+ local_message = Message(comment, avro_record['name'], [], [], {}, {}, [])
96
+ offs = 1
97
+ for i, f in enumerate(avro_record['fields']):
98
+ field = self.convert_field(local_message, f, i+offs, proto_files)
99
+ if isinstance(field, Oneof):
100
+ for f in field.fields:
101
+ local_message.dependencies.extend(f.dependencies)
102
+ local_message.oneofs.append(field)
103
+ offs += len(field.fields)-1
104
+ elif isinstance(field, Enum):
105
+ enum = Enum(field.comment, self.compose_name(field.name,'enum'), field.fields)
106
+ local_message.enums[enum.name] = enum
107
+ local_message.fields.append(Field(field.comment, '', enum.name, '', '', field.name.split('.')[-1], i+offs, []))
108
+ elif isinstance(field, Message):
109
+ inner_message = Message(field.comment, self.compose_name(field.name,'type'), field.fields, field.oneofs, field.messages, field.enums, [])
110
+ local_message.messages[inner_message.name] = inner_message
111
+ local_message.fields.append(Field(field.comment, '', inner_message.name, '', '', field.name.split('.')[-1], i+offs, []))
112
+ local_message.dependencies.extend(field.dependencies)
113
+ else:
114
+ local_message.dependencies.extend(field.dependencies)
115
+ local_message.fields.append(field)
116
+ return local_message
117
+
118
+ def convert_field_type(self, message: Message, field_name: str, field_type: str | dict | list, comment: Comment, index: int, proto_files: ProtoFiles) -> Field | Oneof | Enum | Message:
119
+ """Convert an Avro field type to a Protobuf field type."""
120
+ label = ''
121
+
122
+ if isinstance(field_type, list):
123
+ # Handling union types (including nullable fields)
124
+ non_null_types = [t for t in field_type if t != 'null']
125
+ if len(non_null_types) == 1:
126
+ if self.allow_optional:
127
+ label = 'optional'
128
+ field_type = non_null_types[0]
129
+ elif len(non_null_types) > 0:
130
+ oneof_fields = []
131
+ for i, t in enumerate(non_null_types):
132
+ field = self.convert_field_type(message, self.compose_name(field_name,'choice', 'field'), t, comment, i+index, proto_files)
133
+ if isinstance(field, Field):
134
+ if field.type == 'map' or field.type == 'array':
135
+ local_message = Message(comment, self.compose_name(field.name,field.type), [], [], {}, {}, field.dependencies)
136
+ local_message.fields.append(field)
137
+ new_field = Field(field.comment, '', local_message.name, '', '', self.compose_name(field.name.split('.')[-1],field.type, 'field'), i+index, field.dependencies)
138
+ message.messages[local_message.name] = local_message
139
+ oneof_fields.append(new_field)
140
+ else:
141
+ field = Field(field.comment, field.label, field.type, field.key_type, field.val_type, self.compose_name(field_name, (field.type.split('.')[-1]), 'field'), i+index, field.dependencies)
142
+ oneof_fields.append(field)
143
+ elif isinstance(field, Oneof):
144
+ deps: List[str] = []
145
+ oneof = field
146
+ for f in oneof.fields:
147
+ deps.extend(f.dependencies)
148
+ local_message = Message(comment, self.compose_name(field.name,'choice'), [], [], {}, {}, deps)
149
+ index += len(field.fields)
150
+ local_message.oneofs.append(field)
151
+ new_field = Field(field.comment, '', local_message.name, '', '', field.name.split('.')[-1], i+index, deps)
152
+ message.messages[local_message.name] = local_message
153
+ oneof_fields.append(new_field)
154
+ elif isinstance(field, Enum):
155
+ enum = Enum(field.comment, self.compose_name(field.name,"options"), field.fields)
156
+ message.enums[enum.name] = enum
157
+ field = Field(field.comment, '', enum.name, '', '', field.name.split('.')[-1], i+index, [])
158
+ oneof_fields.append(field)
159
+ elif isinstance(field, Message):
160
+ local_message = Message(field.comment, self.compose_name(field.name,'type'), field.fields, field.oneofs, field.messages, field.enums, field.dependencies)
161
+ message.messages[local_message.name] = local_message
162
+ field = Field(field.comment, '', local_message.name, '', '', field.name.split('.')[-1], i+index, field.dependencies)
163
+ oneof_fields.append(field)
164
+ oneof = Oneof(comment, field_name, copy.deepcopy(oneof_fields))
165
+ return oneof
166
+ else:
167
+ raise ValueError(f"Field {field_name} is a union type without any non-null types")
168
+
169
+ if isinstance(field_type, dict):
170
+ # Nested types (e.g., records, enums) require special handling
171
+ if field_type['type'] == 'record':
172
+ return self.convert_record_type(field_type, comment, proto_files)
173
+ elif field_type['type'] == 'enum':
174
+ enum_symbols = {symbol: Field(comment, '', symbol, '', '', symbol, s, []) for s, symbol in enumerate(field_type['symbols'])}
175
+ return Enum(comment, field_type['name'], enum_symbols)
176
+ elif field_type['type'] == 'array':
177
+ converted_field_type = self.convert_field_type(message, self.compose_name(field_name, "item"), field_type['items'], comment, index, proto_files)
178
+ if isinstance(converted_field_type, Field):
179
+ return Field(comment, 'repeated', 'array', '', converted_field_type.type, field_name, index, converted_field_type.dependencies)
180
+ elif isinstance(converted_field_type, Enum):
181
+ enum = Enum(converted_field_type.comment, self.compose_name(converted_field_type.name,'enum'), converted_field_type.fields)
182
+ message.enums[enum.name] = enum
183
+ return Field(comment, 'repeated', 'array', '', enum.name, field_name, index, [])
184
+ elif isinstance(converted_field_type, Message):
185
+ local_message = Message(converted_field_type.comment, self.compose_name(converted_field_type.name,'type'), converted_field_type.fields, converted_field_type.oneofs, converted_field_type.messages, converted_field_type.enums, converted_field_type.dependencies)
186
+ message.messages[local_message.name] = local_message
187
+ return Field(comment, 'repeated', 'array', '', local_message.name, field_name, index, [])
188
+ elif isinstance(converted_field_type, Oneof):
189
+ deps3: List[str] = []
190
+ fl = []
191
+ for i, f in enumerate(converted_field_type.fields):
192
+ fl.append(Field(Comment('',{}), '', f.type, '', '', f.name, i+1, []))
193
+ deps3.extend(f.dependencies)
194
+ oneof = Oneof(converted_field_type.comment, 'item', fl)
195
+ local_message = Message(comment, self.compose_name(field_name,'type'), [], [], {}, {}, deps3)
196
+ local_message.oneofs.append(oneof)
197
+ new_field = Field(Comment('',{}), 'repeated', 'array', '', local_message.name, field_name.split('.')[-1], index, local_message.dependencies)
198
+ message.messages[local_message.name] = local_message
199
+ return new_field
200
+ elif field_type['type'] == 'map':
201
+ converted_field_type = self.convert_field_type(message, self.compose_name(field_name,'item', 'field'), field_type['values'], comment, index, proto_files)
202
+ if isinstance(converted_field_type, Field):
203
+ return Field(comment, label, 'map', 'string', converted_field_type.type, field_name, index, converted_field_type.dependencies)
204
+ elif isinstance(converted_field_type, Enum):
205
+ enum = Enum(converted_field_type.comment, self.compose_name(converted_field_type.name,'enum'), converted_field_type.fields)
206
+ message.enums[enum.name] = enum
207
+ return Field(comment, label, 'map', 'string', enum.name, field_name, index, [])
208
+ elif isinstance(converted_field_type, Message):
209
+ local_message = Message(converted_field_type.comment, self.compose_name(converted_field_type.name,'type'), converted_field_type.fields, converted_field_type.oneofs, converted_field_type.messages, converted_field_type.enums, [])
210
+ message.messages[local_message.name] = local_message
211
+ return Field(comment, label, 'map', 'string', local_message.name, field_name, index, local_message.dependencies)
212
+ elif isinstance(converted_field_type, Oneof):
213
+ deps4: List[str] = []
214
+ fl = []
215
+ for i, f in enumerate(converted_field_type.fields):
216
+ fl.append(Field(Comment('',{}), '', f.type, '', '', f.name, i+1, []))
217
+ deps4.extend(f.dependencies)
218
+ oneof = Oneof(converted_field_type.comment, 'item', fl)
219
+ local_message = Message(comment, self.compose_name(field_name, 'type'), [], [], {}, {}, deps4)
220
+ local_message.oneofs.append(oneof)
221
+ new_field = Field(Comment('',{}), label, 'map', 'string', local_message.name, field_name.split('.')[-1], index, local_message.dependencies)
222
+ message.messages[local_message.name] = local_message
223
+ return new_field
224
+ elif field_type['type'] == "fixed":
225
+ return Field(comment, label, 'fixed','string', 'string', field_name, index, [])
226
+ else:
227
+ deps1: List[str] = []
228
+ proto_type = self.avro_primitive_to_proto_type(field_type['type'], deps1)
229
+ return Field(comment, label, proto_type, '', '', field_name, index, deps1)
230
+ elif isinstance(field_type, str):
231
+ deps2: List[str] = []
232
+ proto_type = self.avro_primitive_to_proto_type(field_type, deps2)
233
+ return Field(comment, label, proto_type, '', '', field_name, index, deps2)
234
+ raise ValueError(f"Unknown field type {field_type}")
235
+
236
+ def avro_schema_to_proto_message(self, avro_schema: dict, proto_files: ProtoFiles) -> str:
237
+ """Convert an Avro schema to a Protobuf message definition."""
238
+ comment = Comment('',{})
239
+ if 'doc' in avro_schema:
240
+ comment = Comment(avro_schema["doc"], {})
241
+ namespace = avro_schema.get("namespace", '')
242
+ if not namespace:
243
+ namespace = self.default_namespace
244
+ if avro_schema['type'] == 'record':
245
+ message = self.convert_record_type(avro_schema, comment, proto_files)
246
+ file = next((f for f in proto_files.files if f.package == namespace), None)
247
+ if not file:
248
+ file = ProtoFile({}, {}, {}, [], {}, namespace)
249
+ proto_files.files.append(file)
250
+ file.messages[message.name] = message
251
+ elif avro_schema['type'] == 'enum':
252
+ enum_name = avro_schema['name']
253
+ enum_symbols = {symbol: Field(comment, '', symbol, '', '', symbol, s, []) for s, symbol in enumerate(avro_schema['symbols'])}
254
+ enum = Enum(comment, enum_name, enum_symbols)
255
+ file = next((f for f in proto_files.files if f.package == namespace), None)
256
+ if not file:
257
+ file = ProtoFile({}, {}, {}, [], {}, namespace)
258
+ proto_files.files.append(file)
259
+ file.enums[enum_name] = enum
260
+ return avro_schema["name"]
261
+
262
+ def avro_schema_to_proto_messages(self, avro_schema_input, proto_files: ProtoFiles):
263
+ """Convert an Avro schema to Protobuf message definitions."""
264
+ if not isinstance(avro_schema_input, list):
265
+ avro_schema_list = [avro_schema_input]
266
+ else:
267
+ avro_schema_list = avro_schema_input
268
+ for avro_schema in avro_schema_list:
269
+ self.avro_schema_to_proto_message(avro_schema, proto_files)
270
+
271
+ def save_proto_to_file(self, proto_files: ProtoFiles, proto_path):
272
+ """Save the Protobuf schema to a file."""
273
+ for proto in proto_files.files:
274
+ # gather dependencies that are within the package
275
+ deps: List[str] = []
276
+ for message in proto.messages.values():
277
+ for dep in message.dependencies:
278
+ if '.' in dep:
279
+ deps.append(dep.rsplit('.',1)[0])
280
+ deps = list(set(deps))
281
+
282
+ #proto.imports.extend([f.package[len(proto.package)+1:] for f in proto_files.files if f.package.startswith(proto.package) and f.package != proto.package])
283
+ proto.imports.extend([d for d in deps if d != proto.package])
284
+ proto_file_path = os.path.join(proto_path, f"{proto.package}.proto")
285
+ # create the directory for the proto file if it doesn't exist
286
+ proto_dir = os.path.dirname(proto_file_path)
287
+ if not os.path.exists(proto_dir):
288
+ os.makedirs(proto_dir, exist_ok=True)
289
+ with open(proto_file_path, 'w') as proto_file:
290
+ # dump the ProtoFile structure in proto syntax
291
+ proto_str = f'syntax = "proto3";\n\n'
292
+ proto_str += f'package {proto.package};\n\n'
293
+
294
+ for import_package in proto.imports:
295
+ proto_str += f"import \"{import_package}.proto\";\n"
296
+ if (len(proto.imports)):
297
+ proto_str += "\n"
298
+ for enum_name, enum in proto.enums.items():
299
+ proto_str += f"enum {enum_name} {{\n"
300
+ for _, field in enum.fields.items():
301
+ proto_str += f"{indent}{field.name} = {field.number};\n"
302
+ proto_str += "}\n\n"
303
+ for message in proto.messages.values():
304
+ proto_str += self.render_message(message)
305
+ for service in proto.services.values():
306
+ proto_str += f"service {service.name} {{\n"
307
+ for function_name, func in service.functions.items():
308
+ proto_str += f"{indent}rpc {func.name} ({func.in_type}) returns ({func.out_type}) {{\n"
309
+ proto_str += f"{indent}{indent}option (google.api.http) = {{\n"
310
+ proto_str += f"{indent}{indent}{indent}post: \"{func.uri}\"\n"
311
+ proto_str += f"{indent}{indent}}};\n"
312
+ proto_str += f"{indent}}};\n"
313
+ proto_str += "}\n\n"
314
+ proto_file.write(proto_str)
315
+
316
+ def render_message(self, message, level=0) -> str:
317
+ proto_str = f"{indent*level}message {message.name} {{\n"
318
+ fieldsAndOneofs = message.fields+message.oneofs
319
+ fieldsAndOneofs.sort(key=lambda f: f.number if isinstance(f, Field) else f.fields[0].number)
320
+ for fo in fieldsAndOneofs:
321
+ if isinstance(fo, Field):
322
+ field = fo
323
+ if field.type == "map":
324
+ proto_str += f"{indent*level}{indent}{field.label}{' ' if field.label else ''}map<{field.key_type}, {field.val_type}> {field.name} = {field.number};\n"
325
+ elif field.type == "array":
326
+ proto_str += f"{indent*level}{indent}{field.label}{' ' if field.label else ''}{field.val_type} {field.name} = {field.number};\n"
327
+ else:
328
+ proto_str += f"{indent*level}{indent}{field.label}{' ' if field.label else ''}{field.type} {field.name} = {field.number};\n"
329
+ else:
330
+ oneof = fo
331
+ proto_str += f"{indent*level}{indent}oneof {oneof.name} {{\n"
332
+ for field in oneof.fields:
333
+ proto_str += f"{indent*level}{indent}{indent}{field.label}{' ' if field.label else ''}{field.type} {field.name} = {field.number};\n"
334
+ proto_str += f"{indent*level}{indent}}}\n"
335
+ for enum in message.enums.values():
336
+ proto_str += f"{indent*level}{indent}enum {enum.name} {{\n"
337
+ for _, field in enum.fields.items():
338
+ proto_str += f"{indent*level}{indent}{indent}{field.label}{' ' if field.label else ''}{field.name} = {field.number};\n"
339
+ proto_str += f"{indent*level}{indent}}}\n"
340
+ for local_message in message.messages.values():
341
+ proto_str += self.render_message(local_message, level+1)
342
+ proto_str += f"{indent*level}}}\n"
343
+ return proto_str
344
+
345
+
346
+ def convert_avro_to_proto(self, avro_schema_path, proto_file_path):
347
+ """Convert Avro schema file to Protobuf .proto file."""
348
+ with open(avro_schema_path, 'r') as avro_file:
349
+ avro_schema = json.load(avro_file)
350
+ proto_files = ProtoFiles([])
351
+ self.avro_schema_to_proto_messages(avro_schema, proto_files)
352
+ self.save_proto_to_file(proto_files, proto_file_path)
353
+
354
+ def convert_avro_to_proto(avro_schema_path, proto_file_path, naming_mode: Literal['snake', 'pascal', 'camel'] = 'pascal', allow_optional: bool = False):
355
+ avrotoproto = AvroToProto()
356
+ avrotoproto.naming_mode = naming_mode
357
+ avrotoproto.allow_optional = allow_optional
358
+ avrotoproto.default_namespace = os.path.splitext(os.path.basename(proto_file_path))[0].replace('-','_')
359
+ avrotoproto.convert_avro_to_proto(avro_schema_path, proto_file_path)
@@ -0,0 +1,241 @@
1
+ """ {{ class_name }} dataclass. """
2
+
3
+ # pylint: disable=too-many-lines, too-many-locals, too-many-branches, too-many-statements, too-many-arguments, line-too-long, wildcard-import
4
+
5
+ {%- if avro_annotation or dataclasses_json_annotation %}
6
+ import io
7
+ import gzip
8
+ import json
9
+ {%- endif %}
10
+ import enum
11
+ import typing
12
+ import dataclasses
13
+ from dataclasses import dataclass
14
+ {%- if dataclasses_json_annotation %}
15
+ import dataclasses_json
16
+ from dataclasses_json import Undefined, dataclass_json
17
+ {%- for field in fields if field.type == "datetime" or field.type == "typing.Optional[datetime.datetime]" %}
18
+ {%- if loop.first %}
19
+ from marshmallow import fields
20
+ {%- endif %}
21
+ {%- endfor %}
22
+ {%- endif %}
23
+ {%- if avro_annotation %}
24
+ import avro.schema
25
+ import avro.name
26
+ import avro.io
27
+ {%- endif %}
28
+ {%- for import_type in import_types if import_type not in ['datetime.datetime', 'datetime.date', 'datetime.time', 'datetime.timedelta', 'decimal.Decimal'] %}
29
+ from {{ '.'.join(import_type.split('.')[:-1]) | lower }} import {{ import_type.split('.')[-1] }}
30
+ {%- endfor %}
31
+ {%- for import_type in import_types if import_type in ['datetime.datetime', 'datetime.date', 'datetime.time', 'datetime.timedelta'] %}
32
+ {%- if loop.first %}
33
+ import datetime
34
+ {%- endif %}
35
+ {%- endfor %}
36
+
37
+ {% if dataclasses_json_annotation %}
38
+ @dataclass_json(undefined=Undefined.EXCLUDE)
39
+ {%- endif %}
40
+ @dataclass
41
+ class {{ class_name }}:
42
+ """
43
+ {{ docstring }}
44
+ Attributes:
45
+ {%- for field in fields %}
46
+ {{ field.docstring }}
47
+ {%- endfor -%}
48
+ """
49
+ {% for field in fields %}
50
+ {%- set isdate = field.type == "datetime" or field.type == "typing.Optional[datetime.datetime]" %}
51
+ {{ field.name }}: {{ field.type }}=dataclasses.field(kw_only=True{% if dataclasses_json_annotation %}, metadata=dataclasses_json.config(field_name="{{ field.original_name }}"{%- if isdate -%}, encoder=lambda d: d.isoformat() if isinstance(d, datetime.datetime) else d if d else None, decoder=lambda d: datetime.datetime.fromisoformat(d) if isinstance(d, str) else d if d else None, mm_field=fields.DateTime(format='iso'){%- endif -%}){%- endif %})
52
+ {%- endfor %}
53
+ {% if avro_annotation %}
54
+ AvroType: typing.ClassVar[avro.schema.Schema] = avro.schema.make_avsc_object(
55
+ json.loads("{{ avro_schema_json }}"), avro.name.Names()
56
+ )
57
+ {%- endif %}
58
+
59
+ def __post_init__(self):
60
+ """ Initializes the dataclass with the provided keyword arguments."""
61
+ {% filter indent(8) %}
62
+ {{- init_fields }}
63
+ {%- endfilter %}
64
+
65
+ @classmethod
66
+ def from_serializer_dict(cls, data: dict) -> '{{ class_name }}':
67
+ """
68
+ Converts a dictionary to a dataclass instance.
69
+
70
+ Args:
71
+ data: The dictionary to convert to a dataclass.
72
+
73
+ Returns:
74
+ The dataclass representation of the dictionary.
75
+ """
76
+ {%- for field in fields %}
77
+ {%- if field.name != field.original_name %}
78
+ data['{{ field.name }}'] = data.pop('{{ field.original_name }}')
79
+ {%- endif %}
80
+ {%- endfor %}
81
+ return cls(**data)
82
+
83
+ def to_serializer_dict(self) -> dict:
84
+ """
85
+ Converts the dataclass to a dictionary.
86
+
87
+ Returns:
88
+ The dictionary representation of the dataclass.
89
+ """
90
+ asdict_result = dataclasses.asdict(self, dict_factory=self._dict_resolver)
91
+ {%- for field in fields %}
92
+ {%- if field.name != field.original_name and field.original_name+'_' != field.name %}
93
+ asdict_result['{{ field.original_name }}'] = asdict_result.pop('{{ field.name }}')
94
+ {%- endif %}
95
+ {%- endfor %}
96
+ return asdict_result
97
+
98
+ def _dict_resolver(self, data):
99
+ """
100
+ Helps resolving the Enum values to their actual values and fixes the key names.
101
+ """
102
+ def _resolve_enum(v):
103
+ if isinstance(v,enum.Enum):
104
+ return v.value
105
+ return v
106
+ def _fix_key(k):
107
+ return k[:-1] if k.endswith('_') else k
108
+ return {_fix_key(k): _resolve_enum(v) for k, v in iter(data)}
109
+ {%- if avro_annotation or dataclasses_json_annotation %}
110
+
111
+ def to_byte_array(self, content_type_string: str) -> bytes:
112
+ """
113
+ Converts the dataclass to a byte array based on the content type string.
114
+
115
+ Args:
116
+ content_type_string: The content type string to convert the dataclass to.
117
+ Supported content types:
118
+ {%- if avro_annotation %}
119
+ 'avro/binary': Encodes the data to Avro binary format.
120
+ 'application/vnd.apache.avro+avro': Encodes the data to Avro binary format.
121
+ {%- endif %}
122
+ {%- if dataclasses_json_annotation %}
123
+ 'application/json': Encodes the data to JSON format.
124
+ {%- endif %}
125
+ Supported content type extensions:
126
+ '+gzip': Compresses the byte array using gzip, e.g. 'application/json+gzip'.
127
+
128
+ Returns:
129
+ The byte array representation of the dataclass.
130
+ """
131
+ content_type = content_type_string.split(';')[0].strip()
132
+ result = None
133
+
134
+ # Strip compression suffix for base type matching
135
+ base_content_type = content_type.replace('+gzip', '')
136
+
137
+ {%- if avro_annotation %}
138
+ if base_content_type in ['avro/binary', 'application/vnd.apache.avro+avro']:
139
+ stream = io.BytesIO()
140
+ writer = avro.io.DatumWriter(self.AvroType)
141
+ encoder = avro.io.BinaryEncoder(stream)
142
+ writer.write(self.to_serializer_dict(), encoder)
143
+ result = stream.getvalue()
144
+ {%- endif %}
145
+
146
+ {%- if dataclasses_json_annotation %}
147
+ if base_content_type == 'application/json':
148
+ #pylint: disable=no-member
149
+ result = self.to_json()
150
+ #pylint: enable=no-member
151
+ {%- endif %}
152
+
153
+ if result is not None and content_type.endswith('+gzip'):
154
+ # Handle string result from to_json()
155
+ if isinstance(result, str):
156
+ result = result.encode('utf-8')
157
+ with io.BytesIO() as stream:
158
+ with gzip.GzipFile(fileobj=stream, mode='wb') as gzip_file:
159
+ gzip_file.write(result)
160
+ result = stream.getvalue()
161
+
162
+ if result is None:
163
+ raise NotImplementedError(f"Unsupported media type {content_type}")
164
+
165
+ return result
166
+
167
+ @classmethod
168
+ def from_data(cls, data: typing.Any, content_type_string: typing.Optional[str] = None) -> typing.Optional['{{ class_name }}']:
169
+ """
170
+ Converts the data to a dataclass based on the content type string.
171
+
172
+ Args:
173
+ data: The data to convert to a dataclass.
174
+ content_type_string: The content type string to convert the data to.
175
+ Supported content types:
176
+ {%- if avro_annotation %}
177
+ 'avro/binary': Attempts to decode the data from Avro binary encoded format.
178
+ 'application/vnd.apache.avro+avro': Attempts to decode the data from Avro binary encoded format.
179
+ 'avro/json': Attempts to decode the data from Avro JSON encoded format.
180
+ 'application/vnd.apache.avro+json': Attempts to decode the data from Avro JSON encoded format.
181
+ {%- endif %}
182
+ {%- if dataclasses_json_annotation %}
183
+ 'application/json': Attempts to decode the data from JSON encoded format.
184
+ {%- endif %}
185
+ Supported content type extensions:
186
+ '+gzip': First decompresses the data using gzip, e.g. 'application/json+gzip'.
187
+ Returns:
188
+ The dataclass representation of the data.
189
+ """
190
+ if data is None:
191
+ return None
192
+ if isinstance(data, cls):
193
+ return data
194
+ if isinstance(data, dict):
195
+ return cls.from_serializer_dict(data)
196
+
197
+ content_type = (content_type_string or 'application/octet-stream').split(';')[0].strip()
198
+
199
+ if content_type.endswith('+gzip'):
200
+ if isinstance(data, (bytes, io.BytesIO)):
201
+ stream = io.BytesIO(data) if isinstance(data, bytes) else data
202
+ else:
203
+ raise NotImplementedError('Data is not of a supported type for gzip decompression')
204
+ with gzip.GzipFile(fileobj=stream, mode='rb') as gzip_file:
205
+ data = gzip_file.read()
206
+
207
+ # Strip compression suffix for base type matching
208
+ base_content_type = content_type.replace('+gzip', '')
209
+
210
+ {%- if avro_annotation %}
211
+ if base_content_type in ['avro/binary', 'application/vnd.apache.avro+avro', 'avro/json', 'application/vnd.apache.avro+json']:
212
+ if isinstance(data, (bytes, io.BytesIO)):
213
+ stream = io.BytesIO(data) if isinstance(data, bytes) else data
214
+ else:
215
+ raise NotImplementedError('Data is not of a supported type for conversion to Stream')
216
+ reader = avro.io.DatumReader(cls.AvroType)
217
+ if base_content_type in ['avro/binary', 'application/vnd.apache.avro+avro']:
218
+ decoder = avro.io.BinaryDecoder(stream)
219
+ else:
220
+ raise NotImplementedError(f'Unsupported Avro media type {content_type}')
221
+ _record = reader.read(decoder)
222
+ return {{ class_name }}.from_serializer_dict(_record)
223
+ {%- endif %}
224
+
225
+ {%- if dataclasses_json_annotation %}
226
+ if base_content_type == 'application/json':
227
+ if isinstance(data, (bytes, str)):
228
+ data_str = data.decode('utf-8') if isinstance(data, bytes) else data
229
+ _record = json.loads(data_str)
230
+ {%- for field in fields %}
231
+ {%- if field.name != field.original_name %}
232
+ _record['{{ field.name }}'] = _record.pop('{{ field.original_name }}')
233
+ {%- endif %}
234
+ {%- endfor %}
235
+ return {{ class_name }}.from_serializer_dict(_record)
236
+ else:
237
+ raise NotImplementedError('Data is not of a supported type for JSON deserialization')
238
+ {%- endif %}
239
+
240
+ raise NotImplementedError(f'Unsupported media type {content_type}')
241
+ {%- endif %}