sphinx-github-changelog 2.0.1__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/workflows/ci.yml +1 -0
  2. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.pre-commit-config.yaml +4 -4
  3. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/PKG-INFO +45 -19
  4. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/README.rst +44 -18
  5. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/pyproject.toml +1 -4
  6. sphinx_github_changelog-2.2.0/sphinx_github_changelog/__init__.py +5 -0
  7. sphinx_github_changelog-2.2.0/sphinx_github_changelog/changelog.py +179 -0
  8. sphinx_github_changelog-2.2.0/sphinx_github_changelog/config.py +55 -0
  9. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/sphinx_github_changelog/credentials.py +20 -12
  10. sphinx_github_changelog-2.2.0/sphinx_github_changelog/exceptions.py +13 -0
  11. sphinx_github_changelog-2.2.0/sphinx_github_changelog/github_releases.py +95 -0
  12. sphinx_github_changelog-2.2.0/sphinx_github_changelog/setup.py +26 -0
  13. sphinx_github_changelog-2.2.0/sphinx_github_changelog/urls.py +122 -0
  14. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/acceptance/test_all.py +4 -4
  15. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/conftest.py +11 -7
  16. sphinx_github_changelog-2.2.0/tests/unit/test_changelog.py +266 -0
  17. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/unit/test_git.py +37 -21
  18. sphinx_github_changelog-2.2.0/tests/unit/test_github_releases.py +115 -0
  19. sphinx_github_changelog-2.2.0/tests/unit/test_urls.py +103 -0
  20. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/uv.lock +110 -114
  21. sphinx_github_changelog-2.0.1/sphinx_github_changelog/__init__.py +0 -39
  22. sphinx_github_changelog-2.0.1/sphinx_github_changelog/changelog.py +0 -295
  23. sphinx_github_changelog-2.0.1/sphinx_github_changelog/urls.py +0 -110
  24. sphinx_github_changelog-2.0.1/tests/unit/test_changelog.py +0 -396
  25. sphinx_github_changelog-2.0.1/tests/unit/test_urls.py +0 -85
  26. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.editorconfig +0 -0
  27. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/CODEOWNERS +0 -0
  28. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  29. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/release.yml +0 -0
  30. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/renovate.json5 +0 -0
  31. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/workflows/autofix.yml +0 -0
  32. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.github/workflows/coverage-comment.yml +0 -0
  33. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.gitignore +0 -0
  34. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/.readthedocs.yml +0 -0
  35. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/CHANGELOG.rst +0 -0
  36. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/CODE_OF_CONDUCT.rst +0 -0
  37. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/CONTRIBUTING.rst +0 -0
  38. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/LICENSE +0 -0
  39. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/docs/Makefile +0 -0
  40. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/docs/conduct.rst +0 -0
  41. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/docs/conf.py +0 -0
  42. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/docs/contributing.rst +0 -0
  43. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/docs/index.rst +0 -0
  44. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/scripts/README.md +0 -0
  45. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/scripts/docs +0 -0
  46. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/scripts/lint +0 -0
  47. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/scripts/tests +0 -0
  48. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/__init__.py +0 -0
  49. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/acceptance/__init__.py +0 -0
  50. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/acceptance/changelog.html +0 -0
  51. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/roots/test-all/conf.py +0 -0
  52. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/roots/test-all/index.rst +0 -0
  53. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/roots/test-error/conf.py +0 -0
  54. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/roots/test-error/index.rst +0 -0
  55. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.2.0}/tests/unit/__init__.py +0 -0
@@ -97,6 +97,7 @@ jobs:
97
97
  name: Publish package to PyPI
98
98
  if: github.event_name == 'push' && github.ref_type == 'tag'
99
99
  runs-on: ubuntu-latest
100
+ environment: release
100
101
  permissions:
101
102
  id-token: write
102
103
  needs:
@@ -25,7 +25,7 @@ repos:
25
25
  - id: mixed-line-ending
26
26
 
