rngdoc.py 6.7 KB

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