sphinx-github-changelog 2.0.1__tar.gz → 2.1.1__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.1.1}/.github/workflows/ci.yml +1 -0
  2. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.pre-commit-config.yaml +4 -4
  3. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/PKG-INFO +27 -15
  4. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/README.rst +26 -14
  5. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/pyproject.toml +1 -4
  6. sphinx_github_changelog-2.1.1/sphinx_github_changelog/__init__.py +5 -0
  7. sphinx_github_changelog-2.1.1/sphinx_github_changelog/changelog.py +174 -0
  8. sphinx_github_changelog-2.1.1/sphinx_github_changelog/config.py +40 -0
  9. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/sphinx_github_changelog/credentials.py +20 -12
  10. sphinx_github_changelog-2.1.1/sphinx_github_changelog/exceptions.py +13 -0
  11. sphinx_github_changelog-2.1.1/sphinx_github_changelog/github_releases.py +88 -0
  12. sphinx_github_changelog-2.1.1/sphinx_github_changelog/setup.py +28 -0
  13. sphinx_github_changelog-2.1.1/sphinx_github_changelog/urls.py +122 -0
  14. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/acceptance/test_all.py +3 -4
  15. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/conftest.py +10 -7
  16. sphinx_github_changelog-2.1.1/tests/unit/test_changelog.py +239 -0
  17. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/unit/test_git.py +37 -21
  18. sphinx_github_changelog-2.1.1/tests/unit/test_github_releases.py +115 -0
  19. sphinx_github_changelog-2.1.1/tests/unit/test_urls.py +103 -0
  20. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/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.1.1}/.editorconfig +0 -0
  27. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.github/CODEOWNERS +0 -0
  28. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  29. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.github/release.yml +0 -0
  30. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.github/renovate.json5 +0 -0
  31. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.github/workflows/autofix.yml +0 -0
  32. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.github/workflows/coverage-comment.yml +0 -0
  33. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.gitignore +0 -0
  34. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/.readthedocs.yml +0 -0
  35. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/CHANGELOG.rst +0 -0
  36. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/CODE_OF_CONDUCT.rst +0 -0
  37. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/CONTRIBUTING.rst +0 -0
  38. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/LICENSE +0 -0
  39. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/docs/Makefile +0 -0
  40. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/docs/conduct.rst +0 -0
  41. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/docs/conf.py +0 -0
  42. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/docs/contributing.rst +0 -0
  43. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/docs/index.rst +0 -0
  44. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/scripts/README.md +0 -0
  45. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/scripts/docs +0 -0
  46. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/scripts/lint +0 -0
  47. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/scripts/tests +0 -0
  48. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/__init__.py +0 -0
  49. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/acceptance/__init__.py +0 -0
  50. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/acceptance/changelog.html +0 -0
  51. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/roots/test-all/conf.py +0 -0
  52. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/roots/test-all/index.rst +0 -0
  53. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/roots/test-error/conf.py +0 -0
  54. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/tests/roots/test-error/index.rst +0 -0
  55. {sphinx_github_changelog-2.0.1 → sphinx_github_changelog-2.1.1}/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.1.1
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,24 +189,28 @@ 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.
208
+ - ``sphinx_github_changelog_token`` (optional): GitHub API token, if needed, see above
209
+ (please do **NOT** commit your secrets).
199
210
 
200
- Two options are accepted for backwards compatibility, but are likely detected
201
- automatically from the ``:github:`` parameter to the directive:
211
+ The following options are useful in some cases, though most of the time, the
212
+ corresponding values will be detected automatically from the ``:github:`` parameter
213
+ passed to the directive:
202
214
 
203
215
  - ``sphinx_github_changelog_root_repo`` (optional): Root URL to the repository.
204
216
  - ``sphinx_github_changelog_graphql_url`` (optional): URL to GraphQL API.
@@ -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,24 +162,28 @@ 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.
181
+ - ``sphinx_github_changelog_token`` (optional): GitHub API token, if needed, see above
182
+ (please do **NOT** commit your secrets).
172
183
 
173
- Two options are accepted for backwards compatibility, but are likely detected
174
- automatically from the ``:github:`` parameter to the directive:
184
+ The following options are useful in some cases, though most of the time, the
185
+ corresponding values will be detected automatically from the ``:github:`` parameter
186
+ passed to the directive:
175
187
 
176
188
  - ``sphinx_github_changelog_root_repo`` (optional): Root URL to the repository.
177
189
  - ``sphinx_github_changelog_graphql_url`` (optional): URL to GraphQL API.