27
27
  - repo: https://github.com/astral-sh/ruff-pre-commit
28
- rev: v0.15.13
28
+ rev: v0.15.14
29
29
  hooks:
30
30
  - id: ruff
31
31
  args: [--fix, --unsafe-fixes, --show-fixes]
@@ -38,20 +38,20 @@ repos:
38
38
  # - id: doc8
39
39
 
40
40
  - repo: https://github.com/DetachHead/basedpyright-prek-mirror
41
- rev: 1.39.4
41
+ rev: 1.39.5
42
42
  hooks:
43
43
  - id: basedpyright
44
44
  args: [--verbose]
45
45
 
46
46
  - repo: https://github.com/astral-sh/uv-pre-commit
47
47
  # uv version.
48
- rev: 0.11.14
48
+ rev: 0.11.16
49
49
  hooks:
50
50
  - id: uv-lock
51
51
 
52
52
  - repo: https://github.com/zizmorcore/zizmor-pre-commit
53
53
  # Zizmor version.
54
- rev: v1.25.1
54
+ rev: v1.25.2
55
55
  hooks:
56
56
  # Run the linter.
57
57
  - id: zizmor
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sphinx-github-changelog
3
- Version: 2.0.1
3
+ Version: 2.2.0
4
4
  Summary: Build a sphinx changelog from GitHub Releases
5
5
  Project-URL: Homepage, https://sphinx-github-changelog.readthedocs.io/en/latest/
6
6
  Project-URL: Repository, https://github.com/ewjoachim/sphinx-github-changelog
@@ -168,10 +168,18 @@ Authentication
168
168
  The extension uses the GitHub GraphQL API to retrieve the changelog. This
169
169
  requires authentication using a GitHub API token.
170
170
 
171
- However if you use git over HTTPS, or the ``gh`` CLI, you probably already have a
172
- suitable token, which ``sphinx-github-changelog`` will automatically use.
171
+ Tokens can be read from (in this order):
173
172
 
174
- In CI like GitHub Actions you can pass a token explicitly as an environment
173
+ - ``sphinx_github_changelog_token`` in ``conf.py`` (please do **NOT** commit your secrets)
174
+ - ``SPHINX_GITHUB_CHANGELOG_TOKEN`` environment variable
175
+ - ``GITHUB_TOKEN`` environment variable
176
+ - Your ``git`` configuration, using `git's credential system`_
177
+ - The ``gh`` command, using `the auth token command`_
178
+
179
+ .. _`git's credential system`: https://git-scm.com/docs/git-credential
180
+ .. _`the auth token command`: https://cli.github.com/manual/gh_auth_token
181
+
182
+ When using GitHub Actions, you can pass a token explicitly as an environment
175
183
  variable:
176
184
 
177
185
  .. code-block:: yaml
@@ -181,27 +189,45 @@ variable:
181
189
  env:
182
190
  SPHINX_GITHUB_CHANGELOG_TOKEN: ${{ github.token }}
183
191
 
