schema.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. # Copyright 2014 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Schema processing for discovery based APIs
  15. Schemas holds an APIs discovery schemas. It can return those schema as
  16. deserialized JSON objects, or pretty print them as prototype objects that
  17. conform to the schema.
  18. For example, given the schema:
  19. schema = \"\"\"{
  20. "Foo": {
  21. "type": "object",
  22. "properties": {
  23. "etag": {
  24. "type": "string",
  25. "description": "ETag of the collection."
  26. },
  27. "kind": {
  28. "type": "string",
  29. "description": "Type of the collection ('calendar#acl').",
  30. "default": "calendar#acl"
  31. },
  32. "nextPageToken": {
  33. "type": "string",
  34. "description": "Token used to access the next
  35. page of this result. Omitted if no further results are available."
  36. }
  37. }
  38. }
  39. }\"\"\"
  40. s = Schemas(schema)
  41. print s.prettyPrintByName('Foo')
  42. Produces the following output:
  43. {
  44. "nextPageToken": "A String", # Token used to access the
  45. # next page of this result. Omitted if no further results are available.
  46. "kind": "A String", # Type of the collection ('calendar#acl').
  47. "etag": "A String", # ETag of the collection.
  48. },
  49. The constructor takes a discovery document in which to look up named schema.
  50. """
  51. from __future__ import absolute_import
  52. # TODO(jcgregorio) support format, enum, minimum, maximum
  53. __author__ = "jcgregorio@google.com (Joe Gregorio)"
  54. from collections import OrderedDict
  55. from googleapiclient import _helpers as util
  56. class Schemas(object):
  57. """Schemas for an API."""
  58. def __init__(self, discovery):
  59. """Constructor.
  60. Args:
  61. discovery: object, Deserialized discovery document from which we pull
  62. out the named schema.
  63. """
  64. self.schemas = discovery.get("schemas", {})
  65. # Cache of pretty printed schemas.
  66. self.pretty = {}
  67. @util.positional(2)
  68. def _prettyPrintByName(self, name, seen=None, dent=0):
  69. """Get pretty printed object prototype from the schema name.
  70. Args:
  71. name: string, Name of schema in the discovery document.
  72. seen: list of string, Names of schema already seen. Used to handle
  73. recursive definitions.
  74. Returns:
  75. string, A string that contains a prototype object with
  76. comments that conforms to the given schema.
  77. """
  78. if seen is None:
  79. seen = []
  80. if name in seen:
  81. # Do not fall into an infinite loop over recursive definitions.
  82. return "# Object with schema name: %s" % name
  83. seen.append(name)
  84. if name not in self.pretty:
  85. self.pretty[name] = _SchemaToStruct(
  86. self.schemas[name], seen, dent=dent
  87. ).to_str(self._prettyPrintByName)
  88. seen.pop()
  89. return self.pretty[name]
  90. def prettyPrintByName(self, name):
  91. """Get pretty printed object prototype from the schema name.
  92. Args:
  93. name: string, Name of schema in the discovery document.
  94. Returns:
  95. string, A string that contains a prototype object with
  96. comments that conforms to the given schema.
  97. """
  98. # Return with trailing comma and newline removed.
  99. return self._prettyPrintByName(name, seen=[], dent=0)[:-2]
  100. @util.positional(2)
  101. def _prettyPrintSchema(self, schema, seen=None, dent=0):
  102. """Get pretty printed object prototype of schema.
  103. Args:
  104. schema: object, Parsed JSON schema.
  105. seen: list of string, Names of schema already seen. Used to handle
  106. recursive definitions.
  107. Returns:
  108. string, A string that contains a prototype object with
  109. comments that conforms to the given schema.
  110. """
  111. if seen is None:
  112. seen = []
  113. return _SchemaToStruct(schema, seen, dent=dent).to_str(self._prettyPrintByName)
  114. def prettyPrintSchema(self, schema):
  115. """Get pretty printed object prototype of schema.
  116. Args:
  117. schema: object, Parsed JSON schema.
  118. Returns:
  119. string, A string that contains a prototype object with
  120. comments that conforms to the given schema.
  121. """
  122. # Return with trailing comma and newline removed.
  123. return self._prettyPrintSchema(schema, dent=0)[:-2]
  124. def get(self, name, default=None):
  125. """Get deserialized JSON schema from the schema name.
  126. Args:
  127. name: string, Schema name.
  128. default: object, return value if name not found.
  129. """
  130. return self.schemas.get(name, default)
  131. class _SchemaToStruct(object):
  132. """Convert schema to a prototype object."""
  133. @util.positional(3)
  134. def __init__(self, schema, seen, dent=0):
  135. """Constructor.
  136. Args:
  137. schema: object, Parsed JSON schema.
  138. seen: list, List of names of schema already seen while parsing. Used to
  139. handle recursive definitions.
  140. dent: int, Initial indentation depth.
  141. """
  142. # The result of this parsing kept as list of strings.
  143. self.value = []
  144. # The final value of the parsing.
  145. self.string = None
  146. # The parsed JSON schema.
  147. self.schema = schema
  148. # Indentation level.
  149. self.dent = dent
  150. # Method that when called returns a prototype object for the schema with
  151. # the given name.
  152. self.from_cache = None
  153. # List of names of schema already seen while parsing.
  154. self.seen = seen
  155. def emit(self, text):
  156. """Add text as a line to the output.
  157. Args:
  158. text: string, Text to output.
  159. """
  160. self.value.extend([" " * self.dent, text, "\n"])
  161. def emitBegin(self, text):
  162. """Add text to the output, but with no line terminator.
  163. Args:
  164. text: string, Text to output.
  165. """
  166. self.value.extend([" " * self.dent, text])
  167. def emitEnd(self, text, comment):
  168. """Add text and comment to the output with line terminator.
  169. Args:
  170. text: string, Text to output.
  171. comment: string, Python comment.
  172. """
  173. if comment:
  174. divider = "\n" + " " * (self.dent + 2) + "# "
  175. lines = comment.splitlines()
  176. lines = [x.rstrip() for x in lines]
  177. comment = divider.join(lines)
  178. self.value.extend([text, " # ", comment, "\n"])
  179. else:
  180. self.value.extend([text, "\n"])
  181. def indent(self):
  182. """Increase indentation level."""
  183. self.dent += 1
  184. def undent(self):
  185. """Decrease indentation level."""
  186. self.dent -= 1
  187. def _to_str_impl(self, schema):
  188. """Prototype object based on the schema, in Python code with comments.
  189. Args:
  190. schema: object, Parsed JSON schema file.
  191. Returns:
  192. Prototype object based on the schema, in Python code with comments.
  193. """
  194. stype = schema.get("type")
  195. if stype == "object":
  196. self.emitEnd("{", schema.get("description", ""))
  197. self.indent()
  198. if "properties" in schema:
  199. properties = schema.get("properties", {})
  200. sorted_properties = OrderedDict(sorted(properties.items()))
  201. for pname, pschema in sorted_properties.items():
  202. self.emitBegin('"%s": ' % pname)
  203. self._to_str_impl(pschema)
  204. elif "additionalProperties" in schema:
  205. self.emitBegin('"a_key": ')
  206. self._to_str_impl(schema["additionalProperties"])
  207. self.undent()
  208. self.emit("},")
  209. elif "$ref" in schema:
  210. schemaName = schema["$ref"]
  211. description = schema.get("description", "")
  212. s = self.from_cache(schemaName, seen=self.seen)
  213. parts = s.splitlines()
  214. self.emitEnd(parts[0], description)
  215. for line in parts[1:]:
  216. self.emit(line.rstrip())
  217. elif stype == "boolean":
  218. value = schema.get("default", "True or False")
  219. self.emitEnd("%s," % str(value), schema.get("description", ""))
  220. elif stype == "string":
  221. value = schema.get("default", "A String")
  222. self.emitEnd('"%s",' % str(value), schema.get("description", ""))
  223. elif stype == "integer":
  224. value = schema.get("default", "42")
  225. self.emitEnd("%s," % str(value), schema.get("description", ""))
  226. elif stype == "number":
  227. value = schema.get("default", "3.14")
  228. self.emitEnd("%s," % str(value), schema.get("description", ""))
  229. elif stype == "null":
  230. self.emitEnd("None,", schema.get("description", ""))
  231. elif stype == "any":
  232. self.emitEnd('"",', schema.get("description", ""))
  233. elif stype == "array":
  234. self.emitEnd("[", schema.get("description"))
  235. self.indent()
  236. self.emitBegin("")
  237. self._to_str_impl(schema["items"])
  238. self.undent()
  239. self.emit("],")
  240. else:
  241. self.emit("Unknown type! %s" % stype)
  242. self.emitEnd("", "")
  243. self.string = "".join(self.value)
  244. return self.string
  245. def to_str(self, from_cache):
  246. """Prototype object based on the schema, in Python code with comments.
  247. Args:
  248. from_cache: callable(name, seen), Callable that retrieves an object
  249. prototype for a schema with the given name. Seen is a list of schema
  250. names already seen as we recursively descend the schema definition.
  251. Returns:
  252. Prototype object based on the schema, in Python code with comments.
  253. The lines of the code will all be properly indented.
  254. """
  255. self.from_cache = from_cache
  256. return self._to_str_impl(self.schema)