@@ -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,174 @@
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
+ result_nodes = (
68
+ node_for_release(release=release, pypi_name=pypi_name) for release in releases
69
+ )
70
+
71
+ return [n for n in result_nodes if n is not None]
72
+
73
+
74
+ def no_token(changelog_url: str | None) -> list[nodes.Node]:
75
+ par = nodes.paragraph()
76
+ par += nodes.Text(
77
+ "Changelog was not built because no GitHub authentication token was found. "
78
+ "An access token can be provided using the "
79
+ )
80
+ par += nodes.literal("", "SPHINX_GITHUB_CHANGELOG_TOKEN")
81
+ par += nodes.Text(" environment variable or the ")
82
+ par += nodes.literal("", "sphinx_github_changelog_token")
83
+ par += nodes.Text(" parameter in ")
84
+ par += nodes.literal("", "conf.py")
85
+ par += nodes.Text(
86
+ ", or it can be automatically located from a configured git credential helper."
87
+ )
88
+ result: list[nodes.Node] = [nodes.warning("", par)]
89
+
90
+ if changelog_url:
91
+ par2 = nodes.paragraph()
92
+ par2 += nodes.Text("Find the project changelog ")
93
+ par2 += nodes.reference("", "here", refuri=changelog_url)
94
+ par2 += nodes.Text(".")
95
+ result.append(nodes.tip("", par2))
96
+
97
+ return result
98
+
99
+
100
+ def extract_pypi_package_name(url: str | None) -> str | None:
101
+ if not url:
102
+ return None
103
+ stripped_url = url.rstrip("/")
104
+ prefix = "https://pypi.org/project/"
105
+ url_is_correct = stripped_url.startswith(prefix)
106
+ if not url_is_correct:
107
+ raise exceptions.ChangelogError(
108
+ "Changelog needs a PyPI project URL "
109
+ f"(https://pypi.org/project/:project). Received {url}"
110
+ )
111
+
112
+ return stripped_url[len(prefix) :]
113
+
114
+
115
+ def get_release_title(title: str | None, tag: str):
116
+ if not title:
117
+ return tag
118
+ return title if tag in title else f"{tag}: {title}"
119
+
120
+
121
+ def node_for_release(
122
+ release: github_releases.Release,
123
+ pypi_name: str | None = None,
124
+ ) -> nodes.Node | None:
125
+ if release.is_draft:
126
+ return None # For now, draft releases are excluded
127
+
128
+ tag = release.tag_name
129
+ title = release.name
130
+ date = release.published_at.isoformat()
131
+ title = get_release_title(title=title, tag=tag)
132
+
133
+ # Section
134
+ id_section = nodes.make_id("release-" + tag)
135
+ section = nodes.section(ids=[id_section])
136
+
137
+ section += nodes.title(text=title)
138
+
139
+ subtitle = nodes.emphasis()
140
+ subtitle += nodes.Text(f"Released on {date} - ")
141
+
142
+ # Links
143
+ subtitle += nodes.reference("", "GitHub", refuri=release.url)
144
+ if pypi_name:
145
+ subtitle += nodes.Text(" - ")
146
+ url = f"https://pypi.org/project/{pypi_name}/{tag}/"
147
+ subtitle += nodes.reference("", "PyPI", refuri=url)
148
+
149
+ subtitle_paragraph = nodes.paragraph()
150
+ subtitle_paragraph += subtitle
151
+ section += subtitle_paragraph
152
+
153
+ section += convert_markdown_to_nodes(release.description)
154
+ return section
155
+
156
+
157
+ def convert_markdown_to_nodes(markdown: str | None) -> list[nodes.Node]:
158
+ """
159
+ Convert markdown to docutils nodes
160
+ """
161
+ if not markdown or not markdown.strip():
162
+ return []
163
+ parser = Parser()
164
+ settings = get_default_settings(parser)
165
+
166
+ settings.myst_gfm_only = True
167
+
168
+ settings.myst_heading_anchors = 3
169
+
170
+ document = new_document("changelog_text", settings=settings)
171
+
172
+ parser.parse(markdown, document)
173
+
174
+ return document.children
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ from typing import Any, ClassVar
5
+
6
+
7
+ @dataclasses.dataclass
8
+ class ChangelogDirectiveOptions:
9
+ changelog_url: str | None = None
10
+ github: str | None = None
11
+ pypi: str | None = None
12
+
13
+ @classmethod
14
+ def from_options(cls, options: dict[str, str]):
15
+ return cls(
16
+ changelog_url=options.get("changelog-url"),
17
+ github=options.get("github"),
18
+ pypi=options.get("pypi"),
19
+ )
20
+
21
+
22
+ @dataclasses.dataclass
23
+ class ChangelogConfig:
24
+ token: str | None = None
25
+ root_repo: str | None = None
26
+ graphql_url: str | None = None
27
+
28
+ prefix: ClassVar[str] = "sphinx_github_changelog"
29
+
30
+ @classmethod
31
+ def get_field_names(cls) -> list[str]:
32
+ return [f.name for f in dataclasses.fields(cls)]
33
+
34
+ @classmethod
35
+ def from_sphinx_env_config(cls, sphinx_config: Any):
36
+ return cls(
37
+ token=sphinx_config.sphinx_github_changelog_token,
38
+ root_repo=sphinx_config.sphinx_github_changelog_root_repo,
39
+ graphql_url=sphinx_config.sphinx_github_changelog_graphql_url,
40
+ )
@@ -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,88 @@
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
+
21
+ @classmethod
22
+ def from_graphql(cls, data: dict) -> Release:
23
+ return cls(
24
+ name=data["name"],
25
+ description=data["description"],
26
+ url=data["url"],
27
+ tag_name=data["tagName"],
28
+ published_at=datetime.date.fromisoformat(data["publishedAt"][:10]),
29
+ is_draft=data["isDraft"],
30
+ )
31
+
32
+
33
+ def extract_releases(
34
+ github_params: urls.GitHubParams,
35
+ token: str,
36
+ graphql_url: str | None = None,
37
+ ) -> Sequence[Release]:
38
+ query = """
39
+ query($owner: String!, $repo: String!) {
40
+ repository(owner: $owner, name: $repo) {
41
+ releases(orderBy: {field: CREATED_AT, direction: DESC}, first:100) {
42
+ nodes {
43
+ name, description, url, tagName, publishedAt, isDraft
44
+ }
45
+ }
46
+ }
47
+ }
48
+ """
49
+ payload = {
50
+ "query": query,
51
+ "variables": {"owner": github_params.owner, "repo": github_params.repo},
52
+ }
53
+ url = graphql_url or github_params.graphql_url
54
+ result = github_call(url=url, payload=payload, token=token)
55
+ try:
56
+ releases = result["data"]["repository"]["releases"]["nodes"]
57
+ # If you don't have the right to see draft releases, they're "None"
58
+ return [Release.from_graphql(r) for r in releases if r]
59
+ except (KeyError, TypeError):
60
+ raise exceptions.GitHubAPIError(
61
+ f"GitHub API error unexpected format:\n{result!r}"
62
+ )
63
+
64
+
65
+ def github_call(url: str, token: str, payload: dict) -> dict:
66
+ try:
67
+ response = httpx.post(
68
+ url, json=payload, headers={"Authorization": f"token {token}"}
69
+ ).raise_for_status()
70
+
71
+ except httpx.HTTPStatusError as exc:
72
+ # GraphQL always responds 200
73
+ raise exceptions.GitHubAPIError(
74
+ f"Unexpected GitHub API error status code: {exc.response.status_code}\n"
75
+ f"{exc.response.text}"
76
+ ) from exc
77
+ except httpx.HTTPError as exc:
78
+ raise exceptions.GitHubAPIError(
79
+ "Could not retrieve changelog from github: " + str(exc)
80
+ ) from exc
81
+
82
+ response_payload = response.json()
83
+ if "errors" in response_payload:
84
+ raise exceptions.GitHubAPIError(
85
+ "GitHub API error response: \n"
86
+ + "\n".join(e.get("message", str(e)) for e in response_payload["errors"])
87
+ )
88
+ return response_payload
@@ -0,0 +1,28 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib.metadata
4
+ import os
5
+
6
+ from . import changelog, config
7
+
8
+
9
+ def version() -> str:
10
+ return importlib.metadata.version("sphinx-github-changelog")
11
+
12
+
13
+ def setup(app):
14
+ for name in config.ChangelogConfig.get_field_names():
15
+ option_name = f"{config.ChangelogConfig.prefix}_{name}"
16
+ app.add_config_value(
17
+ name=option_name,
18
+ default=os.environ.get(option_name.upper()),
19
+ rebuild="html",
20
+ )
21
+
22
+ app.add_directive("changelog", changelog.ChangelogDirective)
23
+
24
+ return {
25
+ "version": version(),
26
+ "parallel_read_safe": True,
27
+ "parallel_write_safe": True,
28
+ }