Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for repository autolink references #2016

Merged
merged 4 commits into from Oct 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
62 changes: 62 additions & 0 deletions github/Autolink.py
@@ -0,0 +1,62 @@
############################ Copyrights and license ############################
# #
# Copyright 2021 Marco Köpcke <hello@parakoopa.de> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################

import github.GithubObject


class Autolink(github.GithubObject.NonCompletableGithubObject):
def __repr__(self):
return self.get__repr__({"id": self._id.value})

@property
def id(self):
"""
:type: integer
"""
return self._id.value

@property
def key_prefix(self):
"""
:type: string
"""
return self._key_prefix.value

@property
def url_template(self):
"""
:type: string
"""
return self._url_template.value

def _initAttributes(self):
self._id = github.GithubObject.NotSet
self._key_prefix = github.GithubObject.NotSet
self._url_template = github.GithubObject.NotSet

def _useAttributes(self, attributes):
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "key_prefix" in attributes: # pragma no branch
self._key_prefix = self._makeStringAttribute(attributes["key_prefix"])
if "url_template" in attributes: # pragma no branch
self._url_template = self._makeStringAttribute(attributes["url_template"])
13 changes: 13 additions & 0 deletions github/Autolink.pyi
@@ -0,0 +1,13 @@
from typing import Any, Dict, List

from github.GithubObject import NonCompletableGithubObject

class Autolink(NonCompletableGithubObject):
def _initAttributes(self) -> None: ...
def _useAttributes(self, attributes: Dict[str, Any]) -> None: ...
@property
def id(self) -> int: ...
@property
def key_prefix(self) -> str: ...
@property
def url_template(self) -> str: ...
40 changes: 40 additions & 0 deletions github/Repository.py
Expand Up @@ -93,6 +93,7 @@
from deprecated import deprecated

import github.Artifact
import github.Autolink
import github.Branch
import github.CheckRun
import github.CheckSuite
Expand Down Expand Up @@ -918,6 +919,22 @@ def compare(self, base, head):
self._requester, headers, data, completed=True
)

def create_autolink(self, key_prefix, url_template):
"""
:calls: `POST /repos/{owner}/{repo}/autolinks <http://docs.github.com/en/rest/reference/repos>`_
:param key_prefix: string
:param url_template: string
:rtype: :class:`github.Autolink.Autolink`
"""
assert isinstance(key_prefix, str), key_prefix
assert isinstance(url_template, str), url_template

post_parameters = {"key_prefix": key_prefix, "url_template": url_template}
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.url}/autolinks", input=post_parameters
)
return github.Autolink.Autolink(self._requester, headers, data, completed=True)

def create_git_blob(self, content, encoding):
"""
:calls: `POST /repos/{owner}/{repo}/git/blobs <https://docs.github.com/en/rest/reference/git#blobs>`_
Expand Down Expand Up @@ -2088,6 +2105,15 @@ def get_projects(self, state=github.GithubObject.NotSet):
{"Accept": Consts.mediaTypeProjectsPreview},
)

def get_autolinks(self):
"""
:calls: `GET /repos/{owner}/{repo}/autolinks <http://docs.github.com/en/rest/reference/repos>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Autolink.Autolink`
"""
return github.PaginatedList.PaginatedList(
github.Autolink.Autolink, self._requester, f"{self.url}/autolinks", None
)

def create_file(
self,
path,
Expand Down Expand Up @@ -3509,6 +3535,20 @@ def remove_self_hosted_runner(self, runner):
)
return status == 204

def remove_autolink(self, autolink):
"""
:calls: `DELETE /repos/{owner}/{repo}/autolinks/{id} <https://docs.github.com/en/rest/reference/repos>`_
:param autolink: int or :class:`github.Autolink.Autolink`
:rtype: None
theCapypara marked this conversation as resolved.
Show resolved Hide resolved
"""
is_autolink = isinstance(autolink, github.Autolink.Autolink)
assert is_autolink or isinstance(autolink, int), autolink

status, _, _ = self._requester.requestJson(
"DELETE", f"{self.url}/autolinks/{autolink.id if is_autolink else autolink}"
)
return status == 204

def subscribe_to_hub(self, event, callback, secret=github.GithubObject.NotSet):
"""
:calls: `POST /hub <https://docs.github.com/en/rest/reference/repos#pubsubhubbub>`_
Expand Down
4 changes: 4 additions & 0 deletions github/Repository.pyi
Expand Up @@ -3,6 +3,7 @@ from typing import Any, Dict, List, Optional, Union, overload

