rngdoc.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2014-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. from __future__ import print_function
  22. import sys
  23. import textwrap
  24. import lxml.etree
  25. class Element(object):
  26. def __init__(self, schema, xml):
  27. self.schema = schema
  28. self.xml = xml
  29. @property
  30. def nsmap(self):
  31. return self.schema.nsmap
  32. @property
  33. def name(self):
  34. return self.xml.get('name')
  35. def get_description(self, xml=None, wrap=True):
  36. if xml is None:
  37. xml = self.xml
  38. xml = xml.xpath('./doc:description', namespaces=self.nsmap)
  39. if not xml:
  40. return ''
  41. xml = xml[0]
  42. if wrap:
  43. return ''.join(self.schema.wrapper.fill(p) + '\n\n'
  44. for p in textwrap.dedent(xml.text.strip('\n')).split('\n\n'))
  45. else:
  46. return ' '.join(xml.text.strip().split())
  47. def get_data_type(self, xml=None):
  48. if xml is None:
  49. xml = self.xml
  50. value = xml.xpath('./rng:value', namespaces=self.nsmap)
  51. if value:
  52. value = '``{}``'.format(value[0].text.strip())
  53. else:
  54. metavar = xml.xpath('./doc:metavar', namespaces=self.nsmap)
  55. if metavar:
  56. value = '``{}``'.format(metavar[0].text.strip())
  57. else:
  58. value = ''
  59. xml = xml.xpath('./rng:data', namespaces=self.nsmap)
  60. if not xml:
  61. return ('', value)
  62. xml = xml[0]
  63. type_ = xml.get('type', '')
  64. if not value:
  65. pattern = xml.xpath('./rng:param[@name="pattern"]',
  66. namespaces=self.nsmap)
  67. if pattern:
  68. value = '``{}``'.format(pattern[0].text.strip())
  69. return type_, value
  70. def get_attributes(self):
  71. for xml in self.xml.xpath('''./rng:attribute |
  72. ./rng:optional/rng:attribute |
  73. ./rng:choice/rng:attribute''', namespaces=self.nsmap):
  74. required = xml.getparent() == self.xml and 'yes' or 'no'
  75. yield (xml, required)
  76. def resolve_ref(self, ref):
  77. refs = self.xml.xpath(
  78. '//rng:define[name="{}"]/rng:element'.format(ref['name']))
  79. return refs[0] if refs else None
  80. def get_child_elements(self):
  81. for xml in self.xml.xpath('''./rng:element | ./rng:ref |
  82. ./rng:optional/rng:element | ./rng:optional/rng:ref |
  83. ./rng:zeroOrMore/rng:element | ./rng:zeroOrMore/rng:ref |
  84. ./rng:oneOrMore/rng:element | ./rng:oneOrMore/rng:ref''',
  85. namespaces=self.nsmap):
  86. parent = xml.getparent()
  87. qname = lxml.etree.QName(parent)
  88. if parent == self.xml:
  89. number = '1'
  90. elif qname.localname == 'optional':
  91. number = '?'
  92. elif qname.localname == 'zeroOrMore':
  93. number = '\\*'
  94. elif qname.localname == 'oneOrMore':
  95. number = '\\+'
  96. else:
  97. print(parent.tag)
  98. if xml.tag == 'ref':
  99. xml = self.resolve_ref(xml)
  100. if xml is None:
  101. continue
  102. yield (self.schema.elements[xml.get('name')], number)
  103. def write_rst(self, stream):
  104. stream.write('.. _qubesxml-element-{}:\n\n'.format(self.name))
  105. stream.write(make_rst_section('Element: **{}**'.format(self.name), '-'))
  106. stream.write(self.get_description())
  107. attrtable = []
  108. for attr, required in self.get_attributes():
  109. type_, value = self.get_data_type(attr)
  110. attrtable.append((
  111. attr.get('name'),
  112. required,
  113. type_,
  114. value,
  115. self.get_description(attr, wrap=False)))
  116. if attrtable:
  117. stream.write(make_rst_section('Attributes', '^'))
  118. write_rst_table(stream, attrtable,
  119. ('attribute', 'req.', 'type', 'value', 'description'))
  120. childtable = [(':ref:`{0} <qubesxml-element-{0}>`'.format(
  121. child.xml.get('name')), n)
  122. for child, n in self.get_child_elements()]
  123. if childtable:
  124. stream.write(make_rst_section('Child elements', '^'))
  125. write_rst_table(stream, childtable, ('element', 'number'))
  126. class Schema(object):
  127. # pylint: disable=too-few-public-methods
  128. nsmap = {
  129. 'rng': 'http://relaxng.org/ns/structure/1.0',
  130. 'q': 'http://qubes-os.org/qubes/3',
  131. 'doc': 'http://qubes-os.org/qubes-doc/1'}
  132. def __init__(self, xml):
  133. self.xml = xml
  134. self.wrapper = textwrap.TextWrapper(width=80,
  135. break_long_words=False, break_on_hyphens=False)
  136. self.elements = {}
  137. for node in self.xml.xpath('//rng:element', namespaces=self.nsmap):
  138. element = Element(self, node)
  139. self.elements[element.name] = element
  140. def make_rst_section(heading, char):
  141. return '{}\n{}\n\n'.format(heading, char[0] * len(heading))
  142. def write_rst_table(stream, itr, heads):
  143. stream.write('.. csv-table::\n')
  144. stream.write(' :header: {}\n'.format(', '.join('"{}"'.format(c)
  145. for c in heads)))
  146. stream.write(' :widths: {}\n\n'.format(', '.join('1'
  147. for c in heads)))
  148. for row in itr:
  149. stream.write(' {}\n'.format(', '.join('"{}"'.format(i) for i in row)))
  150. stream.write('\n')
  151. def main(filename, example):
  152. schema = Schema(lxml.etree.parse(open(filename, 'rb')))
  153. sys.stdout.write(make_rst_section('Qubes XML specification', '='))
  154. sys.stdout.write('''
  155. This is the documentation of qubes.xml autogenerated from RelaxNG source.
  156. Quick example, worth thousands lines of specification:
  157. .. literalinclude:: {}
  158. :language: xml
  159. '''[1:].format(example))
  160. for name in sorted(schema.elements):
  161. schema.elements[name].write_rst(sys.stdout)
  162. if __name__ == '__main__':
  163. main(*sys.argv[1:])
  164. # vim: ts=4 sw=4 et