dochelpers.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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 argparse
  28. import json
  29. import os
  30. import re
  31. import StringIO
  32. import urllib2
  33. import docutils
  34. import docutils.nodes
  35. import docutils.parsers.rst
  36. import docutils.parsers.rst.roles
  37. import docutils.statemachine
  38. import sphinx
  39. import sphinx.errors
  40. import sphinx.locale
  41. import sphinx.util.docfields
  42. import qubes.tools
  43. SUBCOMMANDS_TITLE = 'COMMANDS'
  44. OPTIONS_TITLE = 'OPTIONS'
  45. class GithubTicket(object):
  46. # pylint: disable=too-few-public-methods
  47. def __init__(self, data):
  48. self.number = data['number']
  49. self.summary = data['title']
  50. self.uri = data['html_url']
  51. def fetch_ticket_info(app, number):
  52. '''Fetch info about particular trac ticket given
  53. :param app: Sphinx app object
  54. :param str number: number of the ticket, without #
  55. :rtype: mapping
  56. :raises: urllib2.HTTPError
  57. '''
  58. response = urllib2.urlopen(urllib2.Request(
  59. app.config.ticket_base_uri.format(number=number),
  60. headers={
  61. 'Accept': 'application/vnd.github.v3+json',
  62. 'User-agent': __name__}))
  63. return GithubTicket(json.load(response))
  64. def ticket(name, rawtext, text, lineno, inliner, options=None, content=None):
  65. '''Link to qubes ticket
  66. :param str name: The role name used in the document
  67. :param str rawtext: The entire markup snippet, with role
  68. :param str text: The text marked with the role
  69. :param int lineno: The line number where rawtext appears in the input
  70. :param docutils.parsers.rst.states.Inliner inliner: The inliner instance \
  71. that called this function
  72. :param options: Directive options for customisation
  73. :param content: The directive content for customisation
  74. ''' # pylint: disable=unused-argument
  75. if options is None:
  76. options = {}
  77. ticketno = text.lstrip('#')
  78. if not ticketno.isdigit():
  79. msg = inliner.reporter.error(
  80. 'Invalid ticket identificator: {!r}'.format(text), line=lineno)
  81. prb = inliner.problematic(rawtext, rawtext, msg)
  82. return [prb], [msg]
  83. try:
  84. info = fetch_ticket_info(inliner.document.settings.env.app, ticketno)
  85. except urllib2.HTTPError, e:
  86. msg = inliner.reporter.error(
  87. 'Error while fetching ticket info: {!s}'.format(e), line=lineno)
  88. prb = inliner.problematic(rawtext, rawtext, msg)
  89. return [prb], [msg]
  90. docutils.parsers.rst.roles.set_classes(options)
  91. node = docutils.nodes.reference(
  92. rawtext,
  93. '#{} ({})'.format(info.number, info.summary),
  94. refuri=info.uri,
  95. **options)
  96. return [node], []
  97. class versioncheck(docutils.nodes.warning):
  98. # pylint: disable=invalid-name
  99. pass
  100. def visit(self, node):
  101. self.visit_admonition(node, 'version')
  102. def depart(self, node):
  103. self.depart_admonition(node)
  104. sphinx.locale.admonitionlabels['version'] = 'Version mismatch'
  105. class VersionCheck(docutils.parsers.rst.Directive):
  106. '''Directive versioncheck
  107. Check if current version (from ``conf.py``) equals version specified as
  108. argument. If not, generate warning.'''
  109. has_content = True
  110. required_arguments = 1
  111. optional_arguments = 0
  112. final_argument_whitespace = True
  113. option_spec = {}
  114. def run(self):
  115. current = self.state.document.settings.env.app.config.version
  116. version = self.arguments[0]
  117. if current == version:
  118. return []
  119. text = ' '.join('''This manual page was written for version **{}**, but
  120. current version at the time when this page was generated is **{}**.
  121. This may or may not mean that page is outdated or has
  122. inconsistencies.'''.format(version, current).split())
  123. node = versioncheck(text)
  124. node['classes'] = ['admonition', 'warning']
  125. self.state.nested_parse(docutils.statemachine.StringList([text]),
  126. self.content_offset, node)
  127. return [node]
  128. def make_rst_section(heading, char):
  129. return '{}\n{}\n\n'.format(heading, char[0] * len(heading))
  130. def prepare_manpage(command):
  131. parser = qubes.tools.get_parser_for_command(command)
  132. stream = StringIO.StringIO()
  133. stream.write('.. program:: {}\n\n'.format(command))
  134. stream.write(make_rst_section(
  135. ':program:`{}` -- {}'.format(command, parser.description), '='))
  136. stream.write('''.. warning::
  137. This page was autogenerated from command-line parser. It shouldn't be 1:1
  138. conversion, because it would add little value. Please revise it and add
  139. more descriptive help, which normally won't fit in standard ``--help``
  140. option.
  141. After rewrite, please remove this admonition.\n\n''')
  142. stream.write(make_rst_section('Synopsis', '-'))
  143. usage = ' '.join(parser.format_usage().strip().split())
  144. if usage.startswith('usage: '):
  145. usage = usage[len('usage: '):]
  146. # replace METAVARS with *METAVARS*
  147. usage = re.sub(r'\b([A-Z]{2,})\b', r'*\1*', usage)
  148. stream.write(':command:`{}` {}\n\n'.format(command, usage))
  149. stream.write(make_rst_section('Options', '-'))
  150. for action in parser._actions: # pylint: disable=protected-access
  151. stream.write('.. option:: ')
  152. if action.metavar:
  153. stream.write(', '.join('{}{}{}'.format(
  154. option,
  155. '=' if option.startswith('--') else ' ',
  156. action.metavar)
  157. for option in sorted(action.option_strings)))
  158. else:
  159. stream.write(', '.join(sorted(action.option_strings)))
  160. stream.write('\n\n {}\n\n'.format(action.help))
  161. stream.write(make_rst_section('Authors', '-'))
  162. stream.write('''\
  163. | Joanna Rutkowska <joanna at invisiblethingslab dot com>
  164. | Rafal Wojtczuk <rafal at invisiblethingslab dot com>
  165. | Marek Marczykowski <marmarek at invisiblethingslab dot com>
  166. | Wojtek Porczyk <woju at invisiblethingslab dot com>
  167. .. vim: ts=3 sw=3 et tw=80
  168. ''')
  169. return stream.getvalue()
  170. class OptionsCheckVisitor(docutils.nodes.SparseNodeVisitor):
  171. ''' Checks if the visited option nodes and the specified args are in sync.
  172. '''
  173. def __init__(self, command, args, document):
  174. assert isinstance(args, set)
  175. docutils.nodes.SparseNodeVisitor.__init__(self, document)
  176. self.command = command
  177. self.args = args
  178. def visit_desc(self, node):
  179. ''' Skips all but 'option' elements '''
  180. # pylint: disable=no-self-use
  181. if not node.get('desctype', None) == 'option':
  182. raise docutils.nodes.SkipChildren
  183. def visit_desc_name(self, node):
  184. ''' Checks if the option is defined `self.args` '''
  185. if not isinstance(node[0], docutils.nodes.Text):
  186. raise sphinx.errors.SphinxError('first child should be Text')
  187. arg = str(node[0])
  188. try:
  189. self.args.remove(arg)
  190. except KeyError:
  191. raise sphinx.errors.SphinxError(
  192. 'No such argument for {!r}: {!r}'.format(self.command, arg))
  193. def check_undocumented_arguments(self, ignored_options=None):
  194. ''' Call this to check if any undocumented arguments are left.
  195. While the documentation talks about a
  196. 'SparseNodeVisitor.depart_document()' function, this function does
  197. not exists. (For details see implementation of
  198. :py:method:`NodeVisitor.dispatch_departure()`) So we need to
  199. manually call this.
  200. '''
  201. if ignored_options is None:
  202. ignored_options = set()
  203. left_over_args = self.args - ignored_options
  204. if left_over_args:
  205. raise sphinx.errors.SphinxError(
  206. 'Undocumented arguments for command {!r}: {!r}'.format(
  207. self.command, ', '.join(sorted(left_over_args))))
  208. class CommandCheckVisitor(docutils.nodes.SparseNodeVisitor):
  209. ''' Checks if the visited sub command section nodes and the specified sub
  210. command args are in sync.
  211. '''
  212. def __init__(self, command, sub_commands, document):
  213. docutils.nodes.SparseNodeVisitor.__init__(self, document)
  214. self.command = command
  215. self.sub_commands = sub_commands
  216. def visit_section(self, node):
  217. ''' Checks if the visited sub-command section nodes exists and it
  218. options are in sync.
  219. Uses :py:class:`OptionsCheckVisitor` for checking
  220. sub-commands options
  221. '''
  222. # pylint: disable=no-self-use
  223. title = str(node[0][0])
  224. if title.upper() == SUBCOMMANDS_TITLE:
  225. return
  226. sub_cmd = self.command + ' ' + title
  227. try:
  228. args = self.sub_commands[title]
  229. options_visitor = OptionsCheckVisitor(sub_cmd, args, self.document)
  230. node.walkabout(options_visitor)
  231. options_visitor.check_undocumented_arguments(
  232. {'--help', '--quiet', '--verbose', '-h', '-q', '-v'})
  233. del self.sub_commands[title]
  234. except KeyError:
  235. raise sphinx.errors.SphinxError(
  236. 'No such sub-command {!r}'.format(sub_cmd))
  237. def visit_Text(self, node):
  238. ''' If the visited text node starts with 'alias: ', all the provided
  239. comma separted alias in this node, are removed from
  240. `self.sub_commands`
  241. '''
  242. # pylint: disable=invalid-name
  243. text = str(node).strip()
  244. if text.startswith('aliases:'):
  245. aliases = {a.strip() for a in text.split('aliases:')[1].split(',')}
  246. for alias in aliases:
  247. assert alias in self.sub_commands
  248. del self.sub_commands[alias]
  249. def check_undocumented_sub_commands(self):
  250. ''' Call this to check if any undocumented sub_commands are left.
  251. While the documentation talks about a
  252. 'SparseNodeVisitor.depart_document()' function, this function does
  253. not exists. (For details see implementation of
  254. :py:method:`NodeVisitor.dispatch_departure()`) So we need to
  255. manually call this.
  256. '''
  257. if self.sub_commands:
  258. raise sphinx.errors.SphinxError(
  259. 'Undocumented commands for {!r}: {!r}'.format(
  260. self.command, ', '.join(sorted(self.sub_commands.keys()))))
  261. class ManpageCheckVisitor(docutils.nodes.SparseNodeVisitor):
  262. ''' Checks if the sub-commands and options specified in the 'COMMAND' and
  263. 'OPTIONS' (case insensitve) sections in sync the command parser.
  264. '''
  265. def __init__(self, app, command, document):
  266. docutils.nodes.SparseNodeVisitor.__init__(self, document)
  267. try:
  268. parser = qubes.tools.get_parser_for_command(command)
  269. except ImportError:
  270. app.warn('cannot import module for command')
  271. self.parser = None
  272. return
  273. except AttributeError:
  274. raise sphinx.errors.SphinxError('cannot find parser in module')
  275. self.command = command
  276. self.parser = parser
  277. self.options = set()
  278. self.sub_commands = {}
  279. self.app = app
  280. # pylint: disable=protected-access
  281. for action in parser._actions:
  282. if action.help == argparse.SUPPRESS:
  283. continue
  284. if issubclass(action.__class__,
  285. qubes.tools.AliasedSubParsersAction):
  286. for cmd, cmd_parser in action._name_parser_map.items():
  287. self.sub_commands[cmd] = set()
  288. for sub_action in cmd_parser._actions:
  289. if sub_action.help != argparse.SUPPRESS:
  290. self.sub_commands[cmd].update(
  291. sub_action.option_strings)
  292. else:
  293. self.options.update(action.option_strings)
  294. def visit_section(self, node):
  295. ''' If section title is OPTIONS or COMMANDS dispatch the apropriate
  296. `NodeVisitor`.
  297. '''
  298. if self.parser is None:
  299. return
  300. section_title = str(node[0][0]).upper()
  301. if section_title == OPTIONS_TITLE:
  302. options_visitor = OptionsCheckVisitor(self.command, self.options,
  303. self.document)
  304. node.walkabout(options_visitor)
  305. options_visitor.check_undocumented_arguments()
  306. elif section_title == SUBCOMMANDS_TITLE:
  307. sub_cmd_visitor = CommandCheckVisitor(
  308. self.command, self.sub_commands, self.document)
  309. node.walkabout(sub_cmd_visitor)
  310. sub_cmd_visitor.check_undocumented_sub_commands()
  311. def check_man_args(app, doctree, docname):
  312. ''' Checks the manpage for undocumented or obsolete sub-commands and
  313. options.
  314. '''
  315. command = os.path.split(docname)[1]
  316. app.info('Checking arguments for {!r}'.format(command))
  317. doctree.walk(ManpageCheckVisitor(app, command, doctree))
  318. #
  319. # this is lifted from sphinx' own conf.py
  320. #
  321. event_sig_re = re.compile(r'([a-zA-Z-:<>]+)\s*\((.*)\)')
  322. def parse_event(env, sig, signode):
  323. # pylint: disable=unused-argument
  324. m = event_sig_re.match(sig)
  325. if not m:
  326. signode += sphinx.addnodes.desc_name(sig, sig)
  327. return sig
  328. name, args = m.groups()
  329. signode += sphinx.addnodes.desc_name(name, name)
  330. plist = sphinx.addnodes.desc_parameterlist()
  331. for arg in args.split(','):
  332. arg = arg.strip()
  333. plist += sphinx.addnodes.desc_parameter(arg, arg)
  334. signode += plist
  335. return name
  336. #
  337. # end of codelifting
  338. #
  339. def break_to_pdb(app, *dummy):
  340. if not app.config.break_to_pdb:
  341. return
  342. import pdb
  343. pdb.set_trace()
  344. def setup(app):
  345. app.add_role('ticket', ticket)
  346. app.add_config_value(
  347. 'ticket_base_uri',
  348. 'https://api.github.com/repos/QubesOS/qubes-issues/issues/{number}',
  349. 'env')
  350. app.add_config_value('break_to_pdb', False, 'env')
  351. app.add_node(versioncheck,
  352. html=(visit, depart),
  353. man=(visit, depart))
  354. app.add_directive('versioncheck', VersionCheck)
  355. fdesc = sphinx.util.docfields.GroupedField('parameter', label='Parameters',
  356. names=['param'], can_collapse=True)
  357. app.add_object_type('event', 'event', 'pair: %s; event', parse_event,
  358. doc_field_types=[fdesc])
  359. app.connect('doctree-resolved', break_to_pdb)
  360. app.connect('doctree-resolved', check_man_args)
  361. # vim: ts=4 sw=4 et