dochelpers.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/python2 -O
  2. # vim: fileencoding=utf-8
  3. #
  4. # The Qubes OS Project, https://www.qubes-os.org/
  5. #
  6. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  7. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. #
  23. '''Documentation helpers.
  24. This module contains classes and functions which help to maintain documentation,
  25. particularly our custom Sphinx extension.
  26. '''
  27. import csv
  28. import posixpath
  29. import re
  30. import sys
  31. import urllib2
  32. import docutils
  33. import docutils.nodes
  34. import docutils.parsers.rst
  35. import docutils.parsers.rst.roles
  36. import docutils.statemachine
  37. import sphinx
  38. import sphinx.locale
  39. import sphinx.util.docfields
  40. def fetch_ticket_info(uri):
  41. '''Fetch info about particular trac ticket given
  42. :param str uri: URI at which ticket resides
  43. :rtype: mapping
  44. :raises: urllib2.HTTPError
  45. '''
  46. data = urllib2.urlopen(uri + '?format=csv').read()
  47. reader = csv.reader((line + '\n' for line in data.split('\r\n')),
  48. quoting=csv.QUOTE_MINIMAL, quotechar='"')
  49. return dict(zip(*((cell.decode('utf-8') for cell in row)
  50. for row in list(reader)[:2])))
  51. def ticket(name, rawtext, text, lineno, inliner, options={}, content=[]):
  52. '''Link to qubes ticket
  53. :param str name: The role name used in the document
  54. :param str rawtext: The entire markup snippet, with role
  55. :param str text: The text marked with the role
  56. :param int lineno: The line number where rawtext appears in the input
  57. :param docutils.parsers.rst.states.Inliner inliner: The inliner instance \
  58. that called this function
  59. :param options: Directive options for customisation
  60. :param content: The directive content for customisation
  61. '''
  62. ticket = text.lstrip('#')
  63. if not ticket.isdigit():
  64. msg = inliner.reporter.error(
  65. 'Invalid ticket identificator: {!r}'.format(text), line=lineno)
  66. prb = inliner.problematic(rawtext, rawtext, msg)
  67. return [prb], [msg]
  68. app = inliner.document.settings.env.app
  69. uri = posixpath.join(app.config.ticket_base_uri, ticket)
  70. try:
  71. info = fetch_ticket_info(uri)
  72. except urllib2.HTTPError, e:
  73. msg = inliner.reporter.error(
  74. 'Error while fetching ticket info: {!s}'.format(e), line=lineno)
  75. prb = inliner.problematic(rawtext, rawtext, msg)
  76. return [prb], [msg]
  77. docutils.parsers.rst.roles.set_classes(options)
  78. node = docutils.nodes.reference(
  79. rawtext,
  80. '#{} ({})'.format(ticket, info['summary']),
  81. refuri=uri,
  82. **options)
  83. return [node], []
  84. class versioncheck(docutils.nodes.warning):
  85. pass
  86. def visit(self, node):
  87. self.visit_admonition(node, 'version')
  88. def depart(self, node):
  89. self.depart_admonition(node)
  90. sphinx.locale.admonitionlabels['version'] = 'Version mismatch'
  91. class VersionCheck(docutils.parsers.rst.Directive):
  92. '''Directive versioncheck
  93. Check if current version (from ``conf.py``) equals version specified as
  94. argument. If not, generate warning.'''
  95. has_content = True
  96. required_arguments = 1
  97. optional_arguments = 0
  98. final_argument_whitespace = True
  99. option_spec = {}
  100. def run(self):
  101. current = self.state.document.settings.env.app.config.version
  102. version = self.arguments[0]
  103. if current == version:
  104. return []
  105. text = ' '.join('''This manual page was written for version **{}**, but
  106. current version at the time when this page was generated is **{}**.
  107. This may or may not mean that page is outdated or has
  108. inconsistencies.'''.format(version, current).split())
  109. node = versioncheck(text)
  110. node['classes'] = ['admonition', 'warning']
  111. self.state.nested_parse(docutils.statemachine.StringList([text]),
  112. self.content_offset, node)
  113. return [node]
  114. #
  115. # this is lifted from sphinx' own conf.py
  116. #
  117. event_sig_re = re.compile(r'([a-zA-Z-:<>]+)\s*\((.*)\)')
  118. def parse_event(env, sig, signode):
  119. m = event_sig_re.match(sig)
  120. if not m:
  121. signode += sphinx.addnodes.desc_name(sig, sig)
  122. return sig
  123. name, args = m.groups()
  124. signode += sphinx.addnodes.desc_name(name, name)
  125. plist = sphinx.addnodes.desc_parameterlist()
  126. for arg in args.split(','):
  127. arg = arg.strip()
  128. plist += sphinx.addnodes.desc_parameter(arg, arg)
  129. signode += plist
  130. return name
  131. #
  132. # end of codelifting
  133. #
  134. def setup(app):
  135. app.add_role('ticket', ticket)
  136. app.add_config_value('ticket_base_uri',
  137. 'https://wiki.qubes-os.org/ticket/', 'env')
  138. app.add_node(versioncheck,
  139. html=(visit, depart),
  140. man=(visit, depart))
  141. app.add_directive('versioncheck', VersionCheck)
  142. fdesc = sphinx.util.docfields.GroupedField('parameter', label='Parameters',
  143. names=['param'], can_collapse=True)
  144. app.add_object_type('event', 'event', 'pair: %s; event', parse_event,
  145. doc_field_types=[fdesc])
  146. # vim: ts=4 sw=4 et