店播爬取Python脚本

text_format.py 60KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Contains routines for printing protocol messages in text format.
  31. Simple usage example::
  32. # Create a proto object and serialize it to a text proto string.
  33. message = my_proto_pb2.MyMessage(foo='bar')
  34. text_proto = text_format.MessageToString(message)
  35. # Parse a text proto string.
  36. message = text_format.Parse(text_proto, my_proto_pb2.MyMessage())
  37. """
  38. __author__ = 'kenton@google.com (Kenton Varda)'
  39. # TODO(b/129989314) Import thread contention leads to test failures.
  40. import encodings.raw_unicode_escape # pylint: disable=unused-import
  41. import encodings.unicode_escape # pylint: disable=unused-import
  42. import io
  43. import math
  44. import re
  45. import six
  46. from google.protobuf.internal import decoder
  47. from google.protobuf.internal import type_checkers
  48. from google.protobuf import descriptor
  49. from google.protobuf import text_encoding
  50. if six.PY3:
  51. long = int # pylint: disable=redefined-builtin,invalid-name
  52. # pylint: disable=g-import-not-at-top
  53. __all__ = ['MessageToString', 'Parse', 'PrintMessage', 'PrintField',
  54. 'PrintFieldValue', 'Merge', 'MessageToBytes']
  55. _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
  56. type_checkers.Int32ValueChecker(),
  57. type_checkers.Uint64ValueChecker(),
  58. type_checkers.Int64ValueChecker())
  59. _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?$', re.IGNORECASE)
  60. _FLOAT_NAN = re.compile('nanf?$', re.IGNORECASE)
  61. _QUOTES = frozenset(("'", '"'))
  62. _ANY_FULL_TYPE_NAME = 'google.protobuf.Any'
  63. class Error(Exception):
  64. """Top-level module error for text_format."""
  65. class ParseError(Error):
  66. """Thrown in case of text parsing or tokenizing error."""
  67. def __init__(self, message=None, line=None, column=None):
  68. if message is not None and line is not None:
  69. loc = str(line)
  70. if column is not None:
  71. loc += ':{0}'.format(column)
  72. message = '{0} : {1}'.format(loc, message)
  73. if message is not None:
  74. super(ParseError, self).__init__(message)
  75. else:
  76. super(ParseError, self).__init__()
  77. self._line = line
  78. self._column = column
  79. def GetLine(self):
  80. return self._line
  81. def GetColumn(self):
  82. return self._column
  83. class TextWriter(object):
  84. def __init__(self, as_utf8):
  85. if six.PY2:
  86. self._writer = io.BytesIO()
  87. else:
  88. self._writer = io.StringIO()
  89. def write(self, val):
  90. if six.PY2:
  91. if isinstance(val, six.text_type):
  92. val = val.encode('utf-8')
  93. return self._writer.write(val)
  94. def close(self):
  95. return self._writer.close()
  96. def getvalue(self):
  97. return self._writer.getvalue()
  98. def MessageToString(
  99. message,
  100. as_utf8=False,
  101. as_one_line=False,
  102. use_short_repeated_primitives=False,
  103. pointy_brackets=False,
  104. use_index_order=False,
  105. float_format=None,
  106. double_format=None,
  107. use_field_number=False,
  108. descriptor_pool=None,
  109. indent=0,
  110. message_formatter=None,
  111. print_unknown_fields=False,
  112. force_colon=False):
  113. # type: (...) -> str
  114. """Convert protobuf message to text format.
  115. Double values can be formatted compactly with 15 digits of
  116. precision (which is the most that IEEE 754 "double" can guarantee)
  117. using double_format='.15g'. To ensure that converting to text and back to a
  118. proto will result in an identical value, double_format='.17g' should be used.
  119. Args:
  120. message: The protocol buffers message.
  121. as_utf8: Return unescaped Unicode for non-ASCII characters.
  122. In Python 3 actual Unicode characters may appear as is in strings.
  123. In Python 2 the return value will be valid UTF-8 rather than only ASCII.
  124. as_one_line: Don't introduce newlines between fields.
  125. use_short_repeated_primitives: Use short repeated format for primitives.
  126. pointy_brackets: If True, use angle brackets instead of curly braces for
  127. nesting.
  128. use_index_order: If True, fields of a proto message will be printed using
  129. the order defined in source code instead of the field number, extensions
  130. will be printed at the end of the message and their relative order is
  131. determined by the extension number. By default, use the field number
  132. order.
  133. float_format (str): If set, use this to specify float field formatting
  134. (per the "Format Specification Mini-Language"); otherwise, shortest float
  135. that has same value in wire will be printed. Also affect double field
  136. if double_format is not set but float_format is set.
  137. double_format (str): If set, use this to specify double field formatting
  138. (per the "Format Specification Mini-Language"); if it is not set but
  139. float_format is set, use float_format. Otherwise, use ``str()``
  140. use_field_number: If True, print field numbers instead of names.
  141. descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
  142. indent (int): The initial indent level, in terms of spaces, for pretty
  143. print.
  144. message_formatter (function(message, indent, as_one_line) -> unicode|None):
  145. Custom formatter for selected sub-messages (usually based on message
  146. type). Use to pretty print parts of the protobuf for easier diffing.
  147. print_unknown_fields: If True, unknown fields will be printed.
  148. force_colon: If set, a colon will be added after the field name even if the
  149. field is a proto message.
  150. Returns:
  151. str: A string of the text formatted protocol buffer message.
  152. """
  153. out = TextWriter(as_utf8)
  154. printer = _Printer(
  155. out,
  156. indent,
  157. as_utf8,
  158. as_one_line,
  159. use_short_repeated_primitives,
  160. pointy_brackets,
  161. use_index_order,
  162. float_format,
  163. double_format,
  164. use_field_number,
  165. descriptor_pool,
  166. message_formatter,
  167. print_unknown_fields=print_unknown_fields,
  168. force_colon=force_colon)
  169. printer.PrintMessage(message)
  170. result = out.getvalue()
  171. out.close()
  172. if as_one_line:
  173. return result.rstrip()
  174. return result
  175. def MessageToBytes(message, **kwargs):
  176. # type: (...) -> bytes
  177. """Convert protobuf message to encoded text format. See MessageToString."""
  178. text = MessageToString(message, **kwargs)
  179. if isinstance(text, bytes):
  180. return text
  181. codec = 'utf-8' if kwargs.get('as_utf8') else 'ascii'
  182. return text.encode(codec)
  183. def _IsMapEntry(field):
  184. return (field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  185. field.message_type.has_options and
  186. field.message_type.GetOptions().map_entry)
  187. def PrintMessage(message,
  188. out,
  189. indent=0,
  190. as_utf8=False,
  191. as_one_line=False,
  192. use_short_repeated_primitives=False,
  193. pointy_brackets=False,
  194. use_index_order=False,
  195. float_format=None,
  196. double_format=None,
  197. use_field_number=False,
  198. descriptor_pool=None,
  199. message_formatter=None,
  200. print_unknown_fields=False,
  201. force_colon=False):
  202. printer = _Printer(
  203. out=out, indent=indent, as_utf8=as_utf8,
  204. as_one_line=as_one_line,
  205. use_short_repeated_primitives=use_short_repeated_primitives,
  206. pointy_brackets=pointy_brackets,
  207. use_index_order=use_index_order,
  208. float_format=float_format,
  209. double_format=double_format,
  210. use_field_number=use_field_number,
  211. descriptor_pool=descriptor_pool,
  212. message_formatter=message_formatter,
  213. print_unknown_fields=print_unknown_fields,
  214. force_colon=force_colon)
  215. printer.PrintMessage(message)
  216. def PrintField(field,
  217. value,
  218. out,
  219. indent=0,
  220. as_utf8=False,
  221. as_one_line=False,
  222. use_short_repeated_primitives=False,
  223. pointy_brackets=False,
  224. use_index_order=False,
  225. float_format=None,
  226. double_format=None,
  227. message_formatter=None,
  228. print_unknown_fields=False,
  229. force_colon=False):
  230. """Print a single field name/value pair."""
  231. printer = _Printer(out, indent, as_utf8, as_one_line,
  232. use_short_repeated_primitives, pointy_brackets,
  233. use_index_order, float_format, double_format,
  234. message_formatter=message_formatter,
  235. print_unknown_fields=print_unknown_fields,
  236. force_colon=force_colon)
  237. printer.PrintField(field, value)
  238. def PrintFieldValue(field,
  239. value,
  240. out,
  241. indent=0,
  242. as_utf8=False,
  243. as_one_line=False,
  244. use_short_repeated_primitives=False,
  245. pointy_brackets=False,
  246. use_index_order=False,
  247. float_format=None,
  248. double_format=None,
  249. message_formatter=None,
  250. print_unknown_fields=False,
  251. force_colon=False):
  252. """Print a single field value (not including name)."""
  253. printer = _Printer(out, indent, as_utf8, as_one_line,
  254. use_short_repeated_primitives, pointy_brackets,
  255. use_index_order, float_format, double_format,
  256. message_formatter=message_formatter,
  257. print_unknown_fields=print_unknown_fields,
  258. force_colon=force_colon)
  259. printer.PrintFieldValue(field, value)
  260. def _BuildMessageFromTypeName(type_name, descriptor_pool):
  261. """Returns a protobuf message instance.
  262. Args:
  263. type_name: Fully-qualified protobuf message type name string.
  264. descriptor_pool: DescriptorPool instance.
  265. Returns:
  266. A Message instance of type matching type_name, or None if the a Descriptor
  267. wasn't found matching type_name.
  268. """
  269. # pylint: disable=g-import-not-at-top
  270. if descriptor_pool is None:
  271. from google.protobuf import descriptor_pool as pool_mod
  272. descriptor_pool = pool_mod.Default()
  273. from google.protobuf import symbol_database
  274. database = symbol_database.Default()
  275. try:
  276. message_descriptor = descriptor_pool.FindMessageTypeByName(type_name)
  277. except KeyError:
  278. return None
  279. message_type = database.GetPrototype(message_descriptor)
  280. return message_type()
  281. # These values must match WireType enum in google/protobuf/wire_format.h.
  282. WIRETYPE_LENGTH_DELIMITED = 2
  283. WIRETYPE_START_GROUP = 3
  284. class _Printer(object):
  285. """Text format printer for protocol message."""
  286. def __init__(
  287. self,
  288. out,
  289. indent=0,
  290. as_utf8=False,
  291. as_one_line=False,
  292. use_short_repeated_primitives=False,
  293. pointy_brackets=False,
  294. use_index_order=False,
  295. float_format=None,
  296. double_format=None,
  297. use_field_number=False,
  298. descriptor_pool=None,
  299. message_formatter=None,
  300. print_unknown_fields=False,
  301. force_colon=False):
  302. """Initialize the Printer.
  303. Double values can be formatted compactly with 15 digits of precision
  304. (which is the most that IEEE 754 "double" can guarantee) using
  305. double_format='.15g'. To ensure that converting to text and back to a proto
  306. will result in an identical value, double_format='.17g' should be used.
  307. Args:
  308. out: To record the text format result.
  309. indent: The initial indent level for pretty print.
  310. as_utf8: Return unescaped Unicode for non-ASCII characters.
  311. In Python 3 actual Unicode characters may appear as is in strings.
  312. In Python 2 the return value will be valid UTF-8 rather than ASCII.
  313. as_one_line: Don't introduce newlines between fields.
  314. use_short_repeated_primitives: Use short repeated format for primitives.
  315. pointy_brackets: If True, use angle brackets instead of curly braces for
  316. nesting.
  317. use_index_order: If True, print fields of a proto message using the order
  318. defined in source code instead of the field number. By default, use the
  319. field number order.
  320. float_format: If set, use this to specify float field formatting
  321. (per the "Format Specification Mini-Language"); otherwise, shortest
  322. float that has same value in wire will be printed. Also affect double
  323. field if double_format is not set but float_format is set.
  324. double_format: If set, use this to specify double field formatting
  325. (per the "Format Specification Mini-Language"); if it is not set but
  326. float_format is set, use float_format. Otherwise, str() is used.
  327. use_field_number: If True, print field numbers instead of names.
  328. descriptor_pool: A DescriptorPool used to resolve Any types.
  329. message_formatter: A function(message, indent, as_one_line): unicode|None
  330. to custom format selected sub-messages (usually based on message type).
  331. Use to pretty print parts of the protobuf for easier diffing.
  332. print_unknown_fields: If True, unknown fields will be printed.
  333. force_colon: If set, a colon will be added after the field name even if
  334. the field is a proto message.
  335. """
  336. self.out = out
  337. self.indent = indent
  338. self.as_utf8 = as_utf8
  339. self.as_one_line = as_one_line
  340. self.use_short_repeated_primitives = use_short_repeated_primitives
  341. self.pointy_brackets = pointy_brackets
  342. self.use_index_order = use_index_order
  343. self.float_format = float_format
  344. if double_format is not None:
  345. self.double_format = double_format
  346. else:
  347. self.double_format = float_format
  348. self.use_field_number = use_field_number
  349. self.descriptor_pool = descriptor_pool
  350. self.message_formatter = message_formatter
  351. self.print_unknown_fields = print_unknown_fields
  352. self.force_colon = force_colon
  353. def _TryPrintAsAnyMessage(self, message):
  354. """Serializes if message is a google.protobuf.Any field."""
  355. if '/' not in message.type_url:
  356. return False
  357. packed_message = _BuildMessageFromTypeName(message.TypeName(),
  358. self.descriptor_pool)
  359. if packed_message:
  360. packed_message.MergeFromString(message.value)
  361. colon = ':' if self.force_colon else ''
  362. self.out.write('%s[%s]%s ' % (self.indent * ' ', message.type_url, colon))
  363. self._PrintMessageFieldValue(packed_message)
  364. self.out.write(' ' if self.as_one_line else '\n')
  365. return True
  366. else:
  367. return False
  368. def _TryCustomFormatMessage(self, message):
  369. formatted = self.message_formatter(message, self.indent, self.as_one_line)
  370. if formatted is None:
  371. return False
  372. out = self.out
  373. out.write(' ' * self.indent)
  374. out.write(formatted)
  375. out.write(' ' if self.as_one_line else '\n')
  376. return True
  377. def PrintMessage(self, message):
  378. """Convert protobuf message to text format.
  379. Args:
  380. message: The protocol buffers message.
  381. """
  382. if self.message_formatter and self._TryCustomFormatMessage(message):
  383. return
  384. if (message.DESCRIPTOR.full_name == _ANY_FULL_TYPE_NAME and
  385. self._TryPrintAsAnyMessage(message)):
  386. return
  387. fields = message.ListFields()
  388. if self.use_index_order:
  389. fields.sort(
  390. key=lambda x: x[0].number if x[0].is_extension else x[0].index)
  391. for field, value in fields:
  392. if _IsMapEntry(field):
  393. for key in sorted(value):
  394. # This is slow for maps with submessage entries because it copies the
  395. # entire tree. Unfortunately this would take significant refactoring
  396. # of this file to work around.
  397. #
  398. # TODO(haberman): refactor and optimize if this becomes an issue.
  399. entry_submsg = value.GetEntryClass()(key=key, value=value[key])
  400. self.PrintField(field, entry_submsg)
  401. elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  402. if (self.use_short_repeated_primitives
  403. and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE
  404. and field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_STRING):
  405. self._PrintShortRepeatedPrimitivesValue(field, value)
  406. else:
  407. for element in value:
  408. self.PrintField(field, element)
  409. else:
  410. self.PrintField(field, value)
  411. if self.print_unknown_fields:
  412. self._PrintUnknownFields(message.UnknownFields())
  413. def _PrintUnknownFields(self, unknown_fields):
  414. """Print unknown fields."""
  415. out = self.out
  416. for field in unknown_fields:
  417. out.write(' ' * self.indent)
  418. out.write(str(field.field_number))
  419. if field.wire_type == WIRETYPE_START_GROUP:
  420. if self.as_one_line:
  421. out.write(' { ')
  422. else:
  423. out.write(' {\n')
  424. self.indent += 2
  425. self._PrintUnknownFields(field.data)
  426. if self.as_one_line:
  427. out.write('} ')
  428. else:
  429. self.indent -= 2
  430. out.write(' ' * self.indent + '}\n')
  431. elif field.wire_type == WIRETYPE_LENGTH_DELIMITED:
  432. try:
  433. # If this field is parseable as a Message, it is probably
  434. # an embedded message.
  435. # pylint: disable=protected-access
  436. (embedded_unknown_message, pos) = decoder._DecodeUnknownFieldSet(
  437. memoryview(field.data), 0, len(field.data))
  438. except Exception: # pylint: disable=broad-except
  439. pos = 0
  440. if pos == len(field.data):
  441. if self.as_one_line:
  442. out.write(' { ')
  443. else:
  444. out.write(' {\n')
  445. self.indent += 2
  446. self._PrintUnknownFields(embedded_unknown_message)
  447. if self.as_one_line:
  448. out.write('} ')
  449. else:
  450. self.indent -= 2
  451. out.write(' ' * self.indent + '}\n')
  452. else:
  453. # A string or bytes field. self.as_utf8 may not work.
  454. out.write(': \"')
  455. out.write(text_encoding.CEscape(field.data, False))
  456. out.write('\" ' if self.as_one_line else '\"\n')
  457. else:
  458. # varint, fixed32, fixed64
  459. out.write(': ')
  460. out.write(str(field.data))
  461. out.write(' ' if self.as_one_line else '\n')
  462. def _PrintFieldName(self, field):
  463. """Print field name."""
  464. out = self.out
  465. out.write(' ' * self.indent)
  466. if self.use_field_number:
  467. out.write(str(field.number))
  468. else:
  469. if field.is_extension:
  470. out.write('[')
  471. if (field.containing_type.GetOptions().message_set_wire_format and
  472. field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
  473. field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
  474. out.write(field.message_type.full_name)
  475. else:
  476. out.write(field.full_name)
  477. out.write(']')
  478. elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
  479. # For groups, use the capitalized name.
  480. out.write(field.message_type.name)
  481. else:
  482. out.write(field.name)
  483. if (self.force_colon or
  484. field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE):
  485. # The colon is optional in this case, but our cross-language golden files
  486. # don't include it. Here, the colon is only included if force_colon is
  487. # set to True
  488. out.write(':')
  489. def PrintField(self, field, value):
  490. """Print a single field name/value pair."""
  491. self._PrintFieldName(field)
  492. self.out.write(' ')
  493. self.PrintFieldValue(field, value)
  494. self.out.write(' ' if self.as_one_line else '\n')
  495. def _PrintShortRepeatedPrimitivesValue(self, field, value):
  496. """"Prints short repeated primitives value."""
  497. # Note: this is called only when value has at least one element.
  498. self._PrintFieldName(field)
  499. self.out.write(' [')
  500. for i in six.moves.range(len(value) - 1):
  501. self.PrintFieldValue(field, value[i])
  502. self.out.write(', ')
  503. self.PrintFieldValue(field, value[-1])
  504. self.out.write(']')
  505. self.out.write(' ' if self.as_one_line else '\n')
  506. def _PrintMessageFieldValue(self, value):
  507. if self.pointy_brackets:
  508. openb = '<'
  509. closeb = '>'
  510. else:
  511. openb = '{'
  512. closeb = '}'
  513. if self.as_one_line:
  514. self.out.write('%s ' % openb)
  515. self.PrintMessage(value)
  516. self.out.write(closeb)
  517. else:
  518. self.out.write('%s\n' % openb)
  519. self.indent += 2
  520. self.PrintMessage(value)
  521. self.indent -= 2
  522. self.out.write(' ' * self.indent + closeb)
  523. def PrintFieldValue(self, field, value):
  524. """Print a single field value (not including name).
  525. For repeated fields, the value should be a single element.
  526. Args:
  527. field: The descriptor of the field to be printed.
  528. value: The value of the field.
  529. """
  530. out = self.out
  531. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  532. self._PrintMessageFieldValue(value)
  533. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
  534. enum_value = field.enum_type.values_by_number.get(value, None)
  535. if enum_value is not None:
  536. out.write(enum_value.name)
  537. else:
  538. out.write(str(value))
  539. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
  540. out.write('\"')
  541. if isinstance(value, six.text_type) and (six.PY2 or not self.as_utf8):
  542. out_value = value.encode('utf-8')
  543. else:
  544. out_value = value
  545. if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  546. # We always need to escape all binary data in TYPE_BYTES fields.
  547. out_as_utf8 = False
  548. else:
  549. out_as_utf8 = self.as_utf8
  550. out.write(text_encoding.CEscape(out_value, out_as_utf8))
  551. out.write('\"')
  552. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
  553. if value:
  554. out.write('true')
  555. else:
  556. out.write('false')
  557. elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_FLOAT:
  558. if self.float_format is not None:
  559. out.write('{1:{0}}'.format(self.float_format, value))
  560. else:
  561. if math.isnan(value):
  562. out.write(str(value))
  563. else:
  564. out.write(str(type_checkers.ToShortestFloat(value)))
  565. elif (field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_DOUBLE and
  566. self.double_format is not None):
  567. out.write('{1:{0}}'.format(self.double_format, value))
  568. else:
  569. out.write(str(value))
  570. def Parse(text,
  571. message,
  572. allow_unknown_extension=False,
  573. allow_field_number=False,
  574. descriptor_pool=None,
  575. allow_unknown_field=False):
  576. """Parses a text representation of a protocol message into a message.
  577. NOTE: for historical reasons this function does not clear the input
  578. message. This is different from what the binary msg.ParseFrom(...) does.
  579. If text contains a field already set in message, the value is appended if the
  580. field is repeated. Otherwise, an error is raised.
  581. Example::
  582. a = MyProto()
  583. a.repeated_field.append('test')
  584. b = MyProto()
  585. # Repeated fields are combined
  586. text_format.Parse(repr(a), b)
  587. text_format.Parse(repr(a), b) # repeated_field contains ["test", "test"]
  588. # Non-repeated fields cannot be overwritten
  589. a.singular_field = 1
  590. b.singular_field = 2
  591. text_format.Parse(repr(a), b) # ParseError
  592. # Binary version:
  593. b.ParseFromString(a.SerializeToString()) # repeated_field is now "test"
  594. Caller is responsible for clearing the message as needed.
  595. Args:
  596. text (str): Message text representation.
  597. message (Message): A protocol buffer message to merge into.
  598. allow_unknown_extension: if True, skip over missing extensions and keep
  599. parsing
  600. allow_field_number: if True, both field number and field name are allowed.
  601. descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
  602. allow_unknown_field: if True, skip over unknown field and keep
  603. parsing. Avoid to use this option if possible. It may hide some
  604. errors (e.g. spelling error on field name)
  605. Returns:
  606. Message: The same message passed as argument.
  607. Raises:
  608. ParseError: On text parsing problems.
  609. """
  610. return ParseLines(text.split(b'\n' if isinstance(text, bytes) else u'\n'),
  611. message,
  612. allow_unknown_extension,
  613. allow_field_number,
  614. descriptor_pool=descriptor_pool,
  615. allow_unknown_field=allow_unknown_field)
  616. def Merge(text,
  617. message,
  618. allow_unknown_extension=False,
  619. allow_field_number=False,
  620. descriptor_pool=None,
  621. allow_unknown_field=False):
  622. """Parses a text representation of a protocol message into a message.
  623. Like Parse(), but allows repeated values for a non-repeated field, and uses
  624. the last one. This means any non-repeated, top-level fields specified in text
  625. replace those in the message.
  626. Args:
  627. text (str): Message text representation.
  628. message (Message): A protocol buffer message to merge into.
  629. allow_unknown_extension: if True, skip over missing extensions and keep
  630. parsing
  631. allow_field_number: if True, both field number and field name are allowed.
  632. descriptor_pool (DescriptorPool): Descriptor pool used to resolve Any types.
  633. allow_unknown_field: if True, skip over unknown field and keep
  634. parsing. Avoid to use this option if possible. It may hide some
  635. errors (e.g. spelling error on field name)
  636. Returns:
  637. Message: The same message passed as argument.
  638. Raises:
  639. ParseError: On text parsing problems.
  640. """
  641. return MergeLines(
  642. text.split(b'\n' if isinstance(text, bytes) else u'\n'),
  643. message,
  644. allow_unknown_extension,
  645. allow_field_number,
  646. descriptor_pool=descriptor_pool,
  647. allow_unknown_field=allow_unknown_field)
  648. def ParseLines(lines,
  649. message,
  650. allow_unknown_extension=False,
  651. allow_field_number=False,
  652. descriptor_pool=None,
  653. allow_unknown_field=False):
  654. """Parses a text representation of a protocol message into a message.
  655. See Parse() for caveats.
  656. Args:
  657. lines: An iterable of lines of a message's text representation.
  658. message: A protocol buffer message to merge into.
  659. allow_unknown_extension: if True, skip over missing extensions and keep
  660. parsing
  661. allow_field_number: if True, both field number and field name are allowed.
  662. descriptor_pool: A DescriptorPool used to resolve Any types.
  663. allow_unknown_field: if True, skip over unknown field and keep
  664. parsing. Avoid to use this option if possible. It may hide some
  665. errors (e.g. spelling error on field name)
  666. Returns:
  667. The same message passed as argument.
  668. Raises:
  669. ParseError: On text parsing problems.
  670. """
  671. parser = _Parser(allow_unknown_extension,
  672. allow_field_number,
  673. descriptor_pool=descriptor_pool,
  674. allow_unknown_field=allow_unknown_field)
  675. return parser.ParseLines(lines, message)
  676. def MergeLines(lines,
  677. message,
  678. allow_unknown_extension=False,
  679. allow_field_number=False,
  680. descriptor_pool=None,
  681. allow_unknown_field=False):
  682. """Parses a text representation of a protocol message into a message.
  683. See Merge() for more details.
  684. Args:
  685. lines: An iterable of lines of a message's text representation.
  686. message: A protocol buffer message to merge into.
  687. allow_unknown_extension: if True, skip over missing extensions and keep
  688. parsing
  689. allow_field_number: if True, both field number and field name are allowed.
  690. descriptor_pool: A DescriptorPool used to resolve Any types.
  691. allow_unknown_field: if True, skip over unknown field and keep
  692. parsing. Avoid to use this option if possible. It may hide some
  693. errors (e.g. spelling error on field name)
  694. Returns:
  695. The same message passed as argument.
  696. Raises:
  697. ParseError: On text parsing problems.
  698. """
  699. parser = _Parser(allow_unknown_extension,
  700. allow_field_number,
  701. descriptor_pool=descriptor_pool,
  702. allow_unknown_field=allow_unknown_field)
  703. return parser.MergeLines(lines, message)
  704. class _Parser(object):
  705. """Text format parser for protocol message."""
  706. def __init__(self,
  707. allow_unknown_extension=False,
  708. allow_field_number=False,
  709. descriptor_pool=None,
  710. allow_unknown_field=False):
  711. self.allow_unknown_extension = allow_unknown_extension
  712. self.allow_field_number = allow_field_number
  713. self.descriptor_pool = descriptor_pool
  714. self.allow_unknown_field = allow_unknown_field
  715. def ParseLines(self, lines, message):
  716. """Parses a text representation of a protocol message into a message."""
  717. self._allow_multiple_scalars = False
  718. self._ParseOrMerge(lines, message)
  719. return message
  720. def MergeLines(self, lines, message):
  721. """Merges a text representation of a protocol message into a message."""
  722. self._allow_multiple_scalars = True
  723. self._ParseOrMerge(lines, message)
  724. return message
  725. def _ParseOrMerge(self, lines, message):
  726. """Converts a text representation of a protocol message into a message.
  727. Args:
  728. lines: Lines of a message's text representation.
  729. message: A protocol buffer message to merge into.
  730. Raises:
  731. ParseError: On text parsing problems.
  732. """
  733. # Tokenize expects native str lines.
  734. if six.PY2:
  735. str_lines = (line if isinstance(line, str) else line.encode('utf-8')
  736. for line in lines)
  737. else:
  738. str_lines = (line if isinstance(line, str) else line.decode('utf-8')
  739. for line in lines)
  740. tokenizer = Tokenizer(str_lines)
  741. while not tokenizer.AtEnd():
  742. self._MergeField(tokenizer, message)
  743. def _MergeField(self, tokenizer, message):
  744. """Merges a single protocol message field into a message.
  745. Args:
  746. tokenizer: A tokenizer to parse the field name and values.
  747. message: A protocol message to record the data.
  748. Raises:
  749. ParseError: In case of text parsing problems.
  750. """
  751. message_descriptor = message.DESCRIPTOR
  752. if (message_descriptor.full_name == _ANY_FULL_TYPE_NAME and
  753. tokenizer.TryConsume('[')):
  754. type_url_prefix, packed_type_name = self._ConsumeAnyTypeUrl(tokenizer)
  755. tokenizer.Consume(']')
  756. tokenizer.TryConsume(':')
  757. if tokenizer.TryConsume('<'):
  758. expanded_any_end_token = '>'
  759. else:
  760. tokenizer.Consume('{')
  761. expanded_any_end_token = '}'
  762. expanded_any_sub_message = _BuildMessageFromTypeName(packed_type_name,
  763. self.descriptor_pool)
  764. if not expanded_any_sub_message:
  765. raise ParseError('Type %s not found in descriptor pool' %
  766. packed_type_name)
  767. while not tokenizer.TryConsume(expanded_any_end_token):
  768. if tokenizer.AtEnd():
  769. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' %
  770. (expanded_any_end_token,))
  771. self._MergeField(tokenizer, expanded_any_sub_message)
  772. deterministic = False
  773. message.Pack(expanded_any_sub_message,
  774. type_url_prefix=type_url_prefix,
  775. deterministic=deterministic)
  776. return
  777. if tokenizer.TryConsume('['):
  778. name = [tokenizer.ConsumeIdentifier()]
  779. while tokenizer.TryConsume('.'):
  780. name.append(tokenizer.ConsumeIdentifier())
  781. name = '.'.join(name)
  782. if not message_descriptor.is_extendable:
  783. raise tokenizer.ParseErrorPreviousToken(
  784. 'Message type "%s" does not have extensions.' %
  785. message_descriptor.full_name)
  786. # pylint: disable=protected-access
  787. field = message.Extensions._FindExtensionByName(name)
  788. # pylint: enable=protected-access
  789. if not field:
  790. if self.allow_unknown_extension:
  791. field = None
  792. else:
  793. raise tokenizer.ParseErrorPreviousToken(
  794. 'Extension "%s" not registered. '
  795. 'Did you import the _pb2 module which defines it? '
  796. 'If you are trying to place the extension in the MessageSet '
  797. 'field of another message that is in an Any or MessageSet field, '
  798. 'that message\'s _pb2 module must be imported as well' % name)
  799. elif message_descriptor != field.containing_type:
  800. raise tokenizer.ParseErrorPreviousToken(
  801. 'Extension "%s" does not extend message type "%s".' %
  802. (name, message_descriptor.full_name))
  803. tokenizer.Consume(']')
  804. else:
  805. name = tokenizer.ConsumeIdentifierOrNumber()
  806. if self.allow_field_number and name.isdigit():
  807. number = ParseInteger(name, True, True)
  808. field = message_descriptor.fields_by_number.get(number, None)
  809. if not field and message_descriptor.is_extendable:
  810. field = message.Extensions._FindExtensionByNumber(number)
  811. else:
  812. field = message_descriptor.fields_by_name.get(name, None)
  813. # Group names are expected to be capitalized as they appear in the
  814. # .proto file, which actually matches their type names, not their field
  815. # names.
  816. if not field:
  817. field = message_descriptor.fields_by_name.get(name.lower(), None)
  818. if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
  819. field = None
  820. if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
  821. field.message_type.name != name):
  822. field = None
  823. if not field and not self.allow_unknown_field:
  824. raise tokenizer.ParseErrorPreviousToken(
  825. 'Message type "%s" has no field named "%s".' %
  826. (message_descriptor.full_name, name))
  827. if field:
  828. if not self._allow_multiple_scalars and field.containing_oneof:
  829. # Check if there's a different field set in this oneof.
  830. # Note that we ignore the case if the same field was set before, and we
  831. # apply _allow_multiple_scalars to non-scalar fields as well.
  832. which_oneof = message.WhichOneof(field.containing_oneof.name)
  833. if which_oneof is not None and which_oneof != field.name:
  834. raise tokenizer.ParseErrorPreviousToken(
  835. 'Field "%s" is specified along with field "%s", another member '
  836. 'of oneof "%s" for message type "%s".' %
  837. (field.name, which_oneof, field.containing_oneof.name,
  838. message_descriptor.full_name))
  839. if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  840. tokenizer.TryConsume(':')
  841. merger = self._MergeMessageField
  842. else:
  843. tokenizer.Consume(':')
  844. merger = self._MergeScalarField
  845. if (field.label == descriptor.FieldDescriptor.LABEL_REPEATED and
  846. tokenizer.TryConsume('[')):
  847. # Short repeated format, e.g. "foo: [1, 2, 3]"
  848. if not tokenizer.TryConsume(']'):
  849. while True:
  850. merger(tokenizer, message, field)
  851. if tokenizer.TryConsume(']'):
  852. break
  853. tokenizer.Consume(',')
  854. else:
  855. merger(tokenizer, message, field)
  856. else: # Proto field is unknown.
  857. assert (self.allow_unknown_extension or self.allow_unknown_field)
  858. _SkipFieldContents(tokenizer)
  859. # For historical reasons, fields may optionally be separated by commas or
  860. # semicolons.
  861. if not tokenizer.TryConsume(','):
  862. tokenizer.TryConsume(';')
  863. def _ConsumeAnyTypeUrl(self, tokenizer):
  864. """Consumes a google.protobuf.Any type URL and returns the type name."""
  865. # Consume "type.googleapis.com/".
  866. prefix = [tokenizer.ConsumeIdentifier()]
  867. tokenizer.Consume('.')
  868. prefix.append(tokenizer.ConsumeIdentifier())
  869. tokenizer.Consume('.')
  870. prefix.append(tokenizer.ConsumeIdentifier())
  871. tokenizer.Consume('/')
  872. # Consume the fully-qualified type name.
  873. name = [tokenizer.ConsumeIdentifier()]
  874. while tokenizer.TryConsume('.'):
  875. name.append(tokenizer.ConsumeIdentifier())
  876. return '.'.join(prefix), '.'.join(name)
  877. def _MergeMessageField(self, tokenizer, message, field):
  878. """Merges a single scalar field into a message.
  879. Args:
  880. tokenizer: A tokenizer to parse the field value.
  881. message: The message of which field is a member.
  882. field: The descriptor of the field to be merged.
  883. Raises:
  884. ParseError: In case of text parsing problems.
  885. """
  886. is_map_entry = _IsMapEntry(field)
  887. if tokenizer.TryConsume('<'):
  888. end_token = '>'
  889. else:
  890. tokenizer.Consume('{')
  891. end_token = '}'
  892. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  893. if field.is_extension:
  894. sub_message = message.Extensions[field].add()
  895. elif is_map_entry:
  896. sub_message = getattr(message, field.name).GetEntryClass()()
  897. else:
  898. sub_message = getattr(message, field.name).add()
  899. else:
  900. if field.is_extension:
  901. if (not self._allow_multiple_scalars and
  902. message.HasExtension(field)):
  903. raise tokenizer.ParseErrorPreviousToken(
  904. 'Message type "%s" should not have multiple "%s" extensions.' %
  905. (message.DESCRIPTOR.full_name, field.full_name))
  906. sub_message = message.Extensions[field]
  907. else:
  908. # Also apply _allow_multiple_scalars to message field.
  909. # TODO(jieluo): Change to _allow_singular_overwrites.
  910. if (not self._allow_multiple_scalars and
  911. message.HasField(field.name)):
  912. raise tokenizer.ParseErrorPreviousToken(
  913. 'Message type "%s" should not have multiple "%s" fields.' %
  914. (message.DESCRIPTOR.full_name, field.name))
  915. sub_message = getattr(message, field.name)
  916. sub_message.SetInParent()
  917. while not tokenizer.TryConsume(end_token):
  918. if tokenizer.AtEnd():
  919. raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token,))
  920. self._MergeField(tokenizer, sub_message)
  921. if is_map_entry:
  922. value_cpptype = field.message_type.fields_by_name['value'].cpp_type
  923. if value_cpptype == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
  924. value = getattr(message, field.name)[sub_message.key]
  925. value.CopyFrom(sub_message.value)
  926. else:
  927. getattr(message, field.name)[sub_message.key] = sub_message.value
  928. @staticmethod
  929. def _IsProto3Syntax(message):
  930. message_descriptor = message.DESCRIPTOR
  931. return (hasattr(message_descriptor, 'syntax') and
  932. message_descriptor.syntax == 'proto3')
  933. def _MergeScalarField(self, tokenizer, message, field):
  934. """Merges a single scalar field into a message.
  935. Args:
  936. tokenizer: A tokenizer to parse the field value.
  937. message: A protocol message to record the data.
  938. field: The descriptor of the field to be merged.
  939. Raises:
  940. ParseError: In case of text parsing problems.
  941. RuntimeError: On runtime errors.
  942. """
  943. _ = self.allow_unknown_extension
  944. value = None
  945. if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
  946. descriptor.FieldDescriptor.TYPE_SINT32,
  947. descriptor.FieldDescriptor.TYPE_SFIXED32):
  948. value = _ConsumeInt32(tokenizer)
  949. elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
  950. descriptor.FieldDescriptor.TYPE_SINT64,
  951. descriptor.FieldDescriptor.TYPE_SFIXED64):
  952. value = _ConsumeInt64(tokenizer)
  953. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
  954. descriptor.FieldDescriptor.TYPE_FIXED32):
  955. value = _ConsumeUint32(tokenizer)
  956. elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
  957. descriptor.FieldDescriptor.TYPE_FIXED64):
  958. value = _ConsumeUint64(tokenizer)
  959. elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
  960. descriptor.FieldDescriptor.TYPE_DOUBLE):
  961. value = tokenizer.ConsumeFloat()
  962. elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
  963. value = tokenizer.ConsumeBool()
  964. elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
  965. value = tokenizer.ConsumeString()
  966. elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
  967. value = tokenizer.ConsumeByteString()
  968. elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
  969. value = tokenizer.ConsumeEnum(field)
  970. else:
  971. raise RuntimeError('Unknown field type %d' % field.type)
  972. if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
  973. if field.is_extension:
  974. message.Extensions[field].append(value)
  975. else:
  976. getattr(message, field.name).append(value)
  977. else:
  978. if field.is_extension:
  979. if (not self._allow_multiple_scalars and
  980. not self._IsProto3Syntax(message) and
  981. message.HasExtension(field)):
  982. raise tokenizer.ParseErrorPreviousToken(
  983. 'Message type "%s" should not have multiple "%s" extensions.' %
  984. (message.DESCRIPTOR.full_name, field.full_name))
  985. else:
  986. message.Extensions[field] = value
  987. else:
  988. duplicate_error = False
  989. if not self._allow_multiple_scalars:
  990. if self._IsProto3Syntax(message):
  991. # Proto3 doesn't represent presence so we try best effort to check
  992. # multiple scalars by compare to default values.
  993. duplicate_error = bool(getattr(message, field.name))
  994. else:
  995. duplicate_error = message.HasField(field.name)
  996. if duplicate_error:
  997. raise tokenizer.ParseErrorPreviousToken(
  998. 'Message type "%s" should not have multiple "%s" fields.' %
  999. (message.DESCRIPTOR.full_name, field.name))
  1000. else:
  1001. setattr(message, field.name, value)
  1002. def _SkipFieldContents(tokenizer):
  1003. """Skips over contents (value or message) of a field.
  1004. Args:
  1005. tokenizer: A tokenizer to parse the field name and values.
  1006. """
  1007. # Try to guess the type of this field.
  1008. # If this field is not a message, there should be a ":" between the
  1009. # field name and the field value and also the field value should not
  1010. # start with "{" or "<" which indicates the beginning of a message body.
  1011. # If there is no ":" or there is a "{" or "<" after ":", this field has
  1012. # to be a message or the input is ill-formed.
  1013. if tokenizer.TryConsume(':') and not tokenizer.LookingAt(
  1014. '{') and not tokenizer.LookingAt('<'):
  1015. _SkipFieldValue(tokenizer)
  1016. else:
  1017. _SkipFieldMessage(tokenizer)
  1018. def _SkipField(tokenizer):
  1019. """Skips over a complete field (name and value/message).
  1020. Args:
  1021. tokenizer: A tokenizer to parse the field name and values.
  1022. """
  1023. if tokenizer.TryConsume('['):
  1024. # Consume extension name.
  1025. tokenizer.ConsumeIdentifier()
  1026. while tokenizer.TryConsume('.'):
  1027. tokenizer.ConsumeIdentifier()
  1028. tokenizer.Consume(']')
  1029. else:
  1030. tokenizer.ConsumeIdentifierOrNumber()
  1031. _SkipFieldContents(tokenizer)
  1032. # For historical reasons, fields may optionally be separated by commas or
  1033. # semicolons.
  1034. if not tokenizer.TryConsume(','):
  1035. tokenizer.TryConsume(';')
  1036. def _SkipFieldMessage(tokenizer):
  1037. """Skips over a field message.
  1038. Args:
  1039. tokenizer: A tokenizer to parse the field name and values.
  1040. """
  1041. if tokenizer.TryConsume('<'):
  1042. delimiter = '>'
  1043. else:
  1044. tokenizer.Consume('{')
  1045. delimiter = '}'
  1046. while not tokenizer.LookingAt('>') and not tokenizer.LookingAt('}'):
  1047. _SkipField(tokenizer)
  1048. tokenizer.Consume(delimiter)
  1049. def _SkipFieldValue(tokenizer):
  1050. """Skips over a field value.
  1051. Args:
  1052. tokenizer: A tokenizer to parse the field name and values.
  1053. Raises:
  1054. ParseError: In case an invalid field value is found.
  1055. """
  1056. # String/bytes tokens can come in multiple adjacent string literals.
  1057. # If we can consume one, consume as many as we can.
  1058. if tokenizer.TryConsumeByteString():
  1059. while tokenizer.TryConsumeByteString():
  1060. pass
  1061. return
  1062. if (not tokenizer.TryConsumeIdentifier() and
  1063. not _TryConsumeInt64(tokenizer) and not _TryConsumeUint64(tokenizer) and
  1064. not tokenizer.TryConsumeFloat()):
  1065. raise ParseError('Invalid field value: ' + tokenizer.token)
  1066. class Tokenizer(object):
  1067. """Protocol buffer text representation tokenizer.
  1068. This class handles the lower level string parsing by splitting it into
  1069. meaningful tokens.
  1070. It was directly ported from the Java protocol buffer API.
  1071. """
  1072. _WHITESPACE = re.compile(r'\s+')
  1073. _COMMENT = re.compile(r'(\s*#.*$)', re.MULTILINE)
  1074. _WHITESPACE_OR_COMMENT = re.compile(r'(\s|(#.*$))+', re.MULTILINE)
  1075. _TOKEN = re.compile('|'.join([
  1076. r'[a-zA-Z_][0-9a-zA-Z_+-]*', # an identifier
  1077. r'([0-9+-]|(\.[0-9]))[0-9a-zA-Z_.+-]*', # a number
  1078. ] + [ # quoted str for each quote mark
  1079. # Avoid backtracking! https://stackoverflow.com/a/844267
  1080. r'{qt}[^{qt}\n\\]*((\\.)+[^{qt}\n\\]*)*({qt}|\\?$)'.format(qt=mark)
  1081. for mark in _QUOTES
  1082. ]))
  1083. _IDENTIFIER = re.compile(r'[^\d\W]\w*')
  1084. _IDENTIFIER_OR_NUMBER = re.compile(r'\w+')
  1085. def __init__(self, lines, skip_comments=True):
  1086. self._position = 0
  1087. self._line = -1
  1088. self._column = 0
  1089. self._token_start = None
  1090. self.token = ''
  1091. self._lines = iter(lines)
  1092. self._current_line = ''
  1093. self._previous_line = 0
  1094. self._previous_column = 0
  1095. self._more_lines = True
  1096. self._skip_comments = skip_comments
  1097. self._whitespace_pattern = (skip_comments and self._WHITESPACE_OR_COMMENT
  1098. or self._WHITESPACE)
  1099. self._SkipWhitespace()
  1100. self.NextToken()
  1101. def LookingAt(self, token):
  1102. return self.token == token
  1103. def AtEnd(self):
  1104. """Checks the end of the text was reached.
  1105. Returns:
  1106. True iff the end was reached.
  1107. """
  1108. return not self.token
  1109. def _PopLine(self):
  1110. while len(self._current_line) <= self._column:
  1111. try:
  1112. self._current_line = next(self._lines)
  1113. except StopIteration:
  1114. self._current_line = ''
  1115. self._more_lines = False
  1116. return
  1117. else:
  1118. self._line += 1
  1119. self._column = 0
  1120. def _SkipWhitespace(self):
  1121. while True:
  1122. self._PopLine()
  1123. match = self._whitespace_pattern.match(self._current_line, self._column)
  1124. if not match:
  1125. break
  1126. length = len(match.group(0))
  1127. self._column += length
  1128. def TryConsume(self, token):
  1129. """Tries to consume a given piece of text.
  1130. Args:
  1131. token: Text to consume.
  1132. Returns:
  1133. True iff the text was consumed.
  1134. """
  1135. if self.token == token:
  1136. self.NextToken()
  1137. return True
  1138. return False
  1139. def Consume(self, token):
  1140. """Consumes a piece of text.
  1141. Args:
  1142. token: Text to consume.
  1143. Raises:
  1144. ParseError: If the text couldn't be consumed.
  1145. """
  1146. if not self.TryConsume(token):
  1147. raise self.ParseError('Expected "%s".' % token)
  1148. def ConsumeComment(self):
  1149. result = self.token
  1150. if not self._COMMENT.match(result):
  1151. raise self.ParseError('Expected comment.')
  1152. self.NextToken()
  1153. return result
  1154. def ConsumeCommentOrTrailingComment(self):
  1155. """Consumes a comment, returns a 2-tuple (trailing bool, comment str)."""
  1156. # Tokenizer initializes _previous_line and _previous_column to 0. As the
  1157. # tokenizer starts, it looks like there is a previous token on the line.
  1158. just_started = self._line == 0 and self._column == 0
  1159. before_parsing = self._previous_line
  1160. comment = self.ConsumeComment()
  1161. # A trailing comment is a comment on the same line than the previous token.
  1162. trailing = (self._previous_line == before_parsing
  1163. and not just_started)
  1164. return trailing, comment
  1165. def TryConsumeIdentifier(self):
  1166. try:
  1167. self.ConsumeIdentifier()
  1168. return True
  1169. except ParseError:
  1170. return False
  1171. def ConsumeIdentifier(self):
  1172. """Consumes protocol message field identifier.
  1173. Returns:
  1174. Identifier string.
  1175. Raises:
  1176. ParseError: If an identifier couldn't be consumed.
  1177. """
  1178. result = self.token
  1179. if not self._IDENTIFIER.match(result):
  1180. raise self.ParseError('Expected identifier.')
  1181. self.NextToken()
  1182. return result
  1183. def TryConsumeIdentifierOrNumber(self):
  1184. try:
  1185. self.ConsumeIdentifierOrNumber()
  1186. return True
  1187. except ParseError:
  1188. return False
  1189. def ConsumeIdentifierOrNumber(self):
  1190. """Consumes protocol message field identifier.
  1191. Returns:
  1192. Identifier string.
  1193. Raises:
  1194. ParseError: If an identifier couldn't be consumed.
  1195. """
  1196. result = self.token
  1197. if not self._IDENTIFIER_OR_NUMBER.match(result):
  1198. raise self.ParseError('Expected identifier or number, got %s.' % result)
  1199. self.NextToken()
  1200. return result
  1201. def TryConsumeInteger(self):
  1202. try:
  1203. # Note: is_long only affects value type, not whether an error is raised.
  1204. self.ConsumeInteger()
  1205. return True
  1206. except ParseError:
  1207. return False
  1208. def ConsumeInteger(self, is_long=False):
  1209. """Consumes an integer number.
  1210. Args:
  1211. is_long: True if the value should be returned as a long integer.
  1212. Returns:
  1213. The integer parsed.
  1214. Raises:
  1215. ParseError: If an integer couldn't be consumed.
  1216. """
  1217. try:
  1218. result = _ParseAbstractInteger(self.token, is_long=is_long)
  1219. except ValueError as e:
  1220. raise self.ParseError(str(e))
  1221. self.NextToken()
  1222. return result
  1223. def TryConsumeFloat(self):
  1224. try:
  1225. self.ConsumeFloat()
  1226. return True
  1227. except ParseError:
  1228. return False
  1229. def ConsumeFloat(self):
  1230. """Consumes an floating point number.
  1231. Returns:
  1232. The number parsed.
  1233. Raises:
  1234. ParseError: If a floating point number couldn't be consumed.
  1235. """
  1236. try:
  1237. result = ParseFloat(self.token)
  1238. except ValueError as e:
  1239. raise self.ParseError(str(e))
  1240. self.NextToken()
  1241. return result
  1242. def ConsumeBool(self):
  1243. """Consumes a boolean value.
  1244. Returns:
  1245. The bool parsed.
  1246. Raises:
  1247. ParseError: If a boolean value couldn't be consumed.
  1248. """
  1249. try:
  1250. result = ParseBool(self.token)
  1251. except ValueError as e:
  1252. raise self.ParseError(str(e))
  1253. self.NextToken()
  1254. return result
  1255. def TryConsumeByteString(self):
  1256. try:
  1257. self.ConsumeByteString()
  1258. return True
  1259. except ParseError:
  1260. return False
  1261. def ConsumeString(self):
  1262. """Consumes a string value.
  1263. Returns:
  1264. The string parsed.
  1265. Raises:
  1266. ParseError: If a string value couldn't be consumed.
  1267. """
  1268. the_bytes = self.ConsumeByteString()
  1269. try:
  1270. return six.text_type(the_bytes, 'utf-8')
  1271. except UnicodeDecodeError as e:
  1272. raise self._StringParseError(e)
  1273. def ConsumeByteString(self):
  1274. """Consumes a byte array value.
  1275. Returns:
  1276. The array parsed (as a string).
  1277. Raises:
  1278. ParseError: If a byte array value couldn't be consumed.
  1279. """
  1280. the_list = [self._ConsumeSingleByteString()]
  1281. while self.token and self.token[0] in _QUOTES:
  1282. the_list.append(self._ConsumeSingleByteString())
  1283. return b''.join(the_list)
  1284. def _ConsumeSingleByteString(self):
  1285. """Consume one token of a string literal.
  1286. String literals (whether bytes or text) can come in multiple adjacent
  1287. tokens which are automatically concatenated, like in C or Python. This
  1288. method only consumes one token.
  1289. Returns:
  1290. The token parsed.
  1291. Raises:
  1292. ParseError: When the wrong format data is found.
  1293. """
  1294. text = self.token
  1295. if len(text) < 1 or text[0] not in _QUOTES:
  1296. raise self.ParseError('Expected string but found: %r' % (text,))
  1297. if len(text) < 2 or text[-1] != text[0]:
  1298. raise self.ParseError('String missing ending quote: %r' % (text,))
  1299. try:
  1300. result = text_encoding.CUnescape(text[1:-1])
  1301. except ValueError as e:
  1302. raise self.ParseError(str(e))
  1303. self.NextToken()
  1304. return result
  1305. def ConsumeEnum(self, field):
  1306. try:
  1307. result = ParseEnum(field, self.token)
  1308. except ValueError as e:
  1309. raise self.ParseError(str(e))
  1310. self.NextToken()
  1311. return result
  1312. def ParseErrorPreviousToken(self, message):
  1313. """Creates and *returns* a ParseError for the previously read token.
  1314. Args:
  1315. message: A message to set for the exception.
  1316. Returns:
  1317. A ParseError instance.
  1318. """
  1319. return ParseError(message, self._previous_line + 1,
  1320. self._previous_column + 1)
  1321. def ParseError(self, message):
  1322. """Creates and *returns* a ParseError for the current token."""
  1323. return ParseError('\'' + self._current_line + '\': ' + message,
  1324. self._line + 1, self._column + 1)
  1325. def _StringParseError(self, e):
  1326. return self.ParseError('Couldn\'t parse string: ' + str(e))
  1327. def NextToken(self):
  1328. """Reads the next meaningful token."""
  1329. self._previous_line = self._line
  1330. self._previous_column = self._column
  1331. self._column += len(self.token)
  1332. self._SkipWhitespace()
  1333. if not self._more_lines:
  1334. self.token = ''
  1335. return
  1336. match = self._TOKEN.match(self._current_line, self._column)
  1337. if not match and not self._skip_comments:
  1338. match = self._COMMENT.match(self._current_line, self._column)
  1339. if match:
  1340. token = match.group(0)
  1341. self.token = token
  1342. else:
  1343. self.token = self._current_line[self._column]
  1344. # Aliased so it can still be accessed by current visibility violators.
  1345. # TODO(dbarnett): Migrate violators to textformat_tokenizer.
  1346. _Tokenizer = Tokenizer # pylint: disable=invalid-name
  1347. def _ConsumeInt32(tokenizer):
  1348. """Consumes a signed 32bit integer number from tokenizer.
  1349. Args:
  1350. tokenizer: A tokenizer used to parse the number.
  1351. Returns:
  1352. The integer parsed.
  1353. Raises:
  1354. ParseError: If a signed 32bit integer couldn't be consumed.
  1355. """
  1356. return _ConsumeInteger(tokenizer, is_signed=True, is_long=False)
  1357. def _ConsumeUint32(tokenizer):
  1358. """Consumes an unsigned 32bit integer number from tokenizer.
  1359. Args:
  1360. tokenizer: A tokenizer used to parse the number.
  1361. Returns:
  1362. The integer parsed.
  1363. Raises:
  1364. ParseError: If an unsigned 32bit integer couldn't be consumed.
  1365. """
  1366. return _ConsumeInteger(tokenizer, is_signed=False, is_long=False)
  1367. def _TryConsumeInt64(tokenizer):
  1368. try:
  1369. _ConsumeInt64(tokenizer)
  1370. return True
  1371. except ParseError:
  1372. return False
  1373. def _ConsumeInt64(tokenizer):
  1374. """Consumes a signed 32bit integer number from tokenizer.
  1375. Args:
  1376. tokenizer: A tokenizer used to parse the number.
  1377. Returns:
  1378. The integer parsed.
  1379. Raises:
  1380. ParseError: If a signed 32bit integer couldn't be consumed.
  1381. """
  1382. return _ConsumeInteger(tokenizer, is_signed=True, is_long=True)
  1383. def _TryConsumeUint64(tokenizer):
  1384. try:
  1385. _ConsumeUint64(tokenizer)
  1386. return True
  1387. except ParseError:
  1388. return False
  1389. def _ConsumeUint64(tokenizer):
  1390. """Consumes an unsigned 64bit integer number from tokenizer.
  1391. Args:
  1392. tokenizer: A tokenizer used to parse the number.
  1393. Returns:
  1394. The integer parsed.
  1395. Raises:
  1396. ParseError: If an unsigned 64bit integer couldn't be consumed.
  1397. """
  1398. return _ConsumeInteger(tokenizer, is_signed=False, is_long=True)
  1399. def _TryConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1400. try:
  1401. _ConsumeInteger(tokenizer, is_signed=is_signed, is_long=is_long)
  1402. return True
  1403. except ParseError:
  1404. return False
  1405. def _ConsumeInteger(tokenizer, is_signed=False, is_long=False):
  1406. """Consumes an integer number from tokenizer.
  1407. Args:
  1408. tokenizer: A tokenizer used to parse the number.
  1409. is_signed: True if a signed integer must be parsed.
  1410. is_long: True if a long integer must be parsed.
  1411. Returns:
  1412. The integer parsed.
  1413. Raises:
  1414. ParseError: If an integer with given characteristics couldn't be consumed.
  1415. """
  1416. try:
  1417. result = ParseInteger(tokenizer.token, is_signed=is_signed, is_long=is_long)
  1418. except ValueError as e:
  1419. raise tokenizer.ParseError(str(e))
  1420. tokenizer.NextToken()
  1421. return result
  1422. def ParseInteger(text, is_signed=False, is_long=False):
  1423. """Parses an integer.
  1424. Args:
  1425. text: The text to parse.
  1426. is_signed: True if a signed integer must be parsed.
  1427. is_long: True if a long integer must be parsed.
  1428. Returns:
  1429. The integer value.
  1430. Raises:
  1431. ValueError: Thrown Iff the text is not a valid integer.
  1432. """
  1433. # Do the actual parsing. Exception handling is propagated to caller.
  1434. result = _ParseAbstractInteger(text, is_long=is_long)
  1435. # Check if the integer is sane. Exceptions handled by callers.
  1436. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
  1437. checker.CheckValue(result)
  1438. return result
  1439. def _ParseAbstractInteger(text, is_long=False):
  1440. """Parses an integer without checking size/signedness.
  1441. Args:
  1442. text: The text to parse.
  1443. is_long: True if the value should be returned as a long integer.
  1444. Returns:
  1445. The integer value.
  1446. Raises:
  1447. ValueError: Thrown Iff the text is not a valid integer.
  1448. """
  1449. # Do the actual parsing. Exception handling is propagated to caller.
  1450. orig_text = text
  1451. c_octal_match = re.match(r'(-?)0(\d+)$', text)
  1452. if c_octal_match:
  1453. # Python 3 no longer supports 0755 octal syntax without the 'o', so
  1454. # we always use the '0o' prefix for multi-digit numbers starting with 0.
  1455. text = c_octal_match.group(1) + '0o' + c_octal_match.group(2)
  1456. try:
  1457. # We force 32-bit values to int and 64-bit values to long to make
  1458. # alternate implementations where the distinction is more significant
  1459. # (e.g. the C++ implementation) simpler.
  1460. if is_long:
  1461. return long(text, 0)
  1462. else:
  1463. return int(text, 0)
  1464. except ValueError:
  1465. raise ValueError('Couldn\'t parse integer: %s' % orig_text)
  1466. def ParseFloat(text):
  1467. """Parse a floating point number.
  1468. Args:
  1469. text: Text to parse.
  1470. Returns:
  1471. The number parsed.
  1472. Raises:
  1473. ValueError: If a floating point number couldn't be parsed.
  1474. """
  1475. try:
  1476. # Assume Python compatible syntax.
  1477. return float(text)
  1478. except ValueError:
  1479. # Check alternative spellings.
  1480. if _FLOAT_INFINITY.match(text):
  1481. if text[0] == '-':
  1482. return float('-inf')
  1483. else:
  1484. return float('inf')
  1485. elif _FLOAT_NAN.match(text):
  1486. return float('nan')
  1487. else:
  1488. # assume '1.0f' format
  1489. try:
  1490. return float(text.rstrip('f'))
  1491. except ValueError:
  1492. raise ValueError('Couldn\'t parse float: %s' % text)
  1493. def ParseBool(text):
  1494. """Parse a boolean value.
  1495. Args:
  1496. text: Text to parse.
  1497. Returns:
  1498. Boolean values parsed
  1499. Raises:
  1500. ValueError: If text is not a valid boolean.
  1501. """
  1502. if text in ('true', 't', '1', 'True'):
  1503. return True
  1504. elif text in ('false', 'f', '0', 'False'):
  1505. return False
  1506. else:
  1507. raise ValueError('Expected "true" or "false".')
  1508. def ParseEnum(field, value):
  1509. """Parse an enum value.
  1510. The value can be specified by a number (the enum value), or by
  1511. a string literal (the enum name).
  1512. Args:
  1513. field: Enum field descriptor.
  1514. value: String value.
  1515. Returns:
  1516. Enum value number.
  1517. Raises:
  1518. ValueError: If the enum value could not be parsed.
  1519. """
  1520. enum_descriptor = field.enum_type
  1521. try:
  1522. number = int(value, 0)
  1523. except ValueError:
  1524. # Identifier.
  1525. enum_value = enum_descriptor.values_by_name.get(value, None)
  1526. if enum_value is None:
  1527. raise ValueError('Enum type "%s" has no value named %s.' %
  1528. (enum_descriptor.full_name, value))
  1529. else:
  1530. # Numeric value.
  1531. if hasattr(field.file, 'syntax'):
  1532. # Attribute is checked for compatibility.
  1533. if field.file.syntax == 'proto3':
  1534. # Proto3 accept numeric unknown enums.
  1535. return number
  1536. enum_value = enum_descriptor.values_by_number.get(number, None)
  1537. if enum_value is None:
  1538. raise ValueError('Enum type "%s" has no value with number %d.' %
  1539. (enum_descriptor.full_name, number))
  1540. return enum_value.number