dochelpers.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. ''' # pylint: disable=unused-argument
  61. ticketno = 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, ticketno)
  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(ticketno, info['summary']),
  80. refuri=uri,
  81. **options)
  82. return [node], []
  83. class versioncheck(docutils.nodes.warning):
  84. # pylint: disable=invalid-name
  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. # pylint: disable=unused-argument
  120. m = event_sig_re.match(sig)
  121. if not m:
  122. signode += sphinx.addnodes.desc_name(sig, sig)
  123. return sig
  124. name, args = m.groups()
  125. signode += sphinx.addnodes.desc_name(name, name)
  126. plist = sphinx.addnodes.desc_parameterlist()
  127. for arg in args.split(','):
  128. arg = arg.strip()
  129. plist += sphinx.addnodes.desc_parameter(arg, arg)
  130. signode += plist
  131. return name
  132. #
  133. # end of codelifting
  134. #
  135. def setup(app):
  136. app.add_role('ticket', ticket)
  137. app.add_config_value('ticket_base_uri',
  138. 'https://wiki.qubes-os.org/ticket/', 'env')
  139. app.add_node(versioncheck,
  140. html=(visit, depart),
  141. man=(visit, depart))
  142. app.add_directive('versioncheck', VersionCheck)
  143. fdesc = sphinx.util.docfields.GroupedField('parameter', label='Parameters',
  144. names=['param'], can_collapse=True)
  145. app.add_object_type('event', 'event', 'pair: %s; event', parse_event,
  146. doc_field_types=[fdesc])
  147. # vim: ts=4 sw=4 et