from github.Artifact import Artifact
from github.AuthenticatedUser import AuthenticatedUser
from github.Autolink import Autolink
from github.Branch import Branch
from github.CheckRun import CheckRun
from github.CheckSuite import CheckSuite
Expand Down Expand Up @@ -104,6 +105,7 @@ class Repository(CompletableGithubObject):
def contents_url(self) -> str: ...
@property
def contributors_url(self) -> str: ...
def create_autolink(self, key_prefix: str, url_template: str) -> Autolink: ...
def create_check_run(
self,
name: str,
Expand Down Expand Up @@ -311,6 +313,7 @@ class Repository(CompletableGithubObject):
def get_artifact(self) -> Artifact: ...
def get_artifacts(self) -> PaginatedList[Artifact]: ...
def get_assignees(self) -> PaginatedList[NamedUser]: ...
def get_autolinks(self) -> PaginatedList[Autolink]: ...
def get_branch(self, branch: str) -> Branch: ...
def rename_branch(self, branch: Union[str, Branch], new_name: str) -> bool: ...
def get_branches(self) -> PaginatedList[Branch]: ...
Expand Down Expand Up @@ -561,6 +564,7 @@ class Repository(CompletableGithubObject):
def pushed_at(self) -> datetime: ...
@property
def releases_url(self) -> str: ...
def remove_autolink(self, autolink: Union[Autolink, int]) -> bool: ...
def remove_from_collaborators(
self, collaborator: Union[str, NamedUser]
) -> None: ...
Expand Down
45 changes: 45 additions & 0 deletions tests/Autolink.py
@@ -0,0 +1,45 @@
############################ Copyrights and license ############################
# #
# Copyright 2021 Marco Köpcke <hello@parakoopa.de> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from tests import Framework


class Autolink(Framework.TestCase):
def setUp(self):
super().setUp()
# When recording test, be sure to create a autolink for yourself on
# Github and update it here.
links = [
x
for x in self.g.get_user("theCapypara").get_repo("PyGithub").get_autolinks()
if x.id == 209614
]
self.assertEqual(
1, len(links), "There must be exactly one autolink with the ID 209614."
)
self.link = links[0]

def testAttributes(self):
self.assertEqual(self.link.id, 209614)
self.assertEqual(self.link.key_prefix, "DUMMY-")
self.assertEqual(
self.link.url_template, "https://github.com/PyGithub/PyGithub/issues/<num>"
)
33 changes: 33 additions & 0 deletions tests/ReplayData/Autolink.setUp.txt

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions tests/ReplayData/Repository.testCreateAutolink.txt
@@ -0,0 +1,11 @@
https
POST
api.github.com
None
/repos/jacquev6/PyGithub/autolinks
{'Authorization': 'Basic login_and_password_removed', 'User-Agent': 'PyGithub/Python', 'Content-Type': 'application/json'}
{"key_prefix": "DUMMY-", "url_template": "https://github.com/PyGithub/PyGithub/issues/<num>"}
201
[('Server', 'GitHub.com'), ('Date', 'Tue, 02 Nov 2021 12:57:55 GMT'), ('Content-Type', 'application/json; charset=utf-8'), ('Content-Length', '102'), ('Cache-Control', 'private, max-age=60, s-maxage=60'), ('Vary', 'Accept, Authorization, Cookie, X-GitHub-OTP, Accept-Encoding, Accept, X-Requested-With'), ('ETag', '"f90a1a598b996d3d1967b96c218459edde984e62d452623ff4aba2530a256b85"'), ('X-OAuth-Scopes', 'admin:repo_hook, repo'), ('X-Accepted-OAuth-Scopes', 'repo'), ('github-authentication-token-expiration', '2021-11-09 12:40:40 UTC'), ('X-GitHub-Media-Type', 'github.v3; format=json'), ('X-RateLimit-Limit', '5000'), ('X-RateLimit-Remaining', '4947'), ('X-RateLimit-Reset', '1635859633'), ('X-RateLimit-Used', '53'), ('X-RateLimit-Resource', 'core'), ('Access-Control-Expose-Headers', 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, Deprecation, Sunset'), ('Access-Control-Allow-Origin', '*'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '0'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Content-Security-Policy', "default-src 'none'"), ('X-GitHub-Request-Id', 'C6E6:34FE:190079B:197523C:618135D3')]
{"id":209614,"key_prefix":"DUMMY-","url_template":"https://github.com/PyGithub/PyGithub/issues/<num>"}

11 changes: 11 additions & 0 deletions tests/ReplayData/Repository.testGetAutolinks.txt
@@ -0,0 +1,11 @@
https
GET
api.github.com
None
/repos/jacquev6/PyGithub/autolinks
{'Authorization': 'Basic login_and_password_removed', 'User-Agent': 'PyGithub/Python'}
None
200
[('Server', 'GitHub.com'), ('Date', 'Tue, 02 Nov 2021 13:01:39 GMT'), ('Content-Type', 'application/json; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Cache-Control', 'private, max-age=60, s-maxage=60'), ('Vary', 'Accept, Authorization, Cookie, X-GitHub-OTP, Accept-Encoding, Accept, X-Requested-With'), ('ETag', 'W/"4d453f5f31fb634e68e615083db0c61dc2d1925cd6f16586a81b24e2369872ba"'), ('X-OAuth-Scopes', 'admin:repo_hook, repo'), ('X-Accepted-OAuth-Scopes', 'repo'), ('github-authentication-token-expiration', '2021-11-09 12:40:40 UTC'), ('X-GitHub-Media-Type', 'github.v3; format=json'), ('X-RateLimit-Limit', '5000'), ('X-RateLimit-Remaining', '4944'), ('X-RateLimit-Reset', '1635859633'), ('X-RateLimit-Used', '56'), ('X-RateLimit-Resource', 'core'), ('Access-Control-Expose-Headers', 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, Deprecation, Sunset'), ('Access-Control-Allow-Origin', '*'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '0'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Content-Security-Policy', "default-src 'none'"), ('Content-Encoding', 'gzip'), ('X-GitHub-Request-Id', 'C11A:B2A9:62722:A8B2E:618136B3')]
[{"id":209614,"key_prefix":"DUMMY-","url_template":"https://github.com/PyGithub/PyGithub/issues/<num>"},{"id":209611,"key_prefix":"TEST-","url_template":"https://github.com/PyGithub/PyGithub/issues/<num>"}]

11 changes: 11 additions & 0 deletions tests/ReplayData/Repository.testRemoveAutolink.txt
@@ -0,0 +1,11 @@
https
DELETE
api.github.com
None
/repos/jacquev6/PyGithub/autolinks/209611
{'Authorization': 'Basic login_and_password_removed', 'User-Agent': 'PyGithub/Python'}
None
204
[('Server', 'GitHub.com'), ('Date', 'Tue, 02 Nov 2021 13:05:13 GMT'), ('X-OAuth-Scopes', 'admin:repo_hook, repo'), ('X-Accepted-OAuth-Scopes', 'repo'), ('github-authentication-token-expiration', '2021-11-09 12:40:40 UTC'), ('X-GitHub-Media-Type', 'github.v3; format=json'), ('X-RateLimit-Limit', '5000'), ('X-RateLimit-Remaining', '4941'), ('X-RateLimit-Reset', '1635859633'), ('X-RateLimit-Used', '59'), ('X-RateLimit-Resource', 'core'), ('Access-Control-Expose-Headers', 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, Deprecation, Sunset'), ('Access-Control-Allow-Origin', '*'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '0'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Content-Security-Policy', "default-src 'none'"), ('Vary', 'Accept-Encoding, Accept, X-Requested-With'), ('X-GitHub-Request-Id', 'C120:10BD6:34C209:39806B:61813789')]


19 changes: 19 additions & 0 deletions tests/Repository.py
Expand Up @@ -258,6 +258,12 @@ def testCreateGitRef(self):
"https://api.github.com/repos/jacquev6/PyGithub/git/refs/heads/BranchCreatedByPyGithub",
)

