rngdoc.py 6.6 KB

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