dochelpers.py 15 KB

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