Coverage for src/ensembl/utils/docs/entrypoints_ext.py: 100%

58 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-21 12:51 +0000

1# See the NOTICE file distributed with this work for additional information 

2# regarding copyright ownership. 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15"""Sphinx extension: auto-inject a CLI entry-points reference table into a Markdown page. 

16 

17At ``builder-inited`` time this extension: 

18 

191. Reads ``[project.scripts]`` from the ``pyproject.toml``. 

202. Builds a Markdown table mapping each script name to its Python target (``package.module:function``). 

213. Writes the table between two sentinel comments inside the target Markdown file, replacing whatever 

22 was there from a previous build so the file stays under version control and is always up-to-date. 

23 

24Enable it via :func:`~ensembl.utils.docs.config.build_config`:: 

25 

26 configure( 

27 globals(), 

28 ..., 

29 include_entrypoints=True, 

30 ) 

31 

32Optionally override the defaults in ``conf.py`` after the ``configure()`` call:: 

33 

34 entrypoints_target_file = "user_guide/usage.md" # relative to docs source dir 

35 entrypoints_toml_file = "../pyproject.toml" # relative to docs source dir 

36 

37""" 

38 

39import re 

40from pathlib import Path 

41from typing import Any 

42import tomllib 

43 

44from sphinx.application import Sphinx 

45from sphinx.util import logging as sphinx_logging 

46 

47import ensembl.utils 

48 

49logger = sphinx_logging.getLogger(__name__) 

50 

51# Sentinels written into the Markdown file. Everything between them is replaced 

52_SENTINEL_START = "<!-- entrypoints-table:start -->" 

53_SENTINEL_END = "<!-- entrypoints-table:end -->" 

54# Regex that matches the region between the two sentinels (inclusive) 

55_REGION_RE = re.compile(rf"{re.escape(_SENTINEL_START)}.*?{re.escape(_SENTINEL_END)}", re.DOTALL) 

56 

57 

58def _read_entry_points(toml_path: Path) -> dict[str, str]: 

59 """Parse ``project.scripts`` from a ``pyproject.toml`` file. 

60 

61 Args: 

62 toml_path: Absolute path to the ``pyproject.toml`` file. 

63 

64 Returns: 

65 Mapping of ``script-name`` to ``package.module:function``. Returns an empty dict when 

66 the section is absent. 

67 

68 """ 

69 with toml_path.open("rb") as fh: 

70 data = tomllib.load(fh) 

71 return data.get("project", {}).get("scripts", {}) 

72 

73 

74def _build_markdown_table(entry_points: dict[str, str]) -> str: 

75 """Render ``entry_points`` as a Markdown table string. 

76 

77 Args: 

78 entry_points: Mapping returned by :func:`_read_entry_points`. 

79 

80 Returns: 

81 A complete Markdown table, or a short italicised notice when ``entry_points`` is empty. 

82 

83 """ 

84 if not entry_points: 

85 return "_No entry points are defined in `pyproject.toml`._" 

86 max_cmd = max(len(cmd) for cmd in entry_points) 

87 max_target = max(len(target) for target in entry_points.values()) 

88 col_cmd = max(len("Command"), max_cmd) 

89 col_target = max(len("Python target"), max_target) 

90 header = f"| {'Command':<{col_cmd}} | {'Python target':<{col_target}} |" 

91 separator = f"| {'-' * col_cmd} | {'-' * col_target} |" 

92 rows = [ 

93 f"| `{cmd}`{' ' * (col_cmd - len(cmd) - 2)} | `{target}`{' ' * (col_target - len(target) - 2)} |" 

94 for cmd, target in sorted(entry_points.items()) 

95 ] 

96 return "\n".join([header, separator, *rows]) 

97 

98 

99def _inject_table(usage_path: Path, table_md: str) -> None: 

100 """Replace the sentinel region in ``usage_path`` with ``table_md``. 

101 

102 If the sentinels are not found the table and the sentinels are appended to the end of the file with 

103 a preceding blank line, so the extension is safe to add to a page that has not yet been prepared. 

104 

105 Args: 

106 usage_path: Absolute path to the target Markdown file. 

107 table_md: Rendered Markdown table produced by :func:`_build_markdown_table`. 

108 

109 """ 

110 original = usage_path.read_text(encoding="utf-8") 

111 replacement_block = f"{_SENTINEL_START}\n{table_md}\n{_SENTINEL_END}" 

112 if _REGION_RE.search(original): 

113 updated = _REGION_RE.sub(replacement_block, original) 

114 else: 

115 logger.warning( 

116 "entrypoints_table: sentinels not found in '%s'. Appending the table and a templated " 

117 "section at the end of the file.", 

118 usage_path, 

119 ) 

120 cli_section = ( 

121 "\n\n## CLI reference\n\nThe following commands are installed as entry points to ease " 

122 f"handling common tasks:\n\n{replacement_block}\n" 

123 ) 

124 updated = original.rstrip("\n") + cli_section 

125 usage_path.write_text(updated, encoding="utf-8") 

126 

127 

128def _on_builder_inited(app: Sphinx) -> None: 

129 """Sphinx event handler for ``builder-inited``. 

130 

131 Args: 

132 app: The Sphinx application object provided by the event system. 

133 

134 """ 

135 src_dir = Path(app.srcdir) 

136 target_rel: str = app.config.entrypoints_target_file # type: ignore[attr-defined] 

137 toml_rel: str = app.config.entrypoints_toml_file # type: ignore[attr-defined] 

138 usage_path = src_dir / target_rel 

139 toml_path = (src_dir / toml_rel).resolve() 

140 logger.info("entrypoints_table: reading entry points from '%s'", toml_path) 

141 try: 

142 entry_points = _read_entry_points(toml_path) 

143 except FileNotFoundError as exc: 

144 logger.warning("entrypoints_table: %s — skipping table generation.", exc) 

145 return 

146 table_md = _build_markdown_table(entry_points) 

147 if not usage_path.is_file(): 

148 logger.warning( 

149 "entrypoints_table: target file '%s' does not exist — skipping injection.", 

150 usage_path, 

151 ) 

152 return 

153 _inject_table(usage_path, table_md) 

154 logger.info("entrypoints_table: table injected into '%s'.", usage_path) 

155 

156 

157def setup(app: Sphinx) -> dict[str, Any]: 

158 """Register the extension with Sphinx. 

159 

160 Adds two optional ``conf.py`` configuration values: 

161 

162 - ``entrypoints_target_file``: Path to the Markdown file to inject into, relative to the Sphinx 

163 source directory. 

164 - ``entrypoints_toml_file``: Path to ``pyproject.toml``, relative to the Sphinx source directory. 

165 

166 Args: 

167 app: The Sphinx application object. 

168 

169 Returns: 

170 Sphinx extension metadata. 

171 

172 """ 

173 app.add_config_value("entrypoints_target_file", "user_guide/usage.md", "env") 

174 app.add_config_value("entrypoints_toml_file", "../pyproject.toml", "env") 

175 app.connect("builder-inited", _on_builder_inited) 

176 return { 

177 "version": ensembl.utils.__version__, 

178 "parallel_read_safe": True, 

179 "parallel_write_safe": True, 

180 }