def testCreateAutolink(self):
key = self.repo.create_autolink(
"DUMMY-", "https://github.com/PyGithub/PyGithub/issues/<num>"
)
self.assertEqual(key.id, 209614)

def testCreateGitBlob(self):
blob = self.repo.create_git_blob("Blob created by PyGithub", "latin1")
self.assertEqual(blob.sha, "5dd930f591cd5188e9ea7200e308ad355182a1d8")
Expand Down Expand Up @@ -478,6 +484,9 @@ def testGetPendingInvitations(self):
def testRemoveInvitation(self):
self.repo.remove_invitation(17285388)

def testRemoveAutolink(self):
self.repo.remove_autolink(209611)

def testCollaboratorPermissionNoPushAccess(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.repo.get_collaborator_permission("lyloa")
Expand Down Expand Up @@ -1170,6 +1179,16 @@ def testGetPullsWithArguments(self):
self.repo.get_pulls("closed"), lambda p: p.id, [1448168, 1436310, 1436215]
)

def testGetAutolinks(self):
self.assertListKeyEqual(
self.repo.get_autolinks(),
lambda i: i.id,
[
209614,
209611,
],
)

def testLegacySearchIssues(self):
issues = self.repo.legacy_search_issues("open", "search")
self.assertListKeyEqual(issues, lambda i: i.title, ["Support new Search API"])
Expand Down