|
| 1 | +# fmt: off |
| 2 | +# Requires Python 3.6+ |
| 3 | +"""Sphinx extension for making titles with dates from Git tags.""" |
| 4 | + |
| 5 | + |
| 6 | +import subprocess # noqa: S404 |
| 7 | +import sys |
| 8 | +from functools import lru_cache |
| 9 | +from pathlib import Path |
| 10 | +from typing import Any, Dict, List, Union |
| 11 | + |
| 12 | +from sphinx.application import Sphinx |
| 13 | +from sphinx.util.docutils import SphinxDirective |
| 14 | +from sphinx.util.nodes import nodes |
| 15 | + |
| 16 | +# isort: split |
| 17 | + |
| 18 | +from docutils import statemachine |
| 19 | +from setuptools_scm import get_version |
| 20 | + |
| 21 | +PROJECT_ROOT_DIR = Path(__file__).parents[2].resolve() |
| 22 | +TOWNCRIER_DRAFT_CMD = ( |
| 23 | + sys.executable, '-m', # invoke via runpy under the same interpreter |
| 24 | + 'towncrier', |
| 25 | + '--draft', # write to stdout, don't change anything on disk |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +@lru_cache(typed=True) |
| 30 | +def _get_changelog_draft_entries( |
| 31 | + target_version: str, |
| 32 | + allow_empty: bool = False, |
| 33 | + working_dir: str = None, |
| 34 | + config_path: str = None, |
| 35 | +) -> str: |
| 36 | + """Retrieve the unreleased changelog entries from Towncrier.""" |
| 37 | + extra_cli_args = ( |
| 38 | + '--version', |
| 39 | + rf'\ {target_version}', # version value to be used in the RST title |
| 40 | + # NOTE: The escaped space sequence (`\ `) is necessary to address |
| 41 | + # NOTE: a corner case when the towncrier config has something like |
| 42 | + # NOTE: `v{version}` in the title format **and** the directive target |
| 43 | + # NOTE: argument starts with a substitution like `|release|`. And so |
| 44 | + # NOTE: when combined, they'd produce `v|release|` causing RST to not |
| 45 | + # NOTE: substitute the `|release|` part. But adding an escaped space |
| 46 | + # NOTE: solves this: that escaped space renders as an empty string and |
| 47 | + # NOTE: the substitution gets processed properly so the result would |
| 48 | + # NOTE: be something like `v1.0` as expected. |
| 49 | + ) |
| 50 | + if config_path is not None: |
| 51 | + # This isn't actually supported by a released version of Towncrier yet: |
| 52 | + # https://github.com/twisted/towncrier/pull/157#issuecomment-666549246 |
| 53 | + # https://github.com/twisted/towncrier/issues/269 |
| 54 | + extra_cli_args += '--config', str(config_path) |
| 55 | + towncrier_output = subprocess.check_output( # noqa: S603 |
| 56 | + TOWNCRIER_DRAFT_CMD + extra_cli_args, |
| 57 | + cwd=str(working_dir) if working_dir else None, |
| 58 | + universal_newlines=True, |
| 59 | + ).strip() |
| 60 | + |
| 61 | + if not allow_empty and 'No significant changes' in towncrier_output: |
| 62 | + raise LookupError('There are no unreleased changelog entries so far') |
| 63 | + |
| 64 | + return towncrier_output |
| 65 | + |
| 66 | + |
| 67 | +@lru_cache(maxsize=1, typed=True) |
| 68 | +def _autodetect_scm_version(): |
| 69 | + """Retrieve an SCM-based project version.""" |
| 70 | + for scm_checkout_path in Path(__file__).parents: # noqa: WPS500 |
| 71 | + is_scm_checkout = ( |
| 72 | + (scm_checkout_path / '.git').exists() |
| 73 | + or (scm_checkout_path / '.hg').exists() |
| 74 | + ) |
| 75 | + if is_scm_checkout: |
| 76 | + return get_version(root=scm_checkout_path) |
| 77 | + else: |
| 78 | + raise LookupError("Failed to locate the project's SCM repo") |
| 79 | + |
| 80 | + |
| 81 | +@lru_cache(maxsize=1, typed=True) |
| 82 | +def _get_draft_version_fallback(strategy: str, sphinx_config: Dict[str, Any]): |
| 83 | + """Generate a fallback version string for towncrier draft.""" |
| 84 | + known_strategies = {'scm-draft', 'scm', 'draft', 'sphinx-version', 'sphinx-release'} |
| 85 | + if strategy not in known_strategies: |
| 86 | + raise ValueError( |
| 87 | + 'Expected "stragegy" to be ' |
| 88 | + f'one of {known_strategies!r} but got {strategy!r}', |
| 89 | + ) |
| 90 | + |
| 91 | + if 'sphinx' in strategy: |
| 92 | + return ( |
| 93 | + sphinx_config.release |
| 94 | + if 'release' in strategy |
| 95 | + else sphinx_config.version |
| 96 | + ) |
| 97 | + |
| 98 | + draft_msg = '[UNRELEASED DRAFT]' |
| 99 | + msg_chunks = () |
| 100 | + if 'scm' in strategy: |
| 101 | + msg_chunks += (_autodetect_scm_version(),) |
| 102 | + if 'draft' in strategy: |
| 103 | + msg_chunks += (draft_msg,) |
| 104 | + |
| 105 | + return ' '.join(msg_chunks) |
| 106 | + |
| 107 | + |
| 108 | +class TowncrierDraftEntriesDirective(SphinxDirective): |
| 109 | + """Definition of the ``towncrier-draft-entries`` directive.""" |
| 110 | + |
| 111 | + has_content = True # default: False |
| 112 | + |
| 113 | + def run(self) -> List[nodes.Node]: |
| 114 | + """Generate a node tree in place of the directive.""" |
| 115 | + target_version = self.content[:1][0] if self.content[:1] else None |
| 116 | + if self.content[1:]: # inner content present |
| 117 | + raise self.error( |
| 118 | + f'Error in "{self.name!s}" directive: ' |
| 119 | + 'only one argument permitted.', |
| 120 | + ) |
| 121 | + |
| 122 | + config = self.state.document.settings.env.config # noqa: WPS219 |
| 123 | + autoversion_mode = config.towncrier_draft_autoversion_mode |
| 124 | + include_empty = config.towncrier_draft_include_empty |
| 125 | + |
| 126 | + try: |
| 127 | + draft_changes = _get_changelog_draft_entries( |
| 128 | + target_version |
| 129 | + or _get_draft_version_fallback(autoversion_mode, config), |
| 130 | + allow_empty=include_empty, |
| 131 | + working_dir=config.towncrier_draft_working_directory, |
| 132 | + config_path=config.towncrier_draft_config_path, |
| 133 | + ) |
| 134 | + except subprocess.CalledProcessError as proc_exc: |
| 135 | + raise self.error(proc_exc) |
| 136 | + except LookupError: |
| 137 | + return [] |
| 138 | + |
| 139 | + self.state_machine.insert_input( |
| 140 | + statemachine.string2lines(draft_changes), |
| 141 | + '[towncrier draft]', |
| 142 | + ) |
| 143 | + return [] |
| 144 | + |
| 145 | + |
| 146 | +def setup(app: Sphinx) -> Dict[str, Union[bool, str]]: |
| 147 | + """Initialize the extension.""" |
| 148 | + rebuild_trigger = 'html' # rebuild full html on settings change |
| 149 | + app.add_config_value( |
| 150 | + 'towncrier_draft_config_path', |
| 151 | + default=None, |
| 152 | + rebuild=rebuild_trigger, |
| 153 | + ) |
| 154 | + app.add_config_value( |
| 155 | + 'towncrier_draft_autoversion_mode', |
| 156 | + default='scm-draft', |
| 157 | + rebuild=rebuild_trigger, |
| 158 | + ) |
| 159 | + app.add_config_value( |
| 160 | + 'towncrier_draft_include_empty', |
| 161 | + default=True, |
| 162 | + rebuild=rebuild_trigger, |
| 163 | + ) |
| 164 | + app.add_config_value( |
| 165 | + 'towncrier_draft_working_directory', |
| 166 | + default=None, |
| 167 | + rebuild=rebuild_trigger, |
| 168 | + ) |
| 169 | + app.add_directive( |
| 170 | + 'towncrier-draft-entries', |
| 171 | + TowncrierDraftEntriesDirective, |
| 172 | + ) |
| 173 | + |
| 174 | + return { |
| 175 | + 'parallel_read_safe': True, |
| 176 | + 'parallel_write_safe': True, |
| 177 | + 'version': get_version(root=PROJECT_ROOT_DIR), |
| 178 | + } |
0 commit comments