-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path__init__.py
More file actions
1829 lines (1547 loc) · 62 KB
/
__init__.py
File metadata and controls
1829 lines (1547 loc) · 62 KB
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Package protogen makes writing protoc plugins easy.
Working with the raw protobuf descriptor messages can be cumbersome. `protogen`
resolves and links the dependencies and references between the raw Protobuf
descriptors and turns them into their corresponding `protogen` classes that are
easier to work with. It also provides mechanisms that are espacially useful to
generate Python code like dealing with Python imports.
Most classes in `protogen` are simply replacements of their corresponding
Protobuf descriptors: `protogen.File` represents a FileDescriptor,
`protogen.Message` a Descriptor, `protogen.Field` a FieldDescriptor and so on.
They should be self explanatory. You can read their docstrings for more
information about them.
The classes `protogen.Options`, `protogen.Plugin` and `protogen.GeneratedFile`
make up a framework to generate files. You can see these in action in the
following example plugin:
.. code-block:: python
#!/usr/bin/env python
'''An example plugin.'''
import protogen
def generate(gen: protogen.Plugin):
for f in gen.files_to_generate:
g = gen.new_generated_file(
f.proto.name.replace(".proto", ".py"),
f.py_import_path,
)
g.P("# Generated code ahead.")
g.P()
g.print_imports()
g.P()
for m in f.message:
g.P("class ", m.py_ident, ":")
for ff in m.fields:
# ...
for s in f.services:
g.P("class ", s.py_ident, ":")
for m in f.methods:
g.P(" def ", m.py_name, "(request):")
g.P(" pass")
if __name__ == "__main__":
opts = protogen.Options()
opts.run(generate)
"""
import enum
import keyword
import sys
from typing import BinaryIO, Callable, Dict, List, Optional, Set, Tuple
from operator import ior
from functools import reduce
import google.protobuf.descriptor_pool
import google.protobuf.descriptor_pb2
import google.protobuf.message_factory
import google.protobuf.compiler.plugin_pb2
import protogen._case
class Registry:
"""A registry for protogen types.
A registry holds referneces to :class:`File`, :class:`Service`,
:class:`Enum` and :class:`Message` objects that have been resolved within
a resolution process (see :meth:`Options.run`).
"""
def __init__(self):
"""Create a new, empty registry."""
self._services_by_name: Dict[str, "Service"] = {}
self._messages_by_name: Dict[str, "Message"] = {}
self._enums_by_name: Dict[str, "Enum"] = {}
self._files_by_name: Dict[str, "File"] = {}
def _register_file(self, file: "File"):
self._files_by_name[file.proto.name] = file
def _register_service(self, service: "Service"):
self._services_by_name[service.full_name] = service
def _register_message(self, message: "Message"):
self._messages_by_name[message.full_name] = message
def _register_enum(self, enum: "Enum"):
self._enums_by_name[enum.full_name] = enum
def file_by_name(self, name: str) -> Optional["File"]:
"""Get a file by its full name.
Arguments
---------
name : str
The full (proto) name of the file to retrieve.
Returns
-------
file: File or None
The file or `None` if no file with that name has been registered.
"""
if name not in self._files_by_name:
return None
return self._files_by_name[name]
def service_by_name(self, name: str) -> Optional["Service"]:
"""Get a service by its full name.
Arguments
---------
name : str
The full (proto) name of the service to retrieve.
Returns
-------
service: Service or None
The service or `None` if no service with that name has been registered.
"""
if name not in self._services_by_name:
return None
return self._services_by_name[name]
def message_by_name(self, name: str) -> Optional["Message"]:
"""Get a message by its full name.
Arguments
---------
name : str
The full (proto) name of the message to retrieve.
Returns
-------
message: Message or None
The message or `None` if no message with that name has been registered.
"""
if name not in self._messages_by_name:
return None
return self._messages_by_name[name]
def enum_by_name(self, name: str) -> Optional["Enum"]:
"""Get an enum by its full name.
Arguments
---------
name : str
The full (proto) name of the enum to retrieve.
Returns
-------
enum: Enum or None
The enum or `None` if no enum with that name has been registered.
"""
if name not in self._enums_by_name:
return None
return self._enums_by_name[name]
def all_files(self) -> List["File"]:
"""Get all registered files."""
return list(self._files_by_name.values())
def all_services(self) -> List["Service"]:
"""Get all registered services."""
return list(self._services_by_name.values())
def all_messages(self) -> List["Message"]:
"""Get all registered messages."""
return list(self._messages_by_name.values())
def all_enums(self) -> List["Enum"]:
"""Get all registered enums."""
return list(self._enums_by_name.values())
def files_by_package(self, package: str) -> List["File"]:
"""Get files by proto package.
Arguments
---------
package : str
The proto package to get files for.
Returns
-------
List[File]
The files.
"""
files = []
for file in self._files_by_name.values():
if file.proto.package == package:
files.append(file)
return files
def services_by_package(self, package: str) -> List["Service"]:
"""Get services by proto package.
Arguments
---------
package : str
The proto package to get services for.
Returns
-------
List[Service]
The services.
"""
services = []
for service in self._services_by_name.values():
if service.parent_file.proto.package == package:
services.append(service)
return services
def messages_by_package(
self, package: str, top_level_only: bool = False
) -> List["Message"]:
"""Get messages by proto package.
Arguments
---------
package : str
The proto package to get messages for.
top_level_only : bool, optional, default=False
If True, only top level message are returned. Otherwise nested
messages are included.
Returns
-------
List[Message]
The messages.
"""
messages = []
for message in self._messages_by_name.values():
include = message.parent is None or not top_level_only
if message.parent_file.proto.package == package and include:
messages.append(message)
return messages
def enums_by_package(
self, package: str, top_level_only: bool = False
) -> List["Enum"]:
"""Get enums by proto package.
Arguments
---------
package : str
The proto package to get enums for.
top_level_only : bool, optional, default=False
If True, only top level enums are returned. Otherwise nested enums
are included.
Returns
-------
List[Enum]
The enums.
"""
enums = []
for enum in self._enums_by_name.values():
include = enum.parent is None or not top_level_only
if enum.parent_file.proto.package == package and include:
enums.append(enum)
return enums
def resolve_enum_type(
self, reference_scope: str, proto_name: str
) -> Optional["Enum"]:
"""Resolve an enum name to an enum.
Searches for an enum within the registry by its proto name. If the
`proto_name` has a leading dot the name is treated as fully qualified,
otherwise the enum is resolved relative to the reference scope using
C++ scoping rules.
E.g. given a `reference_scope` of `"mycom.cloud.datastore.v1.Hello`" and
a `proto_name' of `"World"` the registry would be search for (in that
order):
- mycom.cloud.datastore.v1.Hello.World
- mycom.cloud.datastore.v1.World
- mycom.cloud.datastore.World
- mycom.cloud.World
- mycom.World
- World
and the first existing enum type would be returned.
Arguments
---------
reference_scope : str
The current scope that acts as starting points in the enum type
resolution process.
proto_name : str
The proto (enum type) name to resolve.
Returns
-------
response: protogen.Enum | None
The resolved protogen enum type, or `None` if no enum with that name
could be found under the reference scope.
"""
if proto_name.startswith("."):
return self.enum_by_name(proto_name[1:])
ref_split = reference_scope.split(".")
for i in reversed(range(len(ref_split) + 1)):
ref_i = ".".join(ref_split[:i]) + "." + proto_name
enum = self.enum_by_name(ref_i)
if enum is not None:
return enum
return None
def resolve_message_type(
self, reference_scope: str, proto_name: str
) -> Optional["Message"]:
"""Resolve a message name to a message.
Searches for a message within the registry by its proto name. If the
`proto_name` has a leading dot the name is treated as fully qualified,
otherwise the message is resolved relative to the reference scope using
C++ scoping rules.
E.g. given a `reference_scope` of `"mycom.cloud.datastore.v1.Hello`" and
a `proto_name' of `"World"` the registry would be search for (in that
order):
- mycom.cloud.datastore.v1.Hello.World
- mycom.cloud.datastore.v1.World
- mycom.cloud.datastore.World
- mycom.cloud.World
- mycom.World
- World
and the first existing message type would be returned.
Arguments
---------
reference_scope : str
The current scope that acts as starting points in the message type
resolution process.
proto_name : str
The proto (message type) name to resolve.
Returns
-------
response: protogen.Message | None
The resolved protogen message type, or `None` if no message with
that name could be found under the reference scope.
"""
if proto_name.startswith("."):
return self.message_by_name(proto_name[1:])
ref_split = reference_scope.split(".")
for i in reversed(range(len(ref_split) + 1)):
prefix = ref_split[:i]
_name = prefix + [proto_name]
name = ".".join(_name)
msg = self.message_by_name(name)
if msg is not None:
return msg
return None
def _clean_comment(cmmt: str) -> str:
"""Remove the first whitespace from every line, if any."""
lines = cmmt.splitlines()
clean_lines = []
for line in lines:
if len(line) > 0 and line[0] == " ":
clean_lines.append(line[1:])
else:
clean_lines.append(line)
return "\n".join(clean_lines)
class Location:
"""A proto location.
A Location identifies a piece of source code in a .proto file which
corresponds to a particular definition. This information is particular
useful as it contains the comments that are associated with a certain part
(e.g. a message or field) of the ``.proto`` file.
Attributes
----------
source_file : str
Name of the file the location is from.
path : List[int]
Identifies which part of the FileDescriptor was defined at the location.
leading_comments : str
Comments directly attached (leading) to the location. Not separated with
a blank.
trailing_comments : str
Comments directly attached (trailing) to the location. Not separated
with a blank.
leading_detached_comments : List[str]
Comments that are leading to the current location and detached from it
by at least one blank line.
Examples
--------
The following example explains the different kind of comments.
.. code-block:: proto
optional int32 foo = 1; // Comment attached to foo.
// Comment attached to bar.
optional int32 bar = 2;
optional string baz = 3;
// Comment attached to baz.
// Another line attached to baz.
// Comment attached to qux.
//
// Another line attached to qux.
optional double qux = 4;
// Detached comment for corge. This is not leading or trailing comments
// to qux or corge because there are blank lines separating it from
// both.
// Detached comment for corge paragraph 2.
optional string corge = 5;
/* Block comment attached
* to corge. Leading asterisks
* will be removed. */
/* Block comment attached to
* grault. */
optional int32 grault = 6;
// ignored detached comments.
"""
def __init__(
self,
source_file: str,
path: List[int],
leading_detached_comments: List[str],
leading_comments: str,
trailing_comments: str,
):
self.source_file = source_file
self.path = path
self.leading_detached_comments = [
_clean_comment(c) for c in leading_detached_comments
]
self.leading_comments = _clean_comment(leading_comments)
self.trailing_comments = _clean_comment(trailing_comments)
def _resolve_location(
file: google.protobuf.descriptor_pb2.FileDescriptorProto, path: List[int]
) -> Location:
"""Resolve location information for a path.
Arguments
---------
file : google.protobuf.descriptor_pb2.FileDescriptorProto
The file descriptor that contains the location information.
path : List[number]:
Path to resolve the location information for.
Returns
-------
Location
Location information for the path in file, or an empty Location
information if the path is not present in the file.
"""
for location_pb in file.source_code_info.location:
# location_pb.path is a RepeatedScalarFieldContainer, that implements __eq__
# and compares again its inner _values (list(int)) to the other argument.
if location_pb.path == path:
return Location(
file.name,
path,
location_pb.leading_detached_comments,
location_pb.leading_comments,
location_pb.trailing_comments,
)
return Location(file.name, path, [], "", "")
class PyImportPath:
"""A Python import path.
Represents a Python import path as used in a Python import statement. In
Python, the import path is used to identify the module to import. An import
path "google.protobuf.timestamp_pb2" refers to the
"google/protobuf/timestamp_pb2.py" module and might be imported as follows:
>>> import google.protobuf.timestamp_pb2
or
>>> from google.protobuf.timestamp_pb2 import Timestamp
This is just a simple wrapper class around the import string. It is used in
the `GeneratedFile` to keep track of which import statements need to be
included in the output of the generated file as well as how a `PyIdent`
needs to be referred to in the output the generated file.
Example
-------
Use the `PyImportPath` class to take advantage of the import resolution
mechanism provided by the `GeneratedFile`:
>>> import protogen
>>> grpc_pkg = protogen.PyImportPath("grpc")
>>> # g is of type protogen.GeneratedFile
>>> g.P("def my_method(request):")
>>> g.P(" ", grpc_pkg.ident("unary_unary"), "(request)")
That way `grpc_pkg` will be added automatically to the import list of `g`.
"""
def __init__(self, path: str):
"""Create a new Python import path wrapping `path`."""
self._path = path
def ident(self, name: str) -> "PyIdent":
"""Create a `PyIdent` with `self` as import path and name as `py_name`.
Arguments
---------
name : str
Python name of the identifier.
Returns
-------
PyIdent
The python identifier.
"""
return PyIdent(self, name)
def __eq__(self, o: object) -> bool:
"""Compare the import path.
Returns
-------
True, if the interal paths match. False, otherwise.
"""
if type(o) != PyImportPath:
return NotImplemented
return self._path == o._path
def __hash__(self) -> int:
"""Hash the import path."""
return hash(self._path)
def _is_reserved_name(value: str) -> bool:
if keyword.iskeyword(value):
return True
if value in ("bytes", "str"):
return True
return False
def _sanitize_name(value: str) -> str:
"""Necessary for field and method names."""
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
return f"{value}_" if _is_reserved_name(value) else value
class PyIdent:
"""An identifier for a Python class, function or variable.
A Python class, function or variable is uniquely identified by its import
path (e.g. ``google.protobuf.timestamp_pb2``), that references the module its
defined in, and name (eg `Timestamp`).
Attributes
----------
py_import_path : PyImportPath
The Python import path of the identifier.
py_name : str
Name of the class, function or variable.
"""
def __init__(self, py_import_path: PyImportPath, py_name: str):
"""Create a new Python identifier.
The recommended way to initialize a new `PyIdent` is using
`PyImportPath.indent()` instead.
>>> grpc_pkg = protogen.PyImportPath("grpc")
>>> grpc_pkg.ident("unary_unary")
"""
self.py_import_path = py_import_path
self.py_name = _sanitize_name(py_name)
class Kind(enum.Enum):
"""Kind is an enumeration of the different value types of a field."""
DOUBLE = 1
FLOAT = 2
INT64 = 3
UINT64 = 4
INT32 = 5
FIXED64 = 6
FIXED32 = 7
BOOL = 8
STRING = 9
GROUP = 10
MESSAGE = 11
BYTES = 12
UINT32 = 13
ENUM = 14
SFIXED32 = 15
SFIXED64 = 16
SINT32 = 17
SINT64 = 18
class Cardinality(enum.Enum):
"""Cardinality specifies whether a field is optional, required or repeated."""
OPTIONAL = 1
REQUIRED = 2
REPEATED = 3
class EnumValue:
"""A proto enum value.
This is the ``protogen`` equivalent to a protobuf EnumValueDescriptor. The
enum values attributes are obtained from the EnumValueDescriptor it is
derived from and references to other ``protogen`` classes that have been
resolved in the resolution process. It represents a Protobuf enum value
declared within an Protobuf enum definition.
Attributes
----------
proto : google.protobuf.descriptor_pb2.EnumValueDescriptorProto
The raw EnumValueDescriptor of the enum value.
py_ident : PyIdent
Python identifier for the Python attribute of the enum value.
full_name : str
Full proto name of the enum value. Note that full names of enum values
are different: All other proto declarations are in the namespace of
their parent. Enum values however are within the namespace of ther
parent file. An enum value named ``FOO_VALUE`` declared within an enum
``proto.package.MyEnum`` has a full name of ``proto.package.FOO:VALUE``.
number : int
The enum number.
parent : Enum
The enum the enum value is declared in.
location : Location
Comments associated with the enum value.
"""
def __init__(
self,
proto: google.protobuf.descriptor_pb2.EnumValueDescriptorProto,
parent: "Enum",
path: List[int],
):
self.proto = proto
# The Python identifier for a enum value is TODO
self.py_ident = parent.py_ident.py_import_path.ident(
parent.py_ident.py_name + "." + proto.name
)
self.number = self.proto.number
self.parent = parent
self.location = _resolve_location(parent.parent_file.proto, path)
class Enum:
"""A proto enum.
This is the ``protogen`` equivalent to a protobuf EnumDescriptor. The enums
attributes are obtained from the EnumDescriptor it is derived from and
references to other ``protogen`` classes that have been resolved in the
resolution process. It represents a Protobuf enum defined within an `.proto`
file.
Attributes
----------
proto : google.protobuf.descriptor_pb2.EnumDescriptorProto
The raw EnumDescriptor of the enum.
py_ident : PyIdent
Python identifier for the Python class of the enum.
full_name : str
Full proto name of the enum.
parent_file : File
The File the enum is declared in.
parent : Message or None
For nested enums, the message the enum is declared in. ``None`` otherwise.
values : List[EnumValue]
Values of the enum.
location : Location
Comments associated with the enum.
"""
def __init__(
self,
proto: google.protobuf.descriptor_pb2.EnumDescriptorProto,
parent_file: "File",
parent: Optional["Message"],
path: List[int],
):
self.proto = proto
if parent is None:
self.full_name = parent_file.proto.package + "." + proto.name
self.py_ident = parent_file.py_import_path.ident(proto.name)
else:
self.full_name = parent.full_name + "." + proto.name
self.py_ident = parent.py_ident.py_import_path.ident(
parent.py_ident.py_name + "." + proto.name
)
self.parent_file = parent_file
self.parent = parent
self.location = _resolve_location(parent_file.proto, path)
# Add enum values.
self.values: List[EnumValue] = []
for i in range(len(proto.value)):
value_path = path + [
2,
i,
] # 2 is the field number for `value` in `EnumDescriptorProto`.
self.values.append(EnumValue(proto.value[i], self, value_path))
def _is_map(message: "Message") -> bool:
return (
message.proto.HasField("options")
and message.proto.options.HasField("map_entry")
and getattr(message.proto.options, "map_entry")
)
class Field:
"""A proto field.
This is the ``protogen`` equivalent to a protobuf FieldDescriptor. The
fields attributes are obtained from the FieldDescriptor it is derived from
and references to other ``protogen`` classes that have been resolved in the
resolution process. It represents a Protobuf field declared within a
Protobuf message definition. It is also used to describe protobuf extensions.
Attributes
----------
proto : google.protobuf.descriptor_pb2.FieldDescriptorProto
The raw FieldDescriptor of the field.
py_name : str
Python name of the field. This is a sanatized version of the original
proto field name.
full_name : str
Full proto name of the field.
parent : Message or None
The message the field is declared in. Or ``None`` for top-level
extensions.
parent_file : File
The file the field is declared in.
oneof : OneOf or None
The oneof in case the field is contained in a oneof. ``None`` otherwise.
kind : Kind
The field kind.
cardinality : Cardinality
Cardinality of the field.
enum : Enum or None
The enum type of the field in case the fields :attr:`kind` is
:attr:`Kind.Enum`. ``None`` otherwise.
message : Message or None
The message type of the field in case the fields :attr:`kind` is
:attr:`Kind.Message`. ``None`` otherwise.
extendee : Message or None
The extendee in case this is a top-level extension. ``None`` otherwise.
location : Location
Comments associated with the field.
"""
def __init__(
self,
proto: google.protobuf.descriptor_pb2.FieldDescriptorProto,
parent: Optional["Message"],
parent_file: "File",
oneof: Optional["OneOf"],
path: List[int],
):
self.proto = proto
self.py_name = proto.name
if parent is not None:
self.full_name = parent.full_name + "." + proto.name
else:
# top-level-extension
self.full_name = parent_file.proto.package + "." + proto.name
self.parent = parent
self.parent_file = parent_file
self.oneof = oneof
self.kind = Kind(proto.type) # type V is builtin.int
self.cardinality = Cardinality(proto.label) # type V is builtin.int
self.location = _resolve_location(parent_file.proto, path)
self.message: Optional["Message"] = None
self.enum: Optional["Enum"] = None
def is_map(self) -> bool:
"""Whether the field is a map field.
Returns
-------
bool
``True`` if the field is a map field. ``False`` otherwise.
"""
if self.message is None:
return False
return _is_map(self.message)
def is_list(self) -> bool:
"""Whether the field is a list field.
A list fields has a :attr:`cardinality` of ``Cardinality.REPEATED`` and
is not a map field.
Returns
-------
bool
``True`` if the field is a list field. ``False`` otherwise.
"""
return self.cardinality == Cardinality.REPEATED and not self.is_map()
def map_key(self) -> Optional["Field"]:
"""Return the map key if the field is a map field.
Returns
-------
Field or None
The field of the map key if :meth:`is_map` is ``True``. ``None``
otherwise.
"""
if not self.is_map():
return None
return self.message.fields[0]
def map_value(self) -> Optional["Field"]:
"""Return the map value if the field is a map field.
Returns
-------
Field or None
The field of the map value if :meth:`is_map` is ``True``. ``None``
otherwise.
"""
if not self.is_map():
return None
return self.message.fields[1]
def _resolve(self, registry: Registry):
# resolve extendee is present
if self.proto.HasField("extendee"):
self.extendee = registry.resolve_message_type(
self.full_name, self.proto.extendee
)
if self.extendee is None:
raise ResolutionError(
file=self.parent_file.proto.name,
desc=self.full_name,
ref=self.proto.extendee,
)
# resolve the enum
if self.kind == Kind.ENUM:
if not self.proto.HasField("type_name"):
raise InvalidDescriptorError(
full_name=self.full_name,
msg="is of kind ENUM but has no `type_name` set",
)
self.enum = registry.resolve_enum_type(self.full_name, self.proto.type_name)
if not self.enum:
raise ResolutionError(
file=self.parent_file.proto.name,
desc=self.full_name,
ref=self.proto.type_name,
)
# resolve the message
if self.kind == Kind.MESSAGE:
if not self.proto.HasField("type_name"):
raise InvalidDescriptorError(
full_name=self.full_name,
msg="is of kind MESSAGE but has no `type_name` set",
)
self.message = registry.resolve_message_type(
self.full_name, self.proto.type_name
)
if self.message is None:
raise ResolutionError(
file=self.parent_file.proto.name,
desc=self.full_name,
ref=self.proto.type_name,
)
class OneOf:
"""A proto Oneof.
This is the ``protogen`` equivalent to a protobuf OneofDescriptor. The
oneofs attributes are obtained from the OneofDescriptor it is derived from
and references to other ``protogen`` classes that have been resolved in the
resolution process. It represents a Protobuf oneof declared within a
Protobuf message definition.
Attributes
----------
proto : google.protobuf.descriptor_pb2.OneofDescriptorProto
The raw OneofDescritor of the oneof.
full_name : str
Full proto name of the oneof.
parent : Message
The message the oneof is declared in.
fields : List[Field]
Fields that are part of the oneof.
location : Location
Comments associated with the oneof.
"""
def __init__(
self,
proto: google.protobuf.descriptor_pb2.OneofDescriptorProto,
parent: "Message",
path: List[int],
):
self.proto = proto
self.full_name = parent.full_name + "." + proto.name
self.parent = parent
self.location = _resolve_location(parent.parent_file.proto, path)
self.fields: List[Field] = []
Extension = Field
"""A protobuf extension.
Protobuf extensions are described using FieldDescriptors. See :class:`Field`.
"""
class Message:
"""A proto message.
This is the ``protogen`` equivalent to a protobuf Descriptor. The messages
attributes are obtained from the Descriptor it is derived from and
references to other ``protogen`` classes that have been resolved in the
resolution process. It represents a Protobuf message defined within an
`.proto` file.
Attributes
----------
proto : google.protobuf.descriptor_pb2.DescriptorProto
The raw Descriptor of the message.
py_ident : PyIdent
Python identifier for the Python class of the message.
full_name : str
Full proto name of the message.
parent_file : File
The file the message is defined in.
parent : Message or None
The parent message in case this is a nested message. ``None``, for
top-level messages.
fields : List[Field]
Message field declarations. This includes fields defined within oneofs.
oneofs : List[OneOf]
Oneof declarations.
enums : List[Enum]
Nested enum declarations.
messages List[Message]:
Nested message declarations.
extensions : List[Extension]
Nested extension declations.
location : Location
Comments associated with the message.
"""
def __init__(
self,
proto: google.protobuf.descriptor_pb2.DescriptorProto,
parent_file: "File",
parent: Optional["Message"],
path: List[int],
):
self.proto = proto
if parent is None:
self.full_name = parent_file.proto.package + "." + proto.name
self.py_ident = parent_file.py_import_path.ident(self.proto.name)
else:
self.full_name = parent.full_name + "." + proto.name
self.py_ident = parent_file.py_import_path.ident(
parent.py_ident.py_name + "." + proto.name
)
self.parent_file = parent_file
self.parent = parent