dochelpers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. #
  2. # The Qubes OS Project, https://www.qubes-os.org/
  3. #
  4. # Copyright (C) 2010-2015 Joanna Rutkowska <joanna@invisiblethingslab.com>
  5. # Copyright (C) 2014-2015 Wojtek Porczyk <woju@invisiblethingslab.com>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU Lesser General Public License as published by
  9. # the Free Software Foundation; either version 2.1 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. #
  21. '''Documentation helpers.
  22. This module contains classes and functions which help to maintain documentation,
  23. particularly our custom Sphinx extension.
  24. '''
  25. import argparse
  26. import io
  27. import os
  28. import re
  29. import docutils
  30. import docutils.nodes
  31. import docutils.parsers.rst
  32. import docutils.parsers.rst.roles
  33. import docutils.statemachine
  34. import sphinx
  35. import sphinx.errors
  36. import sphinx.locale
  37. import sphinx.util.docfields
  38. import qubesmgmt.tools
  39. SUBCOMMANDS_TITLE = 'COMMANDS'
  40. OPTIONS_TITLE = 'OPTIONS'
  41. def make_rst_section(heading, char):
  42. return '{}\n{}\n\n'.format(heading, char[0] * len(heading))
  43. def prepare_manpage(command):
  44. parser = qubesmgmt.tools.get_parser_for_command(command)
  45. stream = io.StringIO()
  46. stream.write('.. program:: {}\n\n'.format(command))
  47. stream.write(make_rst_section(
  48. ':program:`{}` -- {}'.format(command, parser.description), '='))
  49. stream.write('''.. warning::
  50. This page was autogenerated from command-line parser. It shouldn't be 1:1
  51. conversion, because it would add little value. Please revise it and add
  52. more descriptive help, which normally won't fit in standard ``--help``
  53. option.
  54. After rewrite, please remove this admonition.\n\n''')
  55. stream.write(make_rst_section('Synopsis', '-'))
  56. usage = ' '.join(parser.format_usage().strip().split())
  57. if usage.startswith('usage: '):
  58. usage = usage[len('usage: '):]
  59. # replace METAVARS with *METAVARS*
  60. usage = re.sub(r'\b([A-Z]{2,})\b', r'*\1*', usage)
  61. stream.write(':command:`{}` {}\n\n'.format(command, usage))
  62. stream.write(make_rst_section('Options', '-'))
  63. for action in parser._actions: # pylint: disable=protected-access
  64. stream.write('.. option:: ')
  65. if action.metavar:
  66. stream.write(', '.join('{}{}{}'.format(
  67. option,
  68. '=' if option.startswith('--') else ' ',
  69. action.metavar)
  70. for option in sorted(action.option_strings)))
  71. else:
  72. stream.write(', '.join(sorted(action.option_strings)))
  73. stream.write('\n\n {}\n\n'.format(action.help))
  74. stream.write(make_rst_section('Authors', '-'))
  75. stream.write('''\
  76. | Joanna Rutkowska <joanna at invisiblethingslab dot com>
  77. | Rafal Wojtczuk <rafal at invisiblethingslab dot com>
  78. | Marek Marczykowski <marmarek at invisiblethingslab dot com>
  79. | Wojtek Porczyk <woju at invisiblethingslab dot com>
  80. .. vim: ts=3 sw=3 et tw=80
  81. ''')
  82. return stream.getvalue()
  83. class OptionsCheckVisitor(docutils.nodes.SparseNodeVisitor):
  84. ''' Checks if the visited option nodes and the specified args are in sync.
  85. '''
  86. def __init__(self, command, args, document):
  87. assert isinstance(args, set)
  88. docutils.nodes.SparseNodeVisitor.__init__(self, document)
  89. self.command = command
  90. self.args = args
  91. def visit_desc(self, node):
  92. ''' Skips all but 'option' elements '''
  93. # pylint: disable=no-self-use
  94. if not node.get('desctype', None) == 'option':
  95. raise docutils.nodes.SkipChildren
  96. def visit_desc_name(self, node):
  97. ''' Checks if the option is defined `self.args` '''
  98. if not isinstance(node[0], docutils.nodes.Text):
  99. raise sphinx.errors.SphinxError('first child should be Text')
  100. arg = str(node[0])
  101. try:
  102. self.args.remove(arg)
  103. except KeyError:
  104. raise sphinx.errors.SphinxError(
  105. 'No such argument for {!r}: {!r}'.format(self.command, arg))
  106. def check_undocumented_arguments(self, ignored_options=None):
  107. ''' Call this to check if any undocumented arguments are left.
  108. While the documentation talks about a
  109. 'SparseNodeVisitor.depart_document()' function, this function does
  110. not exists. (For details see implementation of
  111. :py:method:`NodeVisitor.dispatch_departure()`) So we need to
  112. manually call this.
  113. '''
  114. if ignored_options is None:
  115. ignored_options = set()
  116. left_over_args = self.args - ignored_options
  117. if left_over_args:
  118. raise sphinx.errors.SphinxError(
  119. 'Undocumented arguments for command {!r}: {!r}'.format(
  120. self.command, ', '.join(sorted(left_over_args))))
  121. class CommandCheckVisitor(docutils.nodes.SparseNodeVisitor):
  122. ''' Checks if the visited sub command section nodes and the specified sub
  123. command args are in sync.
  124. '''
  125. def __init__(self, command, sub_commands, document):
  126. docutils.nodes.SparseNodeVisitor.__init__(self, document)
  127. self.command = command
  128. self.sub_commands = sub_commands
  129. def visit_section(self, node):
  130. ''' Checks if the visited sub-command section nodes exists and it
  131. options are in sync.
  132. Uses :py:class:`OptionsCheckVisitor` for checking
  133. sub-commands options
  134. '''
  135. # pylint: disable=no-self-use
  136. title = str(node[0][0])
  137. if title.upper() == SUBCOMMANDS_TITLE:
  138. return
  139. sub_cmd = self.command + ' ' + title
  140. try:
  141. args = self.sub_commands[title]
  142. options_visitor = OptionsCheckVisitor(sub_cmd, args, self.document)
  143. node.walkabout(options_visitor)
  144. options_visitor.check_undocumented_arguments(
  145. {'--help', '--quiet', '--verbose', '-h', '-q', '-v'})
  146. del self.sub_commands[title]
  147. except KeyError:
  148. raise sphinx.errors.SphinxError(
  149. 'No such sub-command {!r}'.format(sub_cmd))
  150. def visit_Text(self, node):
  151. ''' If the visited text node starts with 'alias: ', all the provided
  152. comma separted alias in this node, are removed from
  153. `self.sub_commands`
  154. '''
  155. # pylint: disable=invalid-name
  156. text = str(node).strip()
  157. if text.startswith('aliases:'):
  158. aliases = {a.strip() for a in text.split('aliases:')[1].split(',')}
  159. for alias in aliases:
  160. assert alias in self.sub_commands
  161. del self.sub_commands[alias]
  162. def check_undocumented_sub_commands(self):
  163. ''' Call this to check if any undocumented sub_commands are left.
  164. While the documentation talks about a
  165. 'SparseNodeVisitor.depart_document()' function, this function does
  166. not exists. (For details see implementation of
  167. :py:method:`NodeVisitor.dispatch_departure()`) So we need to
  168. manually call this.
  169. '''
  170. if self.sub_commands:
  171. raise sphinx.errors.SphinxError(
  172. 'Undocumented commands for {!r}: {!r}'.format(
  173. self.command, ', '.join(sorted(self.sub_commands.keys()))))
  174. class ManpageCheckVisitor(docutils.nodes.SparseNodeVisitor):
  175. ''' Checks if the sub-commands and options specified in the 'COMMAND' and
  176. 'OPTIONS' (case insensitve) sections in sync the command parser.
  177. '''
  178. def __init__(self, app, command, document):
  179. docutils.nodes.SparseNodeVisitor.__init__(self, document)
  180. try:
  181. parser = qubesmgmt.tools.get_parser_for_command(command)
  182. except ImportError:
  183. app.warn('cannot import module for command')
  184. self.parser = None
  185. return
  186. except AttributeError:
  187. raise sphinx.errors.SphinxError('cannot find parser in module')
  188. self.command = command
  189. self.parser = parser
  190. self.options = set()
  191. self.sub_commands = {}
  192. self.app = app
  193. # pylint: disable=protected-access
  194. for action in parser._actions:
  195. if action.help == argparse.SUPPRESS:
  196. continue
  197. if issubclass(action.__class__,
  198. qubesmgmt.tools.AliasedSubParsersAction):
  199. for cmd, cmd_parser in action._name_parser_map.items():
  200. self.sub_commands[cmd] = set()
  201. for sub_action in cmd_parser._actions:
  202. if sub_action.help != argparse.SUPPRESS:
  203. self.sub_commands[cmd].update(
  204. sub_action.option_strings)
  205. else:
  206. self.options.update(action.option_strings)
  207. def visit_section(self, node):
  208. ''' If section title is OPTIONS or COMMANDS dispatch the apropriate
  209. `NodeVisitor`.
  210. '''
  211. if self.parser is None:
  212. return
  213. section_title = str(node[0][0]).upper()
  214. if section_title == OPTIONS_TITLE:
  215. options_visitor = OptionsCheckVisitor(self.command, self.options,
  216. self.document)
  217. node.walkabout(options_visitor)
  218. options_visitor.check_undocumented_arguments()
  219. elif section_title == SUBCOMMANDS_TITLE:
  220. sub_cmd_visitor = CommandCheckVisitor(
  221. self.command, self.sub_commands, self.document)
  222. node.walkabout(sub_cmd_visitor)
  223. sub_cmd_visitor.check_undocumented_sub_commands()
  224. def check_man_args(app, doctree, docname):
  225. ''' Checks the manpage for undocumented or obsolete sub-commands and
  226. options.
  227. '''
  228. dirname, command = os.path.split(docname)
  229. if os.path.basename(dirname) != 'manpages':
  230. return
  231. app.info('Checking arguments for {!r}'.format(command))
  232. doctree.walk(ManpageCheckVisitor(app, command, doctree))
  233. def break_to_pdb(app, *dummy):
  234. if not app.config.break_to_pdb:
  235. return
  236. import pdb
  237. pdb.set_trace()
  238. def setup(app):
  239. app.add_config_value('break_to_pdb', False, 'env')
  240. app.connect('doctree-resolved', break_to_pdb)
  241. app.connect('doctree-resolved', check_man_args)
  242. # vim: ts=4 sw=4 et