dochelpers.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 urllib2
  31. import docutils
  32. import docutils.nodes
  33. import docutils.parsers.rst
  34. import docutils.parsers.rst.roles
  35. import docutils.statemachine
  36. import sphinx
  37. import sphinx.locale
  38. import sphinx.util.docfields
  39. def fetch_ticket_info(uri):
  40. '''Fetch info about particular trac ticket given
  41. :param str uri: URI at which ticket resides
  42. :rtype: mapping
  43. :raises: urllib2.HTTPError
  44. '''
  45. data = urllib2.urlopen(uri + '?format=csv').read()
  46. reader = csv.reader((line + '\n' for line in data.split('\r\n')),
  47. quoting=csv.QUOTE_MINIMAL, quotechar='"')
  48. return dict(zip(*((cell.decode('utf-8') for cell in row)
  49. for row in list(reader)[:2])))
  50. def ticket(name, rawtext, text, lineno, inliner, options={}, content=[]):
  51. '''Link to qubes ticket
  52. :param str name: The role name used in the document
  53. :param str rawtext: The entire markup snippet, with role
  54. :param str text: The text marked with the role
  55. :param int lineno: The line number where rawtext appears in the input
  56. :param docutils.parsers.rst.states.Inliner inliner: The inliner instance \
  57. that called this function
  58. :param options: Directive options for customisation
  59. :param content: The directive content for customisation
  60. '''
  61. ticket = text.lstrip('#')
  62. if not ticket.isdigit():
  63. msg = inliner.reporter.error(
  64. 'Invalid ticket identificator: {!r}'.format(text), line=lineno)
  65. prb = inliner.problematic(rawtext, rawtext, msg)
  66. return [prb], [msg]
  67. app = inliner.document.settings.env.app
  68. uri = posixpath.join(app.config.ticket_base_uri, ticket)
  69. try:
  70. info = fetch_ticket_info(uri)
  71. except urllib2.HTTPError, e:
  72. msg = inliner.reporter.error(
  73. 'Error while fetching ticket info: {!s}'.format(e), line=lineno)
  74. prb = inliner.problematic(rawtext, rawtext, msg)
  75. return [prb], [msg]
  76. docutils.parsers.rst.roles.set_classes(options)
  77. node = docutils.nodes.reference(
  78. rawtext,
  79. '#{} ({})'.format(ticket, info['summary']),
  80. refuri=uri,
  81. **options)
  82. return [node], []
  83. class versioncheck(docutils.nodes.warning):
  84. pass
  85. def visit(self, node):
  86. self.visit_admonition(node, 'version')
  87. def depart(self, node):
  88. self.depart_admonition(node)
  89. sphinx.locale.admonitionlabels['version'] = 'Version mismatch'
  90. class VersionCheck(docutils.parsers.rst.Directive):
  91. '''Directive versioncheck
  92. Check if current version (from ``conf.py``) equals version specified as
  93. argument. If not, generate warning.'''
  94. has_content = True
  95. required_arguments = 1
  96. optional_arguments = 0
  97. final_argument_whitespace = True
  98. option_spec = {}
  99. def run(self):
  100. current = self.state.document.settings.env.app.config.version
  101. version = self.arguments[0]
  102. if current == version:
  103. return []
  104. text = ' '.join('''This manual page was written for version **{}**, but
  105. current version at the time when this page was generated is **{}**.
  106. This may or may not mean that page is outdated or has
  107. inconsistencies.'''.format(version, current).split())
  108. node = versioncheck(text)
  109. node['classes'] = ['admonition', 'warning']
  110. self.state.nested_parse(docutils.statemachine.StringList([text]),
  111. self.content_offset, node)
  112. return [node]
  113. #
  114. # this is lifted from sphinx' own conf.py
  115. #
  116. event_sig_re = re.compile(r'([a-zA-Z-:<>]+)\s*\((.*)\)')
  117. def parse_event(env, sig, signode):
  118. m = event_sig_re.match(sig)
  119. if not m:
  120. signode += sphinx.addnodes.desc_name(sig, sig)
  121. return sig
  122. name, args = m.groups()
  123. signode += sphinx.addnodes.desc_name(name, name)
  124. plist = sphinx.addnodes.desc_parameterlist()
  125. for arg in args.split(','):
  126. arg = arg.strip()
  127. plist += sphinx.addnodes.desc_parameter(arg, arg)
  128. signode += plist
  129. return name
  130. #
  131. # end of codelifting
  132. #
  133. def setup(app):
  134. app.add_role('ticket', ticket)
  135. app.add_config_value('ticket_base_uri',
  136. 'https://wiki.qubes-os.org/ticket/', 'env')
  137. app.add_node(versioncheck,
  138. html=(visit, depart),
  139. man=(visit, depart))
  140. app.add_directive('versioncheck', VersionCheck)
  141. fdesc = sphinx.util.docfields.GroupedField('parameter', label='Parameters',
  142. names=['param'], can_collapse=True)
  143. app.add_object_type('event', 'event', 'pair: %s; event', parse_event,
  144. doc_field_types=[fdesc])
  145. # vim: ts=4 sw=4 et