blob: 1c4cadfc6a42ccad93250f132382e73f23f76782 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Protocol Buffers - Google's data interchange format
2# Copyright 2008 Google Inc. All rights reserved.
3# http://code.google.com/p/protobuf/
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
31"""Contains routines for printing protocol messages in text format."""
32
33__author__ = 'kenton@google.com (Kenton Varda)'
34
35import cStringIO
36
37from froofle.protobuf import descriptor
38
39__all__ = [ 'MessageToString', 'PrintMessage', 'PrintField', 'PrintFieldValue' ]
40
41def MessageToString(message):
42 out = cStringIO.StringIO()
43 PrintMessage(message, out)
44 result = out.getvalue()
45 out.close()
46 return result
47
48def PrintMessage(message, out, indent = 0):
49 for field, value in message.ListFields():
50 if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
51 for element in value:
52 PrintField(field, element, out, indent)
53 else:
54 PrintField(field, value, out, indent)
55
56def PrintField(field, value, out, indent = 0):
57 """Print a single field name/value pair. For repeated fields, the value
58 should be a single element."""
59
60 out.write(' ' * indent);
61 if field.is_extension:
62 out.write('[')
63 if (field.containing_type.GetOptions().message_set_wire_format and
64 field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
65 field.message_type == field.extension_scope and
66 field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
67 out.write(field.message_type.full_name)
68 else:
69 out.write(field.full_name)
70 out.write(']')
71 elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
72 # For groups, use the capitalized name.
73 out.write(field.message_type.name)
74 else:
75 out.write(field.name)
76
77 if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
78 # The colon is optional in this case, but our cross-language golden files
79 # don't include it.
80 out.write(': ')
81
82 PrintFieldValue(field, value, out, indent)
83 out.write('\n')
84
85def PrintFieldValue(field, value, out, indent = 0):
86 """Print a single field value (not including name). For repeated fields,
87 the value should be a single element."""
88
89 if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
90 out.write(' {\n')
91 PrintMessage(value, out, indent + 2)
92 out.write(' ' * indent + '}')
93 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
94 out.write(field.enum_type.values_by_number[value].name)
95 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
96 out.write('\"')
97 out.write(_CEscape(value))
98 out.write('\"')
99 elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
100 if value:
101 out.write("true")
102 else:
103 out.write("false")
104 else:
105 out.write(str(value))
106
107# text.encode('string_escape') does not seem to satisfy our needs as it
108# encodes unprintable characters using two-digit hex escapes whereas our
109# C++ unescaping function allows hex escapes to be any length. So,
110# "\0011".encode('string_escape') ends up being "\\x011", which will be
111# decoded in C++ as a single-character string with char code 0x11.
112def _CEscape(text):
113 def escape(c):
114 o = ord(c)
115 if o == 10: return r"\n" # optional escape
116 if o == 13: return r"\r" # optional escape
117 if o == 9: return r"\t" # optional escape
118 if o == 39: return r"\'" # optional escape
119
120 if o == 34: return r'\"' # necessary escape
121 if o == 92: return r"\\" # necessary escape
122
123 if o >= 127 or o < 32: return "\\%03o" % o # necessary escapes
124 return c
125 return "".join([escape(c) for c in text])