|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +Add the ability to specify the version for a specific page. |
| 4 | +
|
| 5 | +This allows you to put metadata at the top of your document:: |
| 6 | +
|
| 7 | + :version: 2.3 |
| 8 | +
|
| 9 | +This version should be the version of the project that this page or API targets. |
| 10 | +
|
| 11 | +If you configure ``versionwarning_node`` to True (default), |
| 12 | +then it will generate an in-page warning for out of date versions. |
| 13 | +
|
| 14 | +If you configure ``versionwarning_console`` to True (default), |
| 15 | +then it will output a warning on the console. |
| 16 | +""" |
| 17 | + |
| 18 | + |
| 19 | +from collections import defaultdict |
| 20 | + |
| 21 | +from sphinx.util.console import red, bold |
| 22 | +from docutils import nodes |
| 23 | + |
| 24 | + |
| 25 | +def process_meta(app, doctree, fromdocname): |
| 26 | + env = app.builder.env |
| 27 | + env.page_to_version = defaultdict(set) |
| 28 | + env.version_to_page = defaultdict(set) |
| 29 | + |
| 30 | + # index metadata |
| 31 | + for pagename, metadata in iter(env.metadata.items()): |
| 32 | + if 'version' in metadata: |
| 33 | + version = metadata['version'] |
| 34 | + env.page_to_version[pagename] = version |
| 35 | + env.version_to_page[version].add(pagename) |
| 36 | + |
| 37 | + if fromdocname == pagename: |
| 38 | + |
| 39 | + # Alert on outdated version |
| 40 | + current_version = env.config['version'] |
| 41 | + if version != current_version: |
| 42 | + text = 'This page documents version {old} and has not yet been updated for version {new}'.format( |
| 43 | + old=version, |
| 44 | + new=current_version, |
| 45 | + ) |
| 46 | + |
| 47 | + if app.config['versionwarning_node']: |
| 48 | + prose = nodes.paragraph(text, text) |
| 49 | + warning = nodes.warning(prose, prose) |
| 50 | + doctree.insert(0, warning) |
| 51 | + if app.config['versionwarning_console']: |
| 52 | + app.warn(bold('[Version Warning: %s] ' % pagename) + red(text)) |
| 53 | + |
| 54 | + |
| 55 | +def setup(app): |
| 56 | + app.connect('doctree-resolved', process_meta) |
| 57 | + app.add_config_value('versionwarning_node', True, 'html') |
| 58 | + app.add_config_value('versionwarning_console', True, 'html') |
0 commit comments