PyGithub-asyncio 3.0.0b1__py3-none-any.whl

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 (188) hide show
  1. githubasyncio/AccessToken.py +159 -0
  2. githubasyncio/AdvisoryBase.py +163 -0
  3. githubasyncio/AdvisoryCredit.py +131 -0
  4. githubasyncio/AdvisoryCreditDetailed.py +110 -0
  5. githubasyncio/AdvisoryVulnerability.py +191 -0
  6. githubasyncio/AdvisoryVulnerabilityPackage.py +93 -0
  7. githubasyncio/AppAuthentication.py +58 -0
  8. githubasyncio/ApplicationOAuth.py +200 -0
  9. githubasyncio/Artifact.py +183 -0
  10. githubasyncio/Auth.py +560 -0
  11. githubasyncio/AuthenticatedUser.py +1251 -0
  12. githubasyncio/Authorization.py +192 -0
  13. githubasyncio/AuthorizationApplication.py +73 -0
  14. githubasyncio/Autolink.py +104 -0
  15. githubasyncio/Branch.py +689 -0
  16. githubasyncio/BranchProtection.py +224 -0
  17. githubasyncio/CVSS.py +83 -0
  18. githubasyncio/CWE.py +75 -0
  19. githubasyncio/CheckRun.py +315 -0
  20. githubasyncio/CheckRunAnnotation.py +134 -0
  21. githubasyncio/CheckRunOutput.py +108 -0
  22. githubasyncio/CheckSuite.py +319 -0
  23. githubasyncio/Clones.py +97 -0
  24. githubasyncio/CodeScanAlert.py +215 -0
  25. githubasyncio/CodeScanAlertInstance.py +134 -0
  26. githubasyncio/CodeScanAlertInstanceLocation.py +102 -0
  27. githubasyncio/CodeScanRule.py +134 -0
  28. githubasyncio/CodeScanTool.py +94 -0
  29. githubasyncio/CodeSecurityConfig.py +301 -0
  30. githubasyncio/CodeSecurityConfigRepository.py +70 -0
  31. githubasyncio/Commit.py +442 -0
  32. githubasyncio/CommitCombinedStatus.py +126 -0
  33. githubasyncio/CommitComment.py +270 -0
  34. githubasyncio/CommitStats.py +78 -0
  35. githubasyncio/CommitStatus.py +169 -0
  36. githubasyncio/Comparison.py +219 -0
  37. githubasyncio/Consts.py +197 -0
  38. githubasyncio/ContentFile.py +304 -0
  39. githubasyncio/Copilot.py +97 -0
  40. githubasyncio/CopilotSeat.py +132 -0
  41. githubasyncio/DefaultCodeSecurityConfig.py +93 -0
  42. githubasyncio/DependabotAlert.py +184 -0
  43. githubasyncio/DependabotAlertAdvisory.py +82 -0
  44. githubasyncio/DependabotAlertDependency.py +100 -0
  45. githubasyncio/DependabotAlertVulnerability.py +85 -0
  46. githubasyncio/Deployment.py +314 -0
  47. githubasyncio/DeploymentBranchPolicy.py +102 -0
  48. githubasyncio/DeploymentStatus.py +201 -0
  49. githubasyncio/DiscussionBase.py +140 -0
  50. githubasyncio/DiscussionCommentBase.py +140 -0
  51. githubasyncio/Download.py +256 -0
  52. githubasyncio/Enterprise.py +175 -0
  53. githubasyncio/EnterpriseConsumedLicenses.py +138 -0
  54. githubasyncio/Environment.py +354 -0
  55. githubasyncio/EnvironmentDeploymentBranchPolicy.py +87 -0
  56. githubasyncio/EnvironmentProtectionRule.py +117 -0
  57. githubasyncio/EnvironmentProtectionRuleReviewer.py +110 -0
  58. githubasyncio/Event.py +134 -0
  59. githubasyncio/File.py +142 -0
  60. githubasyncio/GeneratedReleaseNotes.py +68 -0
  61. githubasyncio/Gist.py +373 -0
  62. githubasyncio/GistComment.py +162 -0
  63. githubasyncio/GistFile.py +106 -0
  64. githubasyncio/GistHistoryState.py +245 -0
  65. githubasyncio/GitAuthor.py +94 -0
  66. githubasyncio/GitBlob.py +123 -0
  67. githubasyncio/GitCommit.py +208 -0
  68. githubasyncio/GitCommitVerification.py +103 -0
  69. githubasyncio/GitObject.py +84 -0
  70. githubasyncio/GitRef.py +122 -0
  71. githubasyncio/GitRelease.py +476 -0
  72. githubasyncio/GitReleaseAsset.py +232 -0
  73. githubasyncio/GitTag.py +143 -0
  74. githubasyncio/GitTree.py +113 -0
  75. githubasyncio/GitTreeElement.py +104 -0
  76. githubasyncio/GithubApp.py +236 -0
  77. githubasyncio/GithubException.py +226 -0
  78. githubasyncio/GithubIntegration.py +365 -0
  79. githubasyncio/GithubObject.py +910 -0
  80. githubasyncio/GithubRetry.py +253 -0
  81. githubasyncio/GitignoreTemplate.py +88 -0
  82. githubasyncio/GlobalAdvisory.py +141 -0
  83. githubasyncio/Hook.py +238 -0
  84. githubasyncio/HookDelivery.py +243 -0
  85. githubasyncio/HookDescription.py +85 -0
  86. githubasyncio/HookResponse.py +83 -0
  87. githubasyncio/InputFileContent.py +63 -0
  88. githubasyncio/InputGitAuthor.py +71 -0
  89. githubasyncio/InputGitTreeElement.py +79 -0
  90. githubasyncio/Installation.py +298 -0
  91. githubasyncio/InstallationAuthorization.py +138 -0
  92. githubasyncio/Invitation.py +171 -0
  93. githubasyncio/Issue.py +955 -0
  94. githubasyncio/IssueComment.py +309 -0
  95. githubasyncio/IssueDependenciesSummary.py +77 -0
  96. githubasyncio/IssueEvent.py +296 -0
  97. githubasyncio/IssuePullRequest.py +97 -0
  98. githubasyncio/IssueType.py +123 -0
  99. githubasyncio/Label.py +186 -0
  100. githubasyncio/License.py +169 -0
  101. githubasyncio/MainClass.py +1142 -0
  102. githubasyncio/Membership.py +154 -0
  103. githubasyncio/MergedUpstream.py +71 -0
  104. githubasyncio/Migration.py +281 -0
  105. githubasyncio/Milestone.py +255 -0
  106. githubasyncio/NamedEnterpriseUser.py +207 -0
  107. githubasyncio/NamedUser.py +841 -0
  108. githubasyncio/Notification.py +182 -0
  109. githubasyncio/NotificationSubject.py +96 -0
  110. githubasyncio/Organization.py +2462 -0
  111. githubasyncio/OrganizationCodeScanAlert.py +65 -0
  112. githubasyncio/OrganizationCustomProperty.py +215 -0
  113. githubasyncio/OrganizationDependabotAlert.py +75 -0
  114. githubasyncio/OrganizationSecret.py +191 -0
  115. githubasyncio/OrganizationSecretScanAlert.py +112 -0
  116. githubasyncio/OrganizationVariable.py +141 -0
  117. githubasyncio/PaginatedList.py +652 -0
  118. githubasyncio/Path.py +102 -0
  119. githubasyncio/Permissions.py +113 -0
  120. githubasyncio/Plan.py +108 -0
  121. githubasyncio/Project.py +286 -0
  122. githubasyncio/ProjectCard.py +257 -0
  123. githubasyncio/ProjectColumn.py +227 -0
  124. githubasyncio/PublicKey.py +138 -0
  125. githubasyncio/PullRequest.py +1202 -0
  126. githubasyncio/PullRequestComment.py +401 -0
  127. githubasyncio/PullRequestMergeStatus.py +89 -0
  128. githubasyncio/PullRequestPart.py +110 -0
  129. githubasyncio/PullRequestReview.py +214 -0
  130. githubasyncio/Rate.py +123 -0
  131. githubasyncio/RateLimit.py +210 -0
  132. githubasyncio/RateLimitOverview.py +104 -0
  133. githubasyncio/Reaction.py +128 -0
  134. githubasyncio/Referrer.py +94 -0
  135. githubasyncio/RepoCodeSecurityConfig.py +93 -0
  136. githubasyncio/Repository.py +5211 -0
  137. githubasyncio/RepositoryAdvisory.py +431 -0
  138. githubasyncio/RepositoryDiscussion.py +221 -0
  139. githubasyncio/RepositoryDiscussionCategory.py +150 -0
  140. githubasyncio/RepositoryDiscussionComment.py +159 -0
  141. githubasyncio/RepositoryKey.py +166 -0
  142. githubasyncio/RepositoryPreferences.py +82 -0
  143. githubasyncio/RepositoryRulesetBypassActor.py +75 -0
  144. githubasyncio/Requester.py +1518 -0
  145. githubasyncio/RequiredPullRequestReviews.py +269 -0
  146. githubasyncio/RequiredStatusChecks.py +153 -0
  147. githubasyncio/Rule.py +134 -0
  148. githubasyncio/Ruleset.py +292 -0
  149. githubasyncio/Secret.py +139 -0
  150. githubasyncio/SecretScanAlert.py +317 -0
  151. githubasyncio/SecretScanAlertInstance.py +128 -0
  152. githubasyncio/SecurityAndAnalysis.py +188 -0
  153. githubasyncio/SecurityAndAnalysisFeature.py +79 -0
  154. githubasyncio/SelfHostedActionsRunner.py +129 -0
  155. githubasyncio/SelfHostedActionsRunnerApplication.py +92 -0
  156. githubasyncio/SelfHostedActionsRunnerJitConfig.py +74 -0
  157. githubasyncio/SelfHostedActionsRunnerToken.py +118 -0
  158. githubasyncio/SourceImport.py +260 -0
  159. githubasyncio/Stargazer.py +88 -0
  160. githubasyncio/StatsCodeFrequency.py +81 -0
  161. githubasyncio/StatsCommitActivity.py +86 -0
  162. githubasyncio/StatsContributor.py +138 -0
  163. githubasyncio/StatsParticipation.py +78 -0
  164. githubasyncio/StatsPunchCard.py +76 -0
  165. githubasyncio/SubIssueSummary.py +70 -0
  166. githubasyncio/Tag.py +108 -0
  167. githubasyncio/Team.py +618 -0
  168. githubasyncio/TeamDiscussion.py +137 -0
  169. githubasyncio/TimelineEvent.py +164 -0
  170. githubasyncio/TimelineEventSource.py +81 -0
  171. githubasyncio/Topic.py +177 -0
  172. githubasyncio/Traffic.py +95 -0
  173. githubasyncio/UserKey.py +141 -0
  174. githubasyncio/Variable.py +155 -0
  175. githubasyncio/View.py +97 -0
  176. githubasyncio/Workflow.py +335 -0
  177. githubasyncio/WorkflowJob.py +253 -0
  178. githubasyncio/WorkflowRun.py +480 -0
  179. githubasyncio/WorkflowStep.py +118 -0
  180. githubasyncio/__init__.py +38 -0
  181. githubasyncio/compat/__init__.py +52 -0
  182. githubasyncio/requestlib/__init__.py +29 -0
  183. pygithub_asyncio-3.0.0b1.dist-info/METADATA +102 -0
  184. pygithub_asyncio-3.0.0b1.dist-info/RECORD +188 -0
  185. pygithub_asyncio-3.0.0b1.dist-info/WHEEL +5 -0
  186. pygithub_asyncio-3.0.0b1.dist-info/licenses/COPYING +674 -0
  187. pygithub_asyncio-3.0.0b1.dist-info/licenses/COPYING.LESSER +165 -0
  188. pygithub_asyncio-3.0.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,652 @@