184
- In remaining cases you may need to create a personal access token. If the
185
- repository is public, the token doesn't need any special access (you can
186
- uncheck eveything). For private and internal repositories, the token must
187
- have ``repo`` scope (classic tokens) or ``contents: read`` access (fine-grained
188
- tokens).
192
+ If you're not in one of the cases above (e.g. for ReadTheDocs, at least for the `time
193
+ being`__), you'll need a personal access token. If the repository is public, the token
194
+ doesn't need any special access (you can uncheck everything). For private and internal
195
+ repositories, the token must have ``repo`` scope (classic tokens) or ``contents: read``
196
+ access (fine-grained tokens).
197
+
198
+ .. __: https://github.com/readthedocs/readthedocs.org/issues/13053
189
199
 
190
- Pass the token as the ``SPHINX_GITHUB_CHANGELOG_TOKEN`` environment variable.
191
- You can also set the token as ``sphinx_github_changelog_token`` in ``conf.py``,
192
- but you should never commit secrets such as this.
200
+ Pass the token as the ``SPHINX_GITHUB_CHANGELOG_TOKEN`` (or ``GITHUB_TOKEN``)
201
+ environment variable. You can also set the token as ``sphinx_github_changelog_token`` in
202
+ ``conf.py``, but you should never commit secrets such as this.
193
203
 
194
204
 
195
205
  Extension options (``conf.py``)
196
206
  -------------------------------
197
207
 
198
- - ``sphinx_github_changelog_token``: GitHub API token, if needed.
199
-
200
- Two options are accepted for backwards compatibility, but are likely detected
201
- automatically from the ``:github:`` parameter to the directive:
202
-
203
- - ``sphinx_github_changelog_root_repo`` (optional): Root URL to the repository.
204
- - ``sphinx_github_changelog_graphql_url`` (optional): URL to GraphQL API.
208
+ All options can also be set via environment variables of the same name in uppercase
209
+ (e.g. ``SPHINX_GITHUB_CHANGELOG_TOKEN``).
210
+
211
+ .. list-table::
212
+ :header-rows: 1
213
+ :widths: 30 10 60
214
+
215
+ * - Option
216
+ - Default
217
+ - Description
218
+ * - ``sphinx_github_changelog_token``
219
+ - ``None``
220
+ - GitHub API token. See above (please do **NOT** commit your secrets).
221
+ * - ``sphinx_github_changelog_root_repo``
222
+ - ``None``
223
+ - Root URL to the repository. Usually detected automatically.
224
+ * - ``sphinx_github_changelog_graphql_url``
225
+ - ``None``
226
+ - URL to GraphQL API. Usually detected automatically.
227
+ * - ``sphinx_github_changelog_include_prereleases``
228
+ - ``True``
229
+ - Whether to include pre-releases in the changelog. Set to ``False``
230
+ to exclude them (env var accepts ``0``, ``false``, ``no``).
205
231
 
206
232
  .. _ReadTheDocs: https://readthedocs.org/
207
233
 
@@ -141,10 +141,18 @@ Authentication
141
141
  The extension uses the GitHub GraphQL API to retrieve the changelog. This
142
142
  requires authentication using a GitHub API token.
143
143
 
144
- However if you use git over HTTPS, or the ``gh`` CLI, you probably already have a
145
- suitable token, which ``sphinx-github-changelog`` will automatically use.
144
+ Tokens can be read from (in this order):
146
145
 
147
- In CI like GitHub Actions you can pass a token explicitly as an environment
146
+ - ``sphinx_github_changelog_token`` in ``conf.py`` (please do **NOT** commit your secrets)
147
+ - ``SPHINX_GITHUB_CHANGELOG_TOKEN`` environment variable
148
+ - ``GITHUB_TOKEN`` environment variable
149
+ - Your ``git`` configuration, using `git's credential system`_
150
+ - The ``gh`` command, using `the auth token command`_
151
+
152
+ .. _`git's credential system`: https://git-scm.com/docs/git-credential
153
+ .. _`the auth token command`: https://cli.github.com/manual/gh_auth_token
154
+
155
+ When using GitHub Actions, you can pass a token explicitly as an environment
148
156
  variable:
149
157
 
150
158
  .. code-block:: yaml
@@ -154,27 +162,45 @@ variable:
154
162
  env:
155
163
  SPHINX_GITHUB_CHANGELOG_TOKEN: ${{ github.token }}
156
164
 
157
- In remaining cases you may need to create a personal access token. If the
158
- repository is public, the token doesn't need any special access (you can
159
- uncheck eveything). For private and internal repositories, the token must
160
- have ``repo`` scope (classic tokens) or ``contents: read`` access (fine-grained
161
- tokens).
165
+ If you're not in one of the cases above (e.g. for ReadTheDocs, at least for the `time
166
+ being`__), you'll need a personal access token. If the repository is public, the token
167
+ doesn't need any special access (you can uncheck everything). For private and internal
168
+ repositories, the token must have ``repo`` scope (classic tokens) or ``contents: read``
169
+ access (fine-grained tokens).
170
+
171
+ .. __: https://github.com/readthedocs/readthedocs.org/issues/13053
162
172
 
163
- Pass the token as the ``SPHINX_GITHUB_CHANGELOG_TOKEN`` environment variable.
164
- You can also set the token as ``sphinx_github_changelog_token`` in ``conf.py``,
165
- but you should never commit secrets such as this.
173
+ Pass the token as the ``SPHINX_GITHUB_CHANGELOG_TOKEN`` (or ``GITHUB_TOKEN``)
174
+ environment variable. You can also set the token as ``sphinx_github_changelog_token`` in
175
+ ``conf.py``, but you should never commit secrets such as this.
166
176
 
167
177
 
168
178
  Extension options (``conf.py``)
169
179
  -------------------------------
170
180
 
171
- - ``sphinx_github_changelog_token``: GitHub API token, if needed.
172
-
173
- Two options are accepted for backwards compatibility, but are likely detected
174
- automatically from the ``:github:`` parameter to the directive:
175
-
176
- - ``sphinx_github_changelog_root_repo`` (optional): Root URL to the repository.
177
- - ``sphinx_github_changelog_graphql_url`` (optional): URL to GraphQL API.
181
+ All options can also be set via environment variables of the same name in uppercase
182
+ (e.g. ``SPHINX_GITHUB_CHANGELOG_TOKEN``).
183
+
184
+ .. list-table::
185
+ :header-rows: 1
186
+ :widths: 30 10 60
187
+
188
+ * - Option
189
+ - Default
190
+ - Description
191
+ * - ``sphinx_github_changelog_token``
192
+ - ``None``
193
+ - GitHub API token. See above (please do **NOT** commit your secrets).
194
+ * - ``sphinx_github_changelog_root_repo``
195
+ - ``None``
196
+ - Root URL to the repository. Usually detected automatically.
197
+ * - ``sphinx_github_changelog_graphql_url``
198
+ - ``None``
199
+ - URL to GraphQL API. Usually detected automatically.
200
+ * - ``sphinx_github_changelog_include_prereleases``
201
+ - ``True``
202
+ - Whether to include pre-releases in the changelog. Set to ``False``
203
+ to exclude them (env var accepts ``0``, ``false``, ``no``).
178
204
 
179
205
  .. _ReadTheDocs: https://readthedocs.org/
180
206
 
@@ -13,7 +13,7 @@ name = "sphinx-github-changelog"
13
13
  dynamic = ["version"]
14
14
  description = "Build a sphinx changelog from GitHub Releases"
15
15
  authors = [{ name = "Joachim Jablon", email = "ewjoachim@gmail.com" }]
16
- requires-python = ">=3.11"
16
+ requires-python = ">= 3.11"
17
17
  readme = "README.rst"
18
18
  license = "MIT"
19
19
  license-files = ["LICENSE"]
@@ -53,15 +53,12 @@ types = ["types-requests", "types-docutils"]
53
53
  [tool.uv]
54
54
  default-groups = ["dev", "docs"]
55
55
  exclude-newer = "5 days"
56
- # TODO: remove after 2026-05-21
57
- exclude-newer-package = { myst-parser = false, mdit-py-plugins = false }
58
56
 
59
57
  [tool.basedpyright]
60
58
  exclude = ["tests", ".venv", "scripts", ".github"]
61
59
  typeCheckingMode = "standard"
62
60
 
63
61
  [tool.ruff]
64
- target-version = "py39"
65
62
  extend-exclude = [".venv"]
66
63
 
67
64
  [tool.ruff.lint]
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .setup import setup
4
+
5
+ __all__: list = ["setup"]
@@ -0,0 +1,179 @@
1
+ from __future__ import annotations
2
+
3
+ from docutils import nodes
4
+ from docutils.frontend import get_default_settings
5
+ from docutils.parsers.rst import Directive, directives
6
+ from docutils.utils import new_document
7
+ from myst_parser.parsers.docutils_ import Parser
8
+
9
+ from . import config as config_module
10
+ from . import credentials, exceptions, github_releases, urls
11
+
12
+
13
+ class ChangelogDirective(Directive):
14
+ # defines the parameter the directive expects
15
+ # directives.unchanged means you get the raw value from RST
16
+ required_arguments = 0
17
+ optional_arguments = 0
18
+ final_argument_whitespace = True
19
+ option_spec = {
20
+ "changelog-url": directives.unchanged,
21
+ "github": directives.unchanged,
22
+ "pypi": directives.unchanged,
23
+ }
24
+ has_content = False
25
+ add_index = False
26
+
27
+ def run(self) -> list[nodes.Node]:
28
+ options = config_module.ChangelogDirectiveOptions.from_options(self.options)
29
+ config = config_module.ChangelogConfig.from_sphinx_env_config(
30
+ self.state.document.settings.env.config
31
+ )
32
+ try:
33
+ return compute_changelog(options=options, config=config)
34
+ except exceptions.ChangelogError as exc:
35
+ raise self.error(str(exc))
36
+
37
+
38
+ def compute_changelog(
39
+ options: config_module.ChangelogDirectiveOptions,
40
+ config: config_module.ChangelogConfig,
41
+ ) -> list[nodes.Node]:
42
+ try:
43
+ github_params = urls.extract_github_params(options=options, config=config)
44
+ except exceptions.CouldNotExtract as exc:
45
+ raise exceptions.ChangelogError(
46
+ "No :github: release URL provided and unable to determine it from "
47
+ "git remotes. Please provide a GitHub release URL in the format "
48
+ "(https://github.com/:owner/:repo/releases)"
49
+ ) from exc
50
+
51
+ # If token is not provided, try to get it from helpers
52
+ token = config.token
53
+ if not token:
54
+ try:
55
+ token = credentials.get_github_token(host=github_params.hostname)
56
+ except exceptions.CouldNotExtract:
57
+ return no_token(changelog_url=options.changelog_url)
58
+
59
+ releases = github_releases.extract_releases(
60
+ github_params=github_params,
61
+ token=token,
62
+ graphql_url=config.graphql_url,
63
+ )
64
+
65
+ pypi_name = extract_pypi_package_name(url=options.pypi)
66
+
67
+ if not config.include_prereleases:
68
+ releases = [r for r in releases if not r.is_prerelease]
69
+
70
+ result_nodes = (
71
+ node_for_release(release=release, pypi_name=pypi_name) for release in releases
72
+ )
73
+
74
+ return [n for n in result_nodes if n is not None]
75
+
76
+
77
+ def no_token(changelog_url: str | None) -> list[nodes.Node]:
78
+ par = nodes.paragraph()
79
+ par += nodes.Text(
80
+ "Changelog was not built because no GitHub authentication token was found. "
81
+ "An access token can be provided using the "
82
+ )
83
+ par += nodes.literal("", "SPHINX_GITHUB_CHANGELOG_TOKEN")
84
+ par += nodes.Text(" environment variable or the ")
85
+ par += nodes.literal("", "sphinx_github_changelog_token")
86
+ par += nodes.Text(" parameter in ")
87
+ par += nodes.literal("", "conf.py")
88
+ par += nodes.Text(
89
+ ", or it can be automatically located from a configured git credential helper."
90
+ )
91
+ result: list[nodes.Node] = [nodes.warning("", par)]
92
+
93
+ if changelog_url:
94
+ par2 = nodes.paragraph()
95
+ par2 += nodes.Text("Find the project changelog ")
96
+ par2 += nodes.reference("", "here", refuri=changelog_url)
97
+ par2 += nodes.Text(".")
98
+ result.append(nodes.tip("", par2))
99
+
100
+ return result
101
+
102
+
103
+ def extract_pypi_package_name(url: str | None) -> str | None:
104
+ if not url:
105
+ return None
106
+ stripped_url = url.rstrip("/")
107
+ prefix = "https://pypi.org/project/"
108
+ url_is_correct = stripped_url.startswith(prefix)
109
+ if not url_is_correct:
110
+ raise exceptions.ChangelogError(
111
+ "Changelog needs a PyPI project URL "
112
+ f"(https://pypi.org/project/:project). Received {url}"
113
+ )
114
+
115
+ return stripped_url[len(prefix) :]
116
+
117
+
118
+ def get_release_title(title: str | None, tag: str):
119
+ version = tag.removeprefix("v")
120
+ if not title:
121
+ return version
122
+ return title if version in title else f"{version}: {title}"
123
+
124
+
125
+ def node_for_release(
126
+ release: github_releases.Release,
127
+ pypi_name: str | None = None,
128
+ ) -> nodes.Node | None:
129
+ if release.is_draft:
130
+ return None # For now, draft releases are excluded
131
+
132
+ tag = release.tag_name
133
+ version = tag.removeprefix("v")
134
+ title = release.name
135
+ date = release.published_at.isoformat()
136
+ title = get_release_title(title=title, tag=tag)
137
+
138
+ # Section
139
+ id_section = nodes.make_id("release-" + version)
140
+ section = nodes.section(ids=[id_section])
141
+
142
+ section += nodes.title(text=title)
143
+
144
+ subtitle = nodes.emphasis()
145
+ subtitle += nodes.Text(f"Released on {date} - ")
146
+
147
+ # Links
148
+ subtitle += nodes.reference("", "GitHub", refuri=release.url)
149
+ if pypi_name:
150
+ subtitle += nodes.Text(" - ")
151
+ url = f"https://pypi.org/project/{pypi_name}/{version}/"
152
+ subtitle += nodes.reference("", "PyPI", refuri=url)
153
+
154
+ subtitle_paragraph = nodes.paragraph()
155
+ subtitle_paragraph += subtitle
156
+ section += subtitle_paragraph
157
+
158
+ section += convert_markdown_to_nodes(release.description)
159
+ return section
160
+
161
+
162
+ def convert_markdown_to_nodes(markdown: str | None) -> list[nodes.Node]:
163
+ """
164
+ Convert markdown to docutils nodes
165
+ """
166
+ if not markdown or not markdown.strip():
167
+ return []
168
+ parser = Parser()
169
+ settings = get_default_settings(parser)
170
+
171
+ settings.myst_gfm_only = True
172
+
173
+ settings.myst_heading_anchors = 3
174
+
175
+ document = new_document("changelog_text", settings=settings)
176
+
177
+ parser.parse(markdown, document)
178
+
179
+ return document.children
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import os
5
+ from collections.abc import Iterator
6
+ from typing import Any, ClassVar
7
+
8
+
9
+ @dataclasses.dataclass
10
+ class ChangelogDirectiveOptions:
11
+ changelog_url: str | None = None
12
+ github: str | None = None
13
+ pypi: str | None = None
14
+
15
+ @classmethod
16
+ def from_options(cls, options: dict[str, str]):
17
+ return cls(
18
+ changelog_url=options.get("changelog-url"),
19
+ github=options.get("github"),
20
+ pypi=options.get("pypi"),
21
+ )
22
+
23
+
24
+ @dataclasses.dataclass
25
+ class ChangelogConfig:
26
+ token: str | None = None
27
+ root_repo: str | None = None
28
+ graphql_url: str | None = None
29
+ include_prereleases: bool = True
30
+
31
+ prefix: ClassVar[str] = "sphinx_github_changelog"
32
+
33
+ @classmethod
34
+ def get_config_defaults(cls) -> Iterator[tuple[str, str | bool | None]]:
35
+ for field in dataclasses.fields(cls):
36
+ option_name = f"{cls.prefix}_{field.name}"
37
+ env_value = os.environ.get(option_name.upper())
38
+ if field.type == "bool":
39
+ default: str | bool | None = (
40
+ env_value.lower() not in ("0", "false", "no")
41
+ if env_value
42
+ else bool(field.default)
43
+ )
44
+ else:
45
+ default = env_value
46
+ yield option_name, default
47
+
48
+ @classmethod
49
+ def from_sphinx_env_config(cls, sphinx_config: Any):
50
+ return cls(
51
+ token=sphinx_config.sphinx_github_changelog_token,
52
+ root_repo=sphinx_config.sphinx_github_changelog_root_repo,
53
+ graphql_url=sphinx_config.sphinx_github_changelog_graphql_url,
54
+ include_prereleases=sphinx_config.sphinx_github_changelog_include_prereleases,
55
+ )
@@ -11,13 +11,18 @@ import os
11
11
  import subprocess
12
12
  from contextlib import suppress
13
13
 
14
+ from . import exceptions
14
15
 
15
- def get_token_from_env(host: str = "github.com") -> str | None:
16
+
17
+ def get_token_from_env() -> str | None:
16
18
  """Get a GitHub token from the SPHINX_GITHUB_CHANGELOG_TOKEN env var.
17
19
 
18
20
  Return None if the environment variable is not set.
19
21
  """
20
- return os.environ.get("SPHINX_GITHUB_CHANGELOG_TOKEN")
22
+ if "SPHINX_GITHUB_CHANGELOG_TOKEN" in os.environ:
23
+ return os.environ["SPHINX_GITHUB_CHANGELOG_TOKEN"]
24
+
25
+ return os.environ.get("GITHUB_TOKEN")
21
26
 
22
27
 
23
28
  def is_github_token(token: str) -> bool:
@@ -33,7 +38,7 @@ def is_github_token(token: str) -> bool:
33
38
  return token.startswith("gh") and len(token) > 4 and token[3] == "_"
34
39
 
35
40
 
36
- def get_token_from_git_credential(host: str = "github.com") -> str | None:
41
+ def get_token_from_git_credential(host: str) -> str | None:
37
42
  """
38
43
  Get a GitHub access token using git's credential helper.
39
44
 
@@ -47,14 +52,14 @@ def get_token_from_git_credential(host: str = "github.com") -> str | None:
47
52
  input=f"protocol=https\nhost={host}\n",
48
53
  text=True,
49
54
  )
50
- for ln in resp.splitlines():
51
- key, _, value = ln.partition("=")
55
+ for line in resp.splitlines():
56
+ key, value = line.split("=", maxsplit=1)
52
57
  if key == "password" and is_github_token(value):
53
58
  return value
54
59
  return None
55
60
 
56
61
 
57
- def get_token_from_gh_cli(host: str = "github.com") -> str | None:
62
+ def get_token_from_gh_cli(host: str) -> str | None:
58
63
  """Get a GitHub token using the GitHub CLI (gh auth token)."""
59
64
  with suppress(subprocess.CalledProcessError, FileNotFoundError):
60
65
  token = subprocess.check_output(
@@ -65,7 +70,7 @@ def get_token_from_gh_cli(host: str = "github.com") -> str | None:
65
70
  return None
66
71
 
67
72
 
68
- def get_github_token(host: str = "github.com") -> str | None:
73
+ def get_github_token(host: str) -> str:
69
74
  """
70
75
  Try to obtain a GitHub token using several mechanisms in order.
71
76
 
@@ -73,10 +78,13 @@ def get_github_token(host: str = "github.com") -> str | None:
73
78
  2. git credential helper
74
79
  3. gh CLI
75
80
 
76
- Returns None if no token is found.
81
+ Raises CouldNotExtract if no token is found.
77
82
  """
78
- return (
79
- get_token_from_env(host)
80
- or get_token_from_git_credential(host)
81
- or get_token_from_gh_cli(host)
83
+ token = (
84
+ get_token_from_env()
85
+ or get_token_from_git_credential(host=host)
86
+ or get_token_from_gh_cli(host=host)
82
87
  )
88
+ if not token:
89
+ raise exceptions.CouldNotExtract("No GitHub token found")
90
+ return token
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class ChangelogError(Exception):
5
+ pass
6
+
7
+
8
+ class CouldNotExtract(ChangelogError):
9
+ pass
10
+
11
+
12
+ class GitHubAPIError(ChangelogError):
13
+ pass
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import datetime
5
+ from collections.abc import Sequence
6
+
7
+ import httpx
8
+
9
+ from . import exceptions, urls
10
+
11
+
12
+ @dataclasses.dataclass
13
+ class Release:
14
+ name: str | None
15
+ description: str | None
16
+ url: str
17
+ tag_name: str
18
+ published_at: datetime.date
19
+ is_draft: bool
20
+ is_prerelease: bool
21
+
22
+ @classmethod
23
+ def from_graphql(cls, data: dict) -> Release:
24
+ return cls(
25
+ name=data["name"],
26
+ description=data["description"],
27
+ url=data["url"],
28
+ tag_name=data["tagName"],
29
+ published_at=datetime.date.fromisoformat(data["publishedAt"][:10]),
30
+ is_draft=data["isDraft"],
31
+ is_prerelease=data["isPrerelease"],
32
+ )
33
+
34
+
35
+ def extract_releases(
36
+ github_params: urls.GitHubParams,
37
+ token: str,
38
+ graphql_url: str | None = None,
39
+ ) -> Sequence[Release]:
40
+ query = """
41
+ query($owner: String!, $repo: String!) {
42
+ repository(owner: $owner, name: $repo) {
43
+ releases(orderBy: {field: CREATED_AT, direction: DESC}, first:100) {
44
+ nodes {
45
+ name, description, url, tagName, publishedAt, isDraft, isPrerelease
46
+ }
47
+ }
48
+ }
49
+ }
50
+ """
51
+ payload = {
52
+ "query": query,
53
+ "variables": {"owner": github_params.owner, "repo": github_params.repo},
54
+ }
55
+ url = graphql_url or github_params.graphql_url
56
+ result = github_call(url=url, payload=payload, token=token)
57
+ try:
58
+ releases = result["data"]["repository"]["releases"]["nodes"]
59
+ # Sort by publication date descending (API only supports CREATED_AT ordering)
60
+ # If you don't have the right to see draft releases, they're "None"
61
+ return sorted(
62
+ (Release.from_graphql(r) for r in releases if r),
63
+ key=lambda r: r.published_at,
64
+ reverse=True,
65
+ )
66
+ except (KeyError, TypeError):
67
+ raise exceptions.GitHubAPIError(
68
+ f"GitHub API error unexpected format:\n{result!r}"
69
+ )
70
+
71
+
72
+ def github_call(url: str, token: str, payload: dict) -> dict:
73
+ try:
74
+ response = httpx.post(
75
+ url, json=payload, headers={"Authorization": f"token {token}"}
76
+ ).raise_for_status()
77
+
78
+ except httpx.HTTPStatusError as exc:
79
+ # GraphQL always responds 200
80
+ raise exceptions.GitHubAPIError(
81
+ f"Unexpected GitHub API error status code: {exc.response.status_code}\n"
82
+ f"{exc.response.text}"
83
+ ) from exc
84
+ except httpx.HTTPError as exc:
85
+ raise exceptions.GitHubAPIError(
86
+ "Could not retrieve changelog from github: " + str(exc)
87
+ ) from exc
88
+
89
+ response_payload = response.json()
90
+ if "errors" in response_payload:
91
+ raise exceptions.GitHubAPIError(
92
+ "GitHub API error response: \n"
93
+ + "\n".join(e.get("message", str(e)) for e in response_payload["errors"])
94
+ )
95
+ return response_payload