1
+ # FILE AUTO GENERATED DO NOT TOUCH
2
+ ############################ Copyrights and license ############################
3
+ # #
4
+ # Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
5
+ # Copyright 2012 Zearin <zearin@gonk.net> #
6
+ # Copyright 2013 AKFish <akfish@gmail.com> #
7
+ # Copyright 2013 Bill Mill <bill.mill@gmail.com> #
8
+ # Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
9
+ # Copyright 2013 davidbrai <davidbrai@gmail.com> #
10
+ # Copyright 2014 Thialfihar <thi@thialfihar.org> #
11
+ # Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
12
+ # Copyright 2015 Dan Vanderkam <danvdk@gmail.com> #
13
+ # Copyright 2015 Eliot Walker <eliot@lyft.com> #
14
+ # Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
15
+ # Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
16
+ # Copyright 2018 Gilad Shefer <gshefer@redhat.com> #
17
+ # Copyright 2018 Joel Koglin <JoelKoglin@gmail.com> #
18
+ # Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
19
+ # Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
20
+ # Copyright 2018 netsgnut <284779+netsgnut@users.noreply.github.com> #
21
+ # Copyright 2018 sfdye <tsfdye@gmail.com> #
22
+ # Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
23
+ # Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
24
+ # Copyright 2020 Emir Hodzic <emir.hodzich@gmail.com> #
25
+ # Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
26
+ # Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
27
+ # Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
28
+ # Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> #
29
+ # Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
30
+ # Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
31
+ # Copyright 2023 Trim21 <trim21.me@gmail.com> #
32
+ # Copyright 2023 YugoHino <henom06@gmail.com> #
33
+ # Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
34
+ # Copyright 2025 Enrico Minack <github@enrico.minack.dev> #
35
+ # Copyright 2025 Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> #
36
+ # Copyright 2025 Matej Focko <mfocko@users.noreply.github.com> #
37
+ # Copyright 2025 Sam <35731946+sam93210@users.noreply.github.com> #
38
+ # Copyright 2025 odedperezcodes <oded.perez.codes@gmail.com> #
39
+ # Copyright 2026 Enrico Minack <github@enrico.minack.dev> #
40
+ # Copyright 2026 Mikhail f. Shiryaev <mr.felixoid@gmail.com> #
41
+ # Copyright 2026 Noethix <ryuga.rago1111@gmail.com> #
42
+ # #
43
+ # This file is part of PyGithub. #
44
+ # http://pygithub.readthedocs.io/ #
45
+ # #
46
+ # PyGithub is free software: you can redistribute it and/or modify it under #
47
+ # the terms of the GNU Lesser General Public License as published by the Free #
48
+ # Software Foundation, either version 3 of the License, or (at your option) #
49
+ # any later version. #
50
+ # #
51
+ # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
52
+ # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
53
+ # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
54
+ # details. #
55
+ # #
56
+ # You should have received a copy of the GNU Lesser General Public License #
57
+ # along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
58
+ # #
59
+ ################################################################################
60
+
61
+ from __future__ import annotations
62
+
63
+ from collections.abc import AsyncIterator, Callable, Iterable
64
+ from typing import Any, Generic, TypeVar, overload
65
+
66
+ from githubasyncio import Consts
67
+ from githubasyncio.GithubObject import GithubObject, rate_limit_from_headers
68
+ from githubasyncio.Rate import Rate
69
+ from githubasyncio.Requester import Requester
70
+
71
+ T = TypeVar("T", bound=GithubObject)
72
+
73
+
74
+ class Page(list[T]):
75
+ """
76
+ A single page of a :class:`PaginatedList`, as returned by :meth:`PaginatedList.pages` and
77
+ :meth:`PaginatedList.get_page`.
78
+
79
+ Provides the elements of that page like a list.
80
+
81
+ """
82
+
83
+ def __init__(self, elements: Iterable[T], requester: Requester, headers: dict[str, str | int] | None):
84
+ super().__init__(elements)
85
+ self.__requester = requester
86
+ self.__headers = headers or {}
87
+
88
+ @property
89
+ def rate_limit(self) -> Rate | None:
90
+ """
91
+ Rate limit reported by the response that provided this page, ``None`` if that response did not report any.
92
+
93
+ This does not send any request and does not get updated by later requests.
94
+
95
+ """
96
+ attributes = rate_limit_from_headers(self.__headers)
97
+ if not attributes:
98
+ return None
99
+ return Rate(self.__requester, self.__headers, attributes)
100
+
101
+ def copy(self) -> Page[T]:
102
+ """
103
+ Creates a shallow copy of this page.
104
+ """
105
+ return Page(self, self.__requester, self.__headers)
106
+
107
+ def _reversed(self) -> Page[T]:
108
+ return Page(self[::-1], self.__requester, self.__headers)
109
+
110
+
111
+ class PaginatedListBase(Generic[T]):
112
+ __elements: list[T]
113
+ __pages: list[Page[T]]
114
+
115
+ def _couldGrow(self) -> bool:
116
+ raise NotImplementedError
117
+
118
+ async def _fetchNextPage(self) -> Page[T]:
119
+ raise NotImplementedError
120
+
121
+ def __init__(self, first_page: Page[T] | None = None) -> None:
122
+ self.__elements = [] if first_page is None else list(first_page)
123
+ self.__pages = [] if first_page is None else [first_page]
124
+
125
+ @overload
126
+ def __getitem__(self, index: int) -> T: ...
127
+
128
+ @overload
129
+ def __getitem__(self, index: slice) -> _Slice: ...
130
+
131
+ def __getitem__(self, index: int | slice) -> T | _Slice:
132
+ """
133
+ Synchronous element access — only returns already-fetched elements.
134
+
135
+ For async-aware fetching (which loads pages on demand), use
136
+ ``await obj.getitem(index)`` instead.
137
+
138
+ :raises IndexError: if *index* has not been fetched yet.
139
+ """
140
+ assert isinstance(index, (int, slice))
141
+ if isinstance(index, int):
142
+ return self.__elements[index]
143
+ else:
144
+ return self._Slice(self, index)
145
+
146
+ async def getitem(self, index: int | slice) -> T | _Slice:
147
+ """
148
+ Async element access with on-demand page fetching.
149
+
150
+ This is the async replacement for ``__getitem__`` — Python cannot
151
+ implicitly ``await`` dunder methods, so ``obj[i]`` would return a
152
+ coroutine rather than a value if ``__getitem__`` were async.
153
+
154
+ Usage::
155
+
156
+ element = await paginated_list.getitem(0)
157
+ sliced = await paginated_list.getitem(slice(2, 5))
158
+ """
159
+ assert isinstance(index, (int, slice))
160
+ if isinstance(index, int):
161
+ await self.__fetchToIndex(index)
162
+ return self.__elements[index]
163
+ else:
164
+ return self._Slice(self, index)
165
+
166
+ async def __aiter__(self) -> AsyncIterator[T]:
167
+ for element in self.__elements:
168
+ yield element
169
+ while self._couldGrow():
170
+ newElements = await self._grow()
171
+ for element in newElements:
172
+ yield element
173
+
174
+ @property
175
+ def has_unfetched_pages(self) -> bool:
176
+ """
177
+ Whether this list has pages that have not been fetched yet, so that continuing to iterate sends a request.
178
+
179
+ This does not send any request. An empty or not yet fetched list may report ``True`` until the first response.
180
+
181
+ """
182
+ return self._couldGrow()
183
+
184
+ async def pages(self) -> AsyncIterator[Page[T]]:
185
+ """
186
+ Iterates over the individual pages of this list, fetching them only when needed.
187
+
188
+ Pages that have been fetched already, also through iterating or indexing this list, are not fetched again.
189
+ In a reversed list, pages come last to first, and the elements of each page are reversed as well.
190
+ Every response provides a page, so an empty list has a single empty page.
191
+
192
+ """
193
+ index = 0
194
+ while index < len(self.__pages) or self._couldGrow():
195
+ if index == len(self.__pages):
196
+ await self._grow()
197
+ else:
198
+ # pages are mutable, a copy makes sure modifying a yielded page does not affect later calls to pages()
199
+ yield self.__pages[index].copy()
200
+ index += 1
201
+
202
+ def _isBiggerThan(self, index: int) -> bool:
203
+ return len(self.__elements) > index or self._couldGrow()
204
+
205
+ async def __fetchToIndex(self, index: int) -> None:
206
+ while len(self.__elements) <= index and self._couldGrow():
207
+ await self._grow()
208
+
209
+ async def _grow(self) -> Page[T]:
210
+ newPage = await self._fetchNextPage()
211
+ self.__elements += newPage
212
+ self.__pages.append(newPage)
213
+ return newPage
214
+
215
+ def _clear(self) -> None:
216
+ self.__elements.clear()
217
+ self.__pages.clear()
218
+
219
+ def _reverse(self) -> None:
220
+ self.__elements.reverse()
221
+ self.__pages = [page._reversed() for page in self.__pages[::-1]]
222
+
223
+ class _Slice:
224
+ def __init__(self, theList: PaginatedListBase[T], theSlice: slice):
225
+ self.__list = theList
226
+ self.__start = theSlice.start or 0
227
+ self.__stop = theSlice.stop
228
+ self.__step = theSlice.step or 1
229
+
230
+ async def __aiter__(self) -> AsyncIterator[T]:
231
+ index = self.__start
232
+ while not self.__finished(index):
233
+ if self.__list._isBiggerThan(index):
234
+ yield await self.__list.getitem(index) # type: ignore
235
+ index += self.__step
236
+ else:
237
+ return
238
+
239
+ def __finished(self, index: int) -> bool:
240
+ return self.__stop is not None and index >= self.__stop
241
+
242
+
243
+ class PaginatedList(PaginatedListBase[T]):
244
+ """
245
+ This class abstracts the `pagination of the REST API <https://docs.github.com/en/rest/guides/traversing-with-pagination>`_
246
+ and the `GraphQl API <https://docs.github.com/en/graphql/guides/using-pagination-in-the-graphql-api>`_.
247
+
248
+ You can simply enumerate through instances of this class::
249
+
250
+ for repo in user.get_repos():
251
+ print(repo.name)
252
+
253
+ If you want to know the total number of items in the list::
254
+
255
+ print(user.get_repos().totalCount)
256
+
257
+ You can also index them or take slices::
258
+
259
+ second_repo = user.get_repos()[1]
260
+ first_repos = user.get_repos()[:10]
261
+
262
+ If you want to iterate in reversed order, just do::
263
+
264
+ for repo in reversed(user.get_repos()):
265
+ print(repo.name)
266
+
267
+ And if you really need it, you can explicitly access a specific page::
268
+
269
+ repos = user.get_repos()
270
+ assert repos.is_rest, "get_page not supported by the GraphQL API"
271
+
272
+ some_repos = repos.get_page(0)
273
+ some_other_repos = repos.get_page(3)
274
+
275
+ You can also iterate over the individual pages, rather than over all items::
276
+
277
+ for page in user.get_repos().pages():
278
+ print(f"{len(page)} repos on this page")
279
+
280
+ Individual items of this list are fetched in pages. The size of those pages
281
+ is configured via ``per_page`` when creating the :class:`githubasyncio.MainClass.Github` instance::
282
+
283
+ g = github.Github(per_page=100)
284
+
285
+ The default page size is 30. The maximum page size is usually 100.
286
+
287
+ Paginated lists are returned by ``get_…`` methods. Additionally, some classes have one property
288
+ that is a paginated list, called `paginated property <https://pygithub.readthedocs.io/en/stable/utilities.html#classes-with-paginated-properties>`_.
289
+
290
+ You can check if GitHub search returned `incomplete results <https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28#timeouts-and-incomplete-results>`_::
291
+
292
+ results = gh.search_code("query")
293
+ if results.incomplete_results:
294
+ print(f"Not sure if {results.totalCount} results are actually all results")
295
+
296
+ """
297
+
298
+ # v3: move * before firstUrl and fix call sites
299
+ def __init__(
300
+ self,
301
+ contentClass: type[T],
302
+ requester: Requester,
303
+ firstUrl: str | None = None,
304
+ firstParams: dict[str, Any] | None = None,
305
+ *,
306
+ headers: dict[str, str] | None = None,
307
+ list_item: str | list[str] = "items",
308
+ total_count_item: str = "total_count",
309
+ firstData: Any | None = None,
310
+ firstHeaders: dict[str, str | int] | None = None,
311
+ attributesTransformer: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
312
+ graphql_query: str | None = None,
313
+ graphql_variables: dict[str, Any] | None = None,
314
+ ):
315
+ if firstUrl is None and firstData is None and graphql_query is None:
316
+ raise ValueError("Either firstUrl or graphql_query must be given")
317
+ if firstUrl is not None and graphql_query is not None:
318
+ raise ValueError("Only one of firstUrl or graphql_query can be given")
319
+ if graphql_query is not None:
320
+ if not (isinstance(list_item, list) and all(isinstance(item, str) for item in list_item)):
321
+ raise ValueError("With graphql_query given, item_list must be a list of strings")
322
+
323
+ firstParams = firstParams or {}
324
+
325
+ # we add the per_page parameter if that value is not the default
326
+ # but only if there is no per_page parameter in the firstParams
327
+ if "per_page" not in firstParams and requester.per_page != Consts.DEFAULT_PER_PAGE:
328
+ firstParams["per_page"] = requester.per_page
329
+
330
+ self.__requester = requester
331
+ self.__contentClass = contentClass
332
+
333
+ self.__is_rest = firstUrl is not None or firstData is not None
334
+ self.__firstUrl = firstUrl
335
+ self.__firstParams: dict[str, Any] = firstParams
336
+ self.__firstData = firstData
337
+ self.__firstHeaders = firstHeaders
338
+ self.__nextUrl = firstUrl
339
+ self.__nextParams: dict[str, Any] = firstParams
340
+ self.__lastUrl: str | None = None
341
+ self.__headers = headers
342
+ self.__list_item = list_item
343
+ self.__total_count_item = total_count_item
344
+
345
+ self._reversed = False
346
+ self.__totalCount: int | None = None
347
+ self.__incomplete_results = None
348
+ self._attributesTransformer = attributesTransformer
349
+
350
+ self.__graphql_query = graphql_query
351
+ self.__graphql_variables = graphql_variables or {}
352
+ self.__page_info = None
353
+
354
+ first_page = None
355
+ if firstData is not None:
356
+ first_page = self._getPage(firstData, firstHeaders)
357
+ # this paginated list contains a single page
358
+ if self.__nextUrl is None and self.__totalCount is None:
359
+ self.__totalCount = len(first_page)
360
+ super().__init__(first_page)
361
+
362
+ @property
363
+ def is_rest(self) -> bool:
364
+ return self.__is_rest
365
+
366
+ @property
367
+ def is_graphql(self) -> bool:
368
+ return not self.is_rest
369
+
370
+ def _transformAttributes(self, element: dict[str, Any]) -> dict[str, Any]:
371
+ if self._attributesTransformer is None:
372
+ return element
373
+ return self._attributesTransformer(element)
374
+
375
+ async def _fetchFirstElement(self) -> None:
376
+ # fetches the first element only, updates __totalCount and __incomplete_results
377
+ if self.is_rest:
378
+ params = self.__nextParams.copy()
379
+ # set per_page = 1 so the totalCount is just the number of pages
380
+ params.update({"per_page": 1})
381
+ headers, data = await self.__requester.requestJsonAndCheck(
382
+ "GET",
383
+ self.__firstUrl, # type: ignore[arg-type]
384
+ parameters=params,
385
+ headers=self.__headers,
386
+ )
387
+ links = self.__parseLinkHeader(headers)
388
+ lastUrl = links.get("last")
389
+
390
+ # update totalCount
391
+ if lastUrl:
392
+ self.__totalCount = int(Requester.get_parameters_of_url(lastUrl)["page"][0])
393
+ elif data and "total_count" in data:
394
+ self.__totalCount = data["total_count"]
395
+ elif data:
396
+ if isinstance(data, dict):
397
+ data = data[self.__list_item]
398
+ self.__totalCount = len(data)
399
+ else:
400
+ self.__totalCount = 0
401
+
402
+ # update incomplete_results
403
+ if data and "incomplete_results" in data:
404
+ self.__incomplete_results = data.get("incomplete_results")
405
+ else:
406
+ variables = self.__graphql_variables.copy()
407
+ if not self._reversed:
408
+ variables["first"] = 1
409
+ variables["after"] = None
410
+ else:
411
+ variables["last"] = 1
412
+ variables["before"] = None
413
+
414
+ _, data = await self.__requester.graphql_query(self.__graphql_query, variables) # type: ignore
415
+ pagination = self._get_graphql_pagination(data["data"], self.__list_item) # type: ignore
416
+ self.__totalCount = pagination.get("totalCount")
417
+
418
+ @property
419
+ async def totalCount(self) -> int:
420
+ if self.__totalCount is None:
421
+ await self._fetchFirstElement()
422
+ return self.__totalCount # type: ignore
423
+
424
+ @property
425
+ async def incomplete_results(self) -> bool | None:
426
+ """
427
+ Reflects `incomplete search results
428
+ <https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28#timeouts-and-incomplete-results>`_
429
+ """
430
+ # we deliberately check __totalCount here as well to check if any page has ever been fetched
431
+ # because __incomplete_results may not get updated by _fetchFirstElement()
432
+ if self.__incomplete_results is None and self.__totalCount is None:
433
+ await self._fetchFirstElement()
434
+ return self.__incomplete_results
435
+
436
+ async def _getLastPageUrl(self) -> str | None:
437
+ headers, data = await self.__requester.requestJsonAndCheck(
438
+ "GET",
439
+ self.__firstUrl, # type: ignore[arg-type]
440
+ parameters=self.__nextParams,
441
+ headers=self.__headers,
442
+ )
443
+ links = self.__parseLinkHeader(headers)
444
+ return links.get("last")
445
+
446
+ @property
447
+ async def reversed(self) -> PaginatedList[T]:
448
+ r = PaginatedList(
449
+ self.__contentClass,
450
+ self.__requester,
451
+ self.__firstUrl,
452
+ self.__firstParams,
453
+ headers=self.__headers,
454
+ list_item=self.__list_item,
455
+ total_count_item=self.__total_count_item,
456
+ firstData=self.__firstData,
457
+ firstHeaders=self.__firstHeaders,
458
+ attributesTransformer=self._attributesTransformer,
459
+ graphql_query=self.__graphql_query,
460
+ graphql_variables=self.__graphql_variables,
461
+ )
462
+ await r.__reverse()
463
+ return r
464
+
465
+ async def __reverse(self) -> None:
466
+ self._reversed = True
467
+ if self.is_rest:
468
+ if self.__lastUrl is None:
469
+ self.__lastUrl = await self._getLastPageUrl()
470
+ if self.__lastUrl:
471
+ if self.__lastUrl != self.__firstUrl:
472
+ super()._clear()
473
+ self.__nextUrl = self.__lastUrl
474
+ if self.__nextParams:
475
+ # #2929: remove all parameters from self.__nextParams contained in self.__nextUrl
476
+ self.__nextParams = {
477
+ k: v
478
+ for k, v in self.__nextParams.items()
479
+ if k not in Requester.get_parameters_of_url(self.__nextUrl).keys()
480
+ }
481
+ super()._reverse()
482
+
483
+ def _couldGrow(self) -> bool:
484
+ return (
485
+ self.is_rest
486
+ and self.__nextUrl is not None
487
+ or self.is_graphql
488
+ and (
489
+ self.__page_info is None
490
+ or not self._reversed
491
+ and self.__page_info["hasNextPage"]
492
+ or self._reversed
493
+ and self.__page_info["hasPreviousPage"]
494
+ )
495
+ )
496
+
497
+ def _get_graphql_pagination(self, data: dict[str, Any], path: list[str]) -> dict[str, Any]:
498
+ for item in path:
499
+ if item not in data:
500
+ raise RuntimeError(f"Pagination path {path} not found in data: {self.paths_of_dict(data)}")
501
+ data = data[item]
502
+ return data
503
+
504
+ async def _fetchNextPage(self) -> Page[T]:
505
+ if self.is_rest:
506
+ # REST API pagination
507
+ headers, data = await self.__requester.requestJsonAndCheck(
508
+ "GET",
509
+ self.__nextUrl, # type: ignore[arg-type]
510
+ parameters=self.__nextParams,
511
+ headers=self.__headers,
512
+ )
513
+ data = data if data else []
514
+ return self._getPage(data, headers)
515
+ else:
516
+ # GraphQL API pagination
517
+ variables = self.__graphql_variables.copy()
518
+ if not self._reversed:
519
+ variables["first"] = self.__requester.per_page
520
+ if self.__page_info is not None:
521
+ variables["after"] = self.__page_info["endCursor"]
522
+ else:
523
+ variables["last"] = self.__requester.per_page
524
+ if self.__page_info is not None:
525
+ variables["before"] = self.__page_info["startCursor"]
526
+
527
+ headers, data = await self.__requester.graphql_query(self.__graphql_query, variables) # type: ignore
528
+
529
+ pagination = self._get_graphql_pagination(data["data"], self.__list_item) # type: ignore
530
+ return self._getPage(pagination, headers)
531
+
532
+ def _getPage(self, data: Any, headers: dict[str, str | int] | None) -> Page[T]:
533
+ if self.is_rest:
534
+ self.__nextUrl = None # type: ignore
535
+ if len(data) > 0:
536
+ links = self.__parseLinkHeader(headers) # type: ignore
537
+ if self._reversed:
538
+ if "prev" in links:
539
+ self.__nextUrl = links["prev"]
540
+ elif "next" in links:
541
+ self.__nextUrl = links["next"]
542
+ if "last" in links:
543
+ self.__lastUrl = links["last"]
544
+ self.__nextParams = {}
545
+ if "incomplete_results" in data:
546
+ self.__incomplete_results = data.get("incomplete_results")
547
+ if self.__list_item in data:
548
+ self.__totalCount = data.get(self.__total_count_item)
549
+ data = data[self.__list_item]
550
+ content = [
551
+ self.__contentClass(self.__requester, headers, self._transformAttributes(element)) # type: ignore
552
+ for element in data
553
+ if element is not None
554
+ ]
555
+ if self._reversed:
556
+ content = content[::-1]
557
+ return Page(content, self.__requester, headers)
558
+ else:
559
+ if "pageInfo" not in data:
560
+ raise RuntimeError(f"Query must provide pagination with pageInfo:\n{self.__graphql_query}")
561
+
562
+ self.__page_info = data["pageInfo"]
563
+ if any(
564
+ item not in self.__page_info # type: ignore
565
+ for item in ["startCursor", "endCursor", "hasNextPage", "hasPreviousPage"]
566
+ ):
567
+ raise RuntimeError(f"Query must provide pagination with pageInfo\n{self.__graphql_query}")
568
+
569
+ if self.__totalCount is None:
570
+ if "totalCount" not in data:
571
+ raise RuntimeError(f"Query must provide totalCount\n{self.__graphql_query}")
572
+ self.__totalCount = data["totalCount"]
573
+
574
+ if "nodes" not in data:
575
+ raise RuntimeError(
576
+ f"No nodes found under pagination path {self.__list_item}: {self.paths_of_dict(data)}"
577
+ )
578
+
579
+ nodes = data["nodes"]
580
+ if self._reversed:
581
+ nodes = nodes[::-1]
582
+ return Page(
583
+ [
584
+ self.__contentClass(self.__requester, headers, element) # type: ignore
585
+ for element in nodes
586
+ if element is not None
587
+ ],
588
+ self.__requester,
589
+ headers,
590
+ )
591
+
592
+ def __parseLinkHeader(self, headers: dict[str, str | int]) -> dict[str, str]:
593
+ links = {}
594
+ if "link" in headers and isinstance(headers["link"], str):
595
+ linkHeaders = headers["link"].split(", ")
596
+ for linkHeader in linkHeaders:
597
+ url, rel, *rest = linkHeader.split("; ")
598
+ url = url[1:-1]
599
+ rel = rel[5:-1]
600
+ links[rel] = url
601
+ return links
602
+
603
+ async def get_page(self, page: int) -> Page[T]:
604
+ if self.is_graphql:
605
+ raise RuntimeError("Not supported for GraphQL pagination")
606
+
607
+ params = dict(self.__firstParams)
608
+ if page != 0:
609
+ params["page"] = page + 1
610
+ if self.__requester.per_page != Consts.DEFAULT_PER_PAGE:
611
+ params["per_page"] = self.__requester.per_page
612
+ headers, data = await self.__requester.requestJsonAndCheck(
613
+ "GET",
614
+ self.__firstUrl, # type: ignore[arg-type]
615
+ parameters=params,
616
+ headers=self.__headers,
617
+ )
618
+
619
+ if self.__list_item in data:
620
+ self.__totalCount = data.get("total_count")
621
+ if "incomplete_results" in data:
622
+ self.__incomplete_results = data.get("incomplete_results")
623
+ data = data[self.__list_item]
624
+ return Page(
625
+ [self.__contentClass(self.__requester, headers, self._transformAttributes(element)) for element in data],
626
+ self.__requester,
627
+ headers,
628
+ )
629
+
630
+ @classmethod
631
+ def override_attributes(cls, overrides: dict[str, Any]) -> Callable[[dict[str, Any]], dict[str, Any]]:
632
+ def attributes_transformer(element: dict[str, Any]) -> dict[str, Any]:
633
+ # Recursively merge overrides with attributes, overriding attributes with overrides
634
+ element = cls.merge_dicts(element, overrides)
635
+ return element
636
+
637
+ return attributes_transformer
638
+
639
+ @classmethod
640
+ def merge_dicts(cls, d1: dict[str, Any], d2: dict[str, Any]) -> dict[str, Any]:
641
+ # clone d1
642
+ d1 = d1.copy()
643
+ for k, v in d2.items():
644
+ if isinstance(v, dict):
645
+ d1[k] = cls.merge_dicts(d1.get(k, {}), v)
646
+ else:
647
+ d1[k] = v
648
+ return d1
649
+
650
+ @classmethod
651
+ def paths_of_dict(cls, d: dict) -> dict:
652
+ return {key: cls.paths_of_dict(val) if isinstance(val, dict) else None for key, val in d.items()}