id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12,400
|
GithubRetry.py
|
PyGithub_PyGithub/github/GithubRetry.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Patryk Szulczyk <therealsoulcheck@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Austin Sasko <austintyler0239@yahoo.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 json
import logging
from datetime import datetime, timezone
from logging import Logger
from types import TracebackType
from typing import Any, Optional
from requests import Response
from requests.models import CaseInsensitiveDict
from requests.utils import get_encoding_from_headers
from typing_extensions import Self
from urllib3 import Retry
from urllib3.connectionpool import ConnectionPool
from urllib3.exceptions import MaxRetryError
from urllib3.response import HTTPResponse
from github.GithubException import GithubException
from github.Requester import Requester
DEFAULT_SECONDARY_RATE_WAIT: int = 60
class GithubRetry(Retry):
"""
A Github-specific implementation of `urllib3.Retry`
This retries 403 responses if they are retry-able. Github requests are retry-able when
the response provides a `"Retry-After"` header, or the content indicates a rate limit error.
By default, response codes 403, and 500 up to 599 are retried. This can be configured
via the `status_forcelist` argument.
By default, all methods defined in `Retry.DEFAULT_ALLOWED_METHODS` are retried, plus GET and POST.
This can be configured via the `allowed_methods` argument.
"""
__logger: Optional[Logger] = None
# used to mock datetime, mock.patch("github.GithubRetry.date") does not work as this
# references the class, not the module (due to re-exporting in github/__init__.py)
__datetime = datetime
def __init__(self, secondary_rate_wait: float = DEFAULT_SECONDARY_RATE_WAIT, **kwargs: Any) -> None:
"""
:param secondary_rate_wait: seconds to wait before retrying secondary rate limit errors
:param kwargs: see urllib3.Retry for more arguments
"""
self.secondary_rate_wait = secondary_rate_wait
# 403 is too broad to be retried, but GitHub API signals rate limits via 403
# we retry 403 and look into the response header via Retry.increment
# to determine if we really retry that 403
kwargs["status_forcelist"] = kwargs.get("status_forcelist", list(range(500, 600))) + [403]
kwargs["allowed_methods"] = kwargs.get("allowed_methods", Retry.DEFAULT_ALLOWED_METHODS.union({"GET", "POST"}))
super().__init__(**kwargs)
def new(self, **kw: Any) -> Self:
kw.update(dict(secondary_rate_wait=self.secondary_rate_wait))
return super().new(**kw) # type: ignore
def increment( # type: ignore[override]
self,
method: Optional[str] = None,
url: Optional[str] = None,
response: Optional[HTTPResponse] = None, # type: ignore[override]
error: Optional[Exception] = None,
_pool: Optional[ConnectionPool] = None,
_stacktrace: Optional[TracebackType] = None,
) -> Retry:
if response:
# we retry 403 only when there is a Retry-After header (indicating it is retry-able)
# or the body message does imply a rate limit error
if response.status == 403:
self.__log(
logging.INFO,
f"Request {method} {url} failed with {response.status}: {response.reason}",
)
if "Retry-After" in response.headers:
# Sleeping 'Retry-After' seconds is implemented in urllib3.Retry.sleep() and called by urllib3
self.__log(
logging.INFO,
f'Retrying after {response.headers.get("Retry-After")} seconds',
)
else:
content = response.reason
# to identify retry-able methods, we inspect the response body
try:
content = self.get_content(response, url) # type: ignore
content = json.loads(content) # type: ignore
message = content.get("message") # type: ignore
except Exception as e:
# we want to fall back to the actual github exception (probably a rate limit error)
# but provide some context why we could not deal with it without another exception
try:
raise RuntimeError("Failed to inspect response message") from e
except RuntimeError as e:
raise GithubException(response.status, content, response.headers) from e # type: ignore
try:
if Requester.isRateLimitError(message):
rate_type = "primary" if Requester.isPrimaryRateLimitError(message) else "secondary"
self.__log(
logging.DEBUG,
f"Response body indicates retry-able {rate_type} rate limit error: {message}",
)
# check early that we are retrying at all
retry = super().increment(method, url, response, error, _pool, _stacktrace)
# we backoff primary rate limit at least until X-RateLimit-Reset,
# we backoff secondary rate limit at for secondary_rate_wait seconds
backoff = 0.0
if Requester.isPrimaryRateLimitError(message):
if "X-RateLimit-Reset" in response.headers:
value = response.headers.get("X-RateLimit-Reset")
if value and value.isdigit():
reset = self.__datetime.fromtimestamp(int(value), timezone.utc)
delta = reset - self.__datetime.now(timezone.utc)
resetBackoff = delta.total_seconds()
if resetBackoff > 0:
self.__log(
logging.DEBUG,
f"Reset occurs in {str(delta)} ({value} / {reset})",
)
# plus 1s as it is not clear when in that second the reset occurs
backoff = resetBackoff + 1
else:
backoff = self.secondary_rate_wait
# we backoff at least retry's next backoff
retry_backoff = retry.get_backoff_time()
if retry_backoff > backoff:
if backoff > 0:
self.__log(
logging.DEBUG,
f"Retry backoff of {retry_backoff}s exceeds "
f"required rate limit backoff of {backoff}s".replace(".0s", "s"),
)
backoff = retry_backoff
def get_backoff_time() -> float:
return backoff
self.__log(
logging.INFO,
f"Setting next backoff to {backoff}s".replace(".0s", "s"),
)
retry.get_backoff_time = get_backoff_time # type: ignore
return retry
self.__log(
logging.DEBUG,
"Response message does not indicate retry-able error",
)
raise Requester.createException(response.status, response.headers, content) # type: ignore
except (MaxRetryError, GithubException):
raise
except Exception as e:
# we want to fall back to the actual github exception (probably a rate limit error)
# but provide some context why we could not deal with it without another exception
try:
raise RuntimeError("Failed to determine retry backoff") from e
except RuntimeError as e:
raise GithubException(response.status, content, response.headers) from e # type: ignore
raise GithubException(
response.status, # type: ignore
content, # type: ignore
response.headers, # type: ignore
) # type: ignore
# retry the request as usual
return super().increment(method, url, response, error, _pool, _stacktrace)
@staticmethod
def get_content(resp: HTTPResponse, url: str) -> bytes: # type: ignore[override]
# logic taken from HTTPAdapter.build_response (requests.adapters)
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, "status", None) # type: ignore
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason # type: ignore
response.url = url
return response.content
def __log(self, level: int, message: str, **kwargs: Any) -> None:
if self.__logger is None:
self.__logger = logging.getLogger(__name__)
if self.__logger.isEnabledFor(level):
self.__logger.log(level, message, **kwargs)
| 12,063
|
Python
|
.py
| 196
| 45.408163
| 119
| 0.521383
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,401
|
Secret.py
|
PyGithub_PyGithub/github/Secret.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Mauricio Alejandro Martínez Pacheco <mauricio.martinez@premise.com>#
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class Secret(CompletableGithubObject):
"""
This class represents a GitHub secret.
The reference can be found here
https://docs.github.com/en/rest/actions/secrets
"""
def _initAttributes(self) -> None:
self._name: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._secrets_url: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self.name})
@property
def name(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._name)
return self._name.value
@property
def created_at(self) -> datetime:
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def updated_at(self) -> datetime:
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def secrets_url(self) -> str:
"""
:type: string
"""
return self._secrets_url.value
@property
def url(self) -> str:
"""
:type: string
"""
# Construct url from secrets_url and name, if self._url. is not set
if self._url is NotSet:
self._url = self._makeStringAttribute(self.secrets_url + "/" + self.name)
return self._url.value
def delete(self) -> None:
"""
:calls: `DELETE {secret_url} <https://docs.github.com/en/rest/actions/secrets>`_
:rtype: None
"""
self._requester.requestJsonAndCheck("DELETE", self.url)
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "name" in attributes:
self._name = self._makeStringAttribute(attributes["name"])
if "created_at" in attributes:
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "updated_at" in attributes:
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "secrets_url" in attributes:
self._secrets_url = self._makeStringAttribute(attributes["secrets_url"])
if "url" in attributes:
self._url = self._makeStringAttribute(attributes["url"])
| 5,660
|
Python
|
.py
| 108
| 46.861111
| 88
| 0.527903
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,402
|
CommitStatus.py
|
PyGithub_PyGithub/github/CommitStatus.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Matt Babineau <mbabineau@dataxu.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Martijn Koster <mak-github@greenhills.co.uk> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.GithubObject
import github.NamedUser
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class CommitStatus(NonCompletableGithubObject):
"""
This class represents CommitStatuses.The reference can be found here https://docs.github.com/en/rest/reference/repos#statuses
"""
def _initAttributes(self) -> None:
self._created_at: Attribute[datetime] = NotSet
self._creator: Attribute[github.NamedUser.NamedUser] = NotSet
self._description: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._state: Attribute[str] = NotSet
self._context: Attribute[str] = NotSet
self._target_url: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"id": self._id.value,
"state": self._state.value,
"context": self._context.value,
}
)
@property
def created_at(self) -> datetime:
return self._created_at.value
@property
def creator(self) -> github.NamedUser.NamedUser:
return self._creator.value
@property
def description(self) -> str:
return self._description.value
@property
def id(self) -> int:
return self._id.value
@property
def state(self) -> str:
return self._state.value
@property
def context(self) -> str:
return self._context.value
@property
def target_url(self) -> str:
return self._target_url.value
@property
def updated_at(self) -> datetime:
return self._updated_at.value
@property
def url(self) -> str:
return self._url.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "creator" in attributes: # pragma no branch
self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "context" in attributes: # pragma no branch
self._context = self._makeStringAttribute(attributes["context"])
if "target_url" in attributes: # pragma no branch
self._target_url = self._makeStringAttribute(attributes["target_url"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 6,280
|
Python
|
.py
| 112
| 50.383929
| 129
| 0.548366
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,403
|
Comparison.py
|
PyGithub_PyGithub/github/Comparison.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
import github.Commit
import github.File
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
from github.PaginatedList import PaginatedList
class Comparison(CompletableGithubObject):
"""
This class represents Comparisons.
"""
def _initAttributes(self) -> None:
self._ahead_by: Attribute[int] = NotSet
self._base_commit: Attribute[github.Commit.Commit] = NotSet
self._behind_by: Attribute[int] = NotSet
self._diff_url: Attribute[str] = NotSet
self._files: Attribute[list[github.File.File]] = NotSet
self._html_url: Attribute[str] = NotSet
self._merge_base_commit: Attribute[github.Commit.Commit] = NotSet
self._patch_url: Attribute[str] = NotSet
self._permalink_url: Attribute[str] = NotSet
self._status: Attribute[str] = NotSet
self._total_commits: Attribute[int] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"url": self._url.value})
@property
def ahead_by(self) -> int:
self._completeIfNotSet(self._ahead_by)
return self._ahead_by.value
@property
def base_commit(self) -> github.Commit.Commit:
self._completeIfNotSet(self._base_commit)
return self._base_commit.value
@property
def behind_by(self) -> int:
self._completeIfNotSet(self._behind_by)
return self._behind_by.value
# This should be a method, but this used to be a property and cannot be changed without breaking user code
# TODO: remove @property on version 3
@property
def commits(self) -> PaginatedList[github.Commit.Commit]:
return PaginatedList(
github.Commit.Commit,
self._requester,
self.url,
{},
None,
"commits",
"total_commits",
self.raw_data,
self.raw_headers,
)
@property
def diff_url(self) -> str:
self._completeIfNotSet(self._diff_url)
return self._diff_url.value
@property
def files(self) -> list[github.File.File]:
self._completeIfNotSet(self._files)
return self._files.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def merge_base_commit(self) -> github.Commit.Commit:
self._completeIfNotSet(self._merge_base_commit)
return self._merge_base_commit.value
@property
def patch_url(self) -> str:
self._completeIfNotSet(self._patch_url)
return self._patch_url.value
@property
def permalink_url(self) -> str:
self._completeIfNotSet(self._permalink_url)
return self._permalink_url.value
@property
def status(self) -> str:
self._completeIfNotSet(self._status)
return self._status.value
@property
def total_commits(self) -> int:
self._completeIfNotSet(self._total_commits)
return self._total_commits.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "ahead_by" in attributes: # pragma no branch
self._ahead_by = self._makeIntAttribute(attributes["ahead_by"])
if "base_commit" in attributes: # pragma no branch
self._base_commit = self._makeClassAttribute(github.Commit.Commit, attributes["base_commit"])
if "behind_by" in attributes: # pragma no branch
self._behind_by = self._makeIntAttribute(attributes["behind_by"])
if "diff_url" in attributes: # pragma no branch
self._diff_url = self._makeStringAttribute(attributes["diff_url"])
if "files" in attributes: # pragma no branch
self._files = self._makeListOfClassesAttribute(github.File.File, attributes["files"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "merge_base_commit" in attributes: # pragma no branch
self._merge_base_commit = self._makeClassAttribute(github.Commit.Commit, attributes["merge_base_commit"])
if "patch_url" in attributes: # pragma no branch
self._patch_url = self._makeStringAttribute(attributes["patch_url"])
if "permalink_url" in attributes: # pragma no branch
self._permalink_url = self._makeStringAttribute(attributes["permalink_url"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
if "total_commits" in attributes: # pragma no branch
self._total_commits = self._makeIntAttribute(attributes["total_commits"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 7,952
|
Python
|
.py
| 149
| 46.885906
| 117
| 0.575944
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,404
|
GitRelease.py
|
PyGithub_PyGithub/github/GitRelease.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Ed Holland <eholland@alertlogic.com> #
# Copyright 2016 Benjamin Whitney <benjamin.whitney@ironnetcybersecurity.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Chris McBride <thehighlander@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Daniel Kesler <kesler.daniel@gmail.com> #
# Copyright 2018 Ggicci <ggicci.t@gmail.com> #
# Copyright 2018 Kuba <jakub.glapa@adspired.com> #
# Copyright 2018 Maarten Fonville <mfonville@users.noreply.github.com> #
# Copyright 2018 Shinichi TAMURA <shnch.tmr@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 edquist <edquist@users.noreply.github.com> #
# Copyright 2018 nurupo <nurupo.contributions@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2020 Jesse Li <jesse.li2002@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Mikhail f. Shiryaev <mr.felixoid@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 Wojciech Barczyński <104033489+WojciechBarczynski@users.noreply.github.com>#
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from os.path import basename
from typing import Any, BinaryIO
import github.GitReleaseAsset
import github.NamedUser
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional
from github.PaginatedList import PaginatedList
from . import Consts
class GitRelease(CompletableGithubObject):
"""
This class represents GitReleases.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#releases
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = NotSet
self._body: Attribute[str] = NotSet
self._title: Attribute[str] = NotSet
self._tag_name: Attribute[str] = NotSet
self._target_commitish: Attribute[str] = NotSet
self._draft: Attribute[bool] = NotSet
self._prerelease: Attribute[bool] = NotSet
self._generate_release_notes: Attribute[bool] = NotSet
self._author: Attribute[github.NamedUser.NamedUser] = NotSet
self._url: Attribute[str] = NotSet
self._upload_url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._published_at: Attribute[datetime] = NotSet
self._tarball_url: Attribute[str] = NotSet
self._zipball_url: Attribute[str] = NotSet
self._assets: Attribute[list[github.GitReleaseAsset.GitReleaseAsset]] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"title": self._title.value})
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def title(self) -> str:
self._completeIfNotSet(self._title)
return self._title.value
@property
def tag_name(self) -> str:
self._completeIfNotSet(self._tag_name)
return self._tag_name.value
@property
def target_commitish(self) -> str:
self._completeIfNotSet(self._target_commitish)
return self._target_commitish.value
@property
def draft(self) -> bool:
self._completeIfNotSet(self._draft)
return self._draft.value
@property
def prerelease(self) -> bool:
self._completeIfNotSet(self._prerelease)
return self._prerelease.value
@property
def author(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._author)
return self._author.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def published_at(self) -> datetime:
self._completeIfNotSet(self._published_at)
return self._published_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def upload_url(self) -> str:
self._completeIfNotSet(self._upload_url)
return self._upload_url.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def tarball_url(self) -> str:
self._completeIfNotSet(self._tarball_url)
return self._tarball_url.value
@property
def zipball_url(self) -> str:
self._completeIfNotSet(self._zipball_url)
return self._zipball_url.value
@property
def assets(self) -> list[github.GitReleaseAsset.GitReleaseAsset]:
self._completeIfNotSet(self._assets)
return self._assets.value
def delete_release(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/releases/{release_id} <https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#delete-a-release>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def update_release(
self,
name: str,
message: str,
draft: bool = False,
prerelease: bool = False,
tag_name: Opt[str] = NotSet,
target_commitish: Opt[str] = NotSet,
make_latest: Opt[str] = NotSet,
discussion_category_name: Opt[str] = NotSet,
) -> GitRelease:
"""
:calls: `PATCH /repos/{owner}/{repo}/releases/{release_id} <https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#update-a-release>`_
"""
assert isinstance(name, str), name
assert isinstance(message, str), message
assert isinstance(draft, bool), draft
assert isinstance(prerelease, bool), prerelease
assert is_optional(tag_name, str), "tag_name must be a str/unicode object"
assert is_optional(target_commitish, str), "target_commitish must be a str/unicode object"
assert make_latest in ["true", "false", "legacy", NotSet], make_latest
assert is_optional(discussion_category_name, str), discussion_category_name
# default tag_name with instance attribute if not given to the method
if tag_name is NotSet:
tag_name = self.tag_name
post_parameters = {
"tag_name": tag_name,
"name": name,
"body": message,
"draft": draft,
"prerelease": prerelease,
}
# Do not set target_commitish to self.target_commitish when omitted, just don't send it
# altogether in that case, in order to match the Github API behaviour. Only send it when set.
if target_commitish is not NotSet:
post_parameters["target_commitish"] = target_commitish
if make_latest is not NotSet:
post_parameters["make_latest"] = make_latest
if discussion_category_name is not NotSet:
post_parameters["discussion_category_name"] = discussion_category_name
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def upload_asset(
self, path: str, label: str = "", content_type: Opt[str] = NotSet, name: Opt[str] = NotSet
) -> github.GitReleaseAsset.GitReleaseAsset:
"""
:calls: `POST https://<upload_url>/repos/{owner}/{repo}/releases/{release_id}/assets <https://docs.github.com/en/rest/releases/assets?apiVersion=2022-11-28#upload-a-release-assett>`_
"""
assert isinstance(path, str), path
assert isinstance(label, str), label
assert name is NotSet or isinstance(name, str), name
post_parameters: dict[str, Any] = {"label": label}
if name is NotSet:
post_parameters["name"] = basename(path)
else:
post_parameters["name"] = name
headers: dict[str, Any] = {}
if content_type is not NotSet:
headers["Content-Type"] = content_type
resp_headers, data = self._requester.requestBlobAndCheck(
"POST",
self.upload_url.split("{?")[0],
parameters=post_parameters,
headers=headers,
input=path,
)
return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True)
def upload_asset_from_memory(
self,
file_like: BinaryIO,
file_size: int,
name: str,
content_type: Opt[str] = NotSet,
label: str = "",
) -> github.GitReleaseAsset.GitReleaseAsset:
"""
Uploads an asset.
Unlike ``upload_asset()`` this method allows you to pass in a file-like object to upload.
Note that this method is more strict and requires you to specify the ``name``, since there's no file name to infer these from.
:calls: `POST https://<upload_url>/repos/{owner}/{repo}/releases/{release_id}/assets <https://docs.github.com/en/rest/reference/repos#upload-a-release-asset>`_
:param file_like: binary file-like object, such as those returned by ``open("file_name", "rb")``. At the very minimum, this object must implement ``read()``.
:param file_size: int, size in bytes of ``file_like``
"""
assert isinstance(name, str), name
assert isinstance(file_size, int), file_size
assert isinstance(label, str), label
post_parameters = {"label": label, "name": name}
content_type = content_type if content_type is not NotSet else Consts.defaultMediaType
headers = {"Content-Type": content_type, "Content-Length": str(file_size)}
resp_headers, data = self._requester.requestMemoryBlobAndCheck(
"POST",
self.upload_url.split("{?")[0],
parameters=post_parameters,
headers=headers,
file_like=file_like,
)
return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True)
def get_assets(self) -> PaginatedList[github.GitReleaseAsset.GitReleaseAsset]:
"""
:calls: `GET /repos/{owner}/{repo}/releases/{release_id}/assets <https://docs.github.com/en/rest/releases/assets?apiVersion=2022-11-28#get-a-release-asset>`_
"""
return github.PaginatedList.PaginatedList(
github.GitReleaseAsset.GitReleaseAsset,
self._requester,
f"{self.url}/assets",
None,
)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "id" in attributes:
self._id = self._makeIntAttribute(attributes["id"])
if "body" in attributes:
self._body = self._makeStringAttribute(attributes["body"])
if "name" in attributes:
self._title = self._makeStringAttribute(attributes["name"])
if "tag_name" in attributes:
self._tag_name = self._makeStringAttribute(attributes["tag_name"])
if "target_commitish" in attributes:
self._target_commitish = self._makeStringAttribute(attributes["target_commitish"])
if "draft" in attributes:
self._draft = self._makeBoolAttribute(attributes["draft"])
if "prerelease" in attributes:
self._prerelease = self._makeBoolAttribute(attributes["prerelease"])
if "generate_release_notes" in attributes:
self._generate_release_notes = self._makeBoolAttribute(attributes["generate_release_notes"])
if "author" in attributes:
self._author = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["author"])
if "url" in attributes:
self._url = self._makeStringAttribute(attributes["url"])
if "upload_url" in attributes:
self._upload_url = self._makeStringAttribute(attributes["upload_url"])
if "html_url" in attributes:
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "created_at" in attributes:
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "published_at" in attributes:
self._published_at = self._makeDatetimeAttribute(attributes["published_at"])
if "tarball_url" in attributes:
self._tarball_url = self._makeStringAttribute(attributes["tarball_url"])
if "zipball_url" in attributes:
self._zipball_url = self._makeStringAttribute(attributes["zipball_url"])
if "assets" in attributes:
self._assets = self._makeListOfClassesAttribute(
github.GitReleaseAsset.GitReleaseAsset, attributes["assets"]
)
| 16,200
|
Python
|
.py
| 304
| 45.930921
| 190
| 0.60483
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,405
|
GitTreeElement.py
|
PyGithub_PyGithub/github/GitTreeElement.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class GitTreeElement(NonCompletableGithubObject):
"""
This class represents GitTreeElements.
"""
def _initAttributes(self) -> None:
self._mode: Attribute[str] = NotSet
self._path: Attribute[str] = NotSet
self._sha: Attribute[str] = NotSet
self._size: Attribute[int] = NotSet
self._type: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"sha": self._sha.value, "path": self._path.value})
@property
def mode(self) -> str:
return self._mode.value
@property
def path(self) -> str:
return self._path.value
@property
def sha(self) -> str:
return self._sha.value
@property
def size(self) -> int:
return self._size.value
@property
def type(self) -> str:
return self._type.value
@property
def url(self) -> str:
return self._url.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "mode" in attributes: # pragma no branch
self._mode = self._makeStringAttribute(attributes["mode"])
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(attributes["path"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "size" in attributes: # pragma no branch
self._size = self._makeIntAttribute(attributes["size"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 4,796
|
Python
|
.py
| 82
| 53.719512
| 83
| 0.512019
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,406
|
DependabotAlertVulnerability.py
|
PyGithub_PyGithub/github/DependabotAlertVulnerability.py
|
############################ Copyrights and license ############################
# #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.AdvisoryVulnerabilityPackage
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.AdvisoryVulnerabilityPackage import AdvisoryVulnerabilityPackage
class DependabotAlertVulnerability(NonCompletableGithubObject):
"""
A vulnerability represented in a Dependabot alert.
"""
def _initAttributes(self) -> None:
self._package: Attribute[AdvisoryVulnerabilityPackage] = NotSet
self._severity: Attribute[str] = NotSet
self._vulnerable_version_range: Attribute[str | None] = NotSet
self._first_patched_version: Attribute[dict] = NotSet
@property
def package(self) -> AdvisoryVulnerabilityPackage:
return self._package.value
@property
def severity(self) -> str:
return self._severity.value
@property
def vulnerable_version_range(self) -> str | None:
return self._vulnerable_version_range.value
@property
def first_patched_version(self) -> dict:
return self._first_patched_version.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "package" in attributes:
self._package = self._makeClassAttribute(
github.AdvisoryVulnerabilityPackage.AdvisoryVulnerabilityPackage,
attributes["package"],
)
if "severity" in attributes:
self._severity = self._makeStringAttribute(attributes["severity"])
if "vulnerable_version_range" in attributes:
self._vulnerable_version_range = self._makeStringAttribute(attributes["vulnerable_version_range"])
if "first_patched_version" in attributes:
self._first_patched_version = self._makeDictAttribute(
attributes["first_patched_version"],
)
| 3,682
|
Python
|
.py
| 63
| 52.936508
| 110
| 0.542556
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,407
|
Gist.py
|
PyGithub_PyGithub/github/Gist.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Dale Jung <dale@dalejung.com> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2018 ç¾½ <Just4test@users.noreply.github.com> #
# Copyright 2019 Jon Dufresne <jon.dufresne@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.GistComment
import github.GistFile
import github.GistHistoryState
import github.GithubObject
import github.NamedUser
import github.PaginatedList
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, _NotSetType, is_defined, is_optional
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.GistComment import GistComment
from github.GistHistoryState import GistHistoryState
from github.InputFileContent import InputFileContent
class Gist(CompletableGithubObject):
"""
This class represents Gists.
The reference can be found here
https://docs.github.com/en/rest/reference/gists
"""
def _initAttributes(self) -> None:
self._comments: Attribute[int] = NotSet
self._comments_url: Attribute[str] = NotSet
self._commits_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._description: Attribute[str] = NotSet
self._files: Attribute[dict[str, github.GistFile.GistFile]] = NotSet
self._fork_of: Attribute[Gist] = NotSet
self._forks: Attribute[list[Gist]] = NotSet
self._forks_url: Attribute[str] = NotSet
self._git_pull_url: Attribute[str] = NotSet
self._git_push_url: Attribute[str] = NotSet
self._history: Attribute[list[GistHistoryState]] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[str] = NotSet
self._owner: Attribute[github.NamedUser.NamedUser] = NotSet
self._public: Attribute[bool] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._user: Attribute[github.NamedUser.NamedUser] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def comments(self) -> int:
self._completeIfNotSet(self._comments)
return self._comments.value
@property
def comments_url(self) -> str:
self._completeIfNotSet(self._comments_url)
return self._comments_url.value
@property
def commits_url(self) -> str:
self._completeIfNotSet(self._commits_url)
return self._commits_url.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def description(self) -> str:
self._completeIfNotSet(self._description)
return self._description.value
@property
def files(self) -> dict[str, github.GistFile.GistFile]:
self._completeIfNeeded()
return self._files.value
@property
def fork_of(self) -> github.Gist.Gist:
self._completeIfNotSet(self._fork_of)
return self._fork_of.value
@property
def forks(self) -> list[Gist]:
self._completeIfNotSet(self._forks)
return self._forks.value
@property
def forks_url(self) -> str:
self._completeIfNotSet(self._forks_url)
return self._forks_url.value
@property
def git_pull_url(self) -> str:
self._completeIfNotSet(self._git_pull_url)
return self._git_pull_url.value
@property
def git_push_url(self) -> str:
self._completeIfNotSet(self._git_push_url)
return self._git_push_url.value
@property
def history(self) -> list[GistHistoryState]:
self._completeIfNotSet(self._history)
return self._history.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> str:
self._completeIfNotSet(self._id)
return self._id.value
@property
def owner(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._owner)
return self._owner.value
@property
def public(self) -> bool:
self._completeIfNotSet(self._public)
return self._public.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def user(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
def create_comment(self, body: str) -> GistComment:
"""
:calls: `POST /gists/{gist_id}/comments <https://docs.github.com/en/rest/reference/gists#comments>`_
"""
assert isinstance(body, str), body
post_parameters = {
"body": body,
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/comments", input=post_parameters)
return github.GistComment.GistComment(self._requester, headers, data, completed=True)
def create_fork(self) -> Gist:
"""
:calls: `POST /gists/{id}/forks <https://docs.github.com/en/rest/reference/gists>`_
"""
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/forks")
return Gist(self._requester, headers, data, completed=True)
def delete(self) -> None:
"""
:calls: `DELETE /gists/{id} <https://docs.github.com/en/rest/reference/gists>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(self, description: Opt[str] = NotSet, files: Opt[dict[str, InputFileContent | None]] = NotSet) -> None:
"""
:calls: `PATCH /gists/{id} <https://docs.github.com/en/rest/reference/gists>`_
"""
assert is_optional(description, str), description
# limitation of `TypeGuard`
assert isinstance(files, _NotSetType) or all(
element is None or isinstance(element, github.InputFileContent) for element in files.values()
), files
post_parameters: dict[str, Any] = {}
if is_defined(description):
post_parameters["description"] = description
if is_defined(files):
post_parameters["files"] = {key: None if value is None else value._identity for key, value in files.items()}
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def get_comment(self, id: int) -> GistComment:
"""
:calls: `GET /gists/{gist_id}/comments/{id} <https://docs.github.com/en/rest/reference/gists#comments>`_
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/comments/{id}")
return github.GistComment.GistComment(self._requester, headers, data, completed=True)
def get_comments(self) -> PaginatedList[GistComment]:
"""
:calls: `GET /gists/{gist_id}/comments <https://docs.github.com/en/rest/reference/gists#comments>`_
"""
return PaginatedList(
github.GistComment.GistComment,
self._requester,
f"{self.url}/comments",
None,
)
def is_starred(self) -> bool:
"""
:calls: `GET /gists/{id}/star <https://docs.github.com/en/rest/reference/gists>`_
"""
status, headers, data = self._requester.requestJson("GET", f"{self.url}/star")
return status == 204
def reset_starred(self) -> None:
"""
:calls: `DELETE /gists/{id}/star <https://docs.github.com/en/rest/reference/gists>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/star")
def set_starred(self) -> None:
"""
:calls: `PUT /gists/{id}/star <https://docs.github.com/en/rest/reference/gists>`_
"""
headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/star")
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "comments" in attributes: # pragma no branch
self._comments = self._makeIntAttribute(attributes["comments"])
if "comments_url" in attributes: # pragma no branch
self._comments_url = self._makeStringAttribute(attributes["comments_url"])
if "commits_url" in attributes: # pragma no branch
self._commits_url = self._makeStringAttribute(attributes["commits_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "files" in attributes: # pragma no branch
self._files = self._makeDictOfStringsToClassesAttribute(github.GistFile.GistFile, attributes["files"])
if "fork_of" in attributes: # pragma no branch
self._fork_of = self._makeClassAttribute(Gist, attributes["fork_of"])
if "forks" in attributes: # pragma no branch
self._forks = self._makeListOfClassesAttribute(Gist, attributes["forks"])
if "forks_url" in attributes: # pragma no branch
self._forks_url = self._makeStringAttribute(attributes["forks_url"])
if "git_pull_url" in attributes: # pragma no branch
self._git_pull_url = self._makeStringAttribute(attributes["git_pull_url"])
if "git_push_url" in attributes: # pragma no branch
self._git_push_url = self._makeStringAttribute(attributes["git_push_url"])
if "history" in attributes: # pragma no branch
self._history = self._makeListOfClassesAttribute(
github.GistHistoryState.GistHistoryState, attributes["history"]
)
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeStringAttribute(attributes["id"])
if "owner" in attributes: # pragma no branch
self._owner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["owner"])
if "public" in attributes: # pragma no branch
self._public = self._makeBoolAttribute(attributes["public"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 14,291
|
Python
|
.py
| 273
| 45.25641
| 120
| 0.605194
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,408
|
TimelineEventSource.py
|
PyGithub_PyGithub/github/TimelineEventSource.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Nick Campbell <nicholas.j.campbell@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.Issue
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.Issue import Issue
class TimelineEventSource(NonCompletableGithubObject):
"""
This class represents IssueTimelineEventSource.
The reference can be found here
https://docs.github.com/en/rest/reference/issues#timeline
"""
def _initAttributes(self) -> None:
self._type: Attribute[str] = NotSet
self._issue: Attribute[Issue] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"type": self._type.value})
@property
def type(self) -> str:
return self._type.value
@property
def issue(self) -> Issue:
return self._issue.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "issue" in attributes: # pragma no branch
self._issue = self._makeClassAttribute(github.Issue.Issue, attributes["issue"])
| 4,243
|
Python
|
.py
| 66
| 61.090909
| 91
| 0.518732
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,409
|
Stargazer.py
|
PyGithub_PyGithub/github/Stargazer.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Dan Vanderkam <danvdk@gmail.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.NamedUser
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.NamedUser import NamedUser
class Stargazer(NonCompletableGithubObject):
"""
This class represents Stargazers.
The reference can be found here
https://docs.github.com/en/rest/reference/activity#starring
"""
def _initAttributes(self) -> None:
self._starred_at: Attribute[datetime] = NotSet
self._user: Attribute[NamedUser] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
# this is not a type error, just we didn't type `NamedUser` yet.
# enable type checker here after we typed attribute of `NamedUser`
return self.get__repr__({"user": self._user.value._login.value}) # type: ignore
@property
def starred_at(self) -> datetime:
return self._starred_at.value
@property
def user(self) -> NamedUser:
return self._user.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "starred_at" in attributes:
self._starred_at = self._makeDatetimeAttribute(attributes["starred_at"])
if "user" in attributes:
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 4,744
|
Python
|
.py
| 73
| 61.671233
| 97
| 0.52383
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,410
|
DeploymentStatus.py
|
PyGithub_PyGithub/github/DeploymentStatus.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Matt Babineau <mbabineau@dataxu.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Martijn Koster <mak-github@greenhills.co.uk> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Colby Gallup <colbygallup@gmail.com> #
# Copyright 2020 Pascal Hofmann <mail@pascalhofmann.de> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.NamedUser
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class DeploymentStatus(CompletableGithubObject):
"""
This class represents Deployment Statuses.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#deployments
"""
def _initAttributes(self) -> None:
self._created_at: Attribute[datetime] = NotSet
self._creator: Attribute[github.NamedUser.NamedUser] = NotSet
self._deployment_url: Attribute[str] = NotSet
self._description: Attribute[str] = NotSet
self._environment: Attribute[str] = NotSet
self._environment_url: Attribute[str] = NotSet
self._repository_url: Attribute[str] = NotSet
self._state: Attribute[str] = NotSet
self._target_url: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._node_id: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "url": self._url.value})
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def creator(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._creator)
return self._creator.value
@property
def deployment_url(self) -> str:
self._completeIfNotSet(self._deployment_url)
return self._deployment_url.value
@property
def description(self) -> str:
self._completeIfNotSet(self._description)
return self._description.value
@property
def environment(self) -> str:
self._completeIfNotSet(self._environment)
return self._environment.value
@property
def environment_url(self) -> str:
self._completeIfNotSet(self._environment_url)
return self._environment_url.value
@property
def repository_url(self) -> str:
self._completeIfNotSet(self._repository_url)
return self._repository_url.value
@property
def state(self) -> str:
self._completeIfNotSet(self._state)
return self._state.value
@property
def target_url(self) -> str:
self._completeIfNotSet(self._target_url)
return self._target_url.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "environment_url" in attributes: # pragma no branch
self._environment_url = self._makeStringAttribute(attributes["environment_url"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "creator" in attributes: # pragma no branch
self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"])
if "deployment_url" in attributes: # pragma no branch
self._deployment_url = self._makeStringAttribute(attributes["deployment_url"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "environment" in attributes: # pragma no branch
self._environment = self._makeStringAttribute(attributes["environment"])
if "repository_url" in attributes: # pragma no branch
self._repository_url = self._makeStringAttribute(attributes["repository_url"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "target_url" in attributes: # pragma no branch
self._target_url = self._makeStringAttribute(attributes["target_url"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
| 8,295
|
Python
|
.py
| 148
| 50.054054
| 103
| 0.581364
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,411
|
ProjectCard.py
|
PyGithub_PyGithub/github/ProjectCard.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Matt Babineau <mbabineau@dataxu.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Martijn Koster <mak-github@greenhills.co.uk> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 Yossarian King <yggy@blackbirdinteractive.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Jody McIntyre <scjody@modernduck.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 chloe jungah kim <43295963+chloeeekim@users.noreply.github.com>#
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.Issue
import github.NamedUser
import github.ProjectColumn
import github.PullRequest
from github import Consts
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt
# NOTE: There is currently no way to get cards "in triage" for a project.
# https://platform.github.community/t/moving-github-project-cards-that-are-in-triage/3784
#
# See also https://developer.github.com/v4/object/projectcard for the next generation GitHub API,
# which may point the way to where the API is likely headed and what might come back to v3. E.g. ProjectCard.content member.
class ProjectCard(CompletableGithubObject):
"""
This class represents Project Cards.
The reference can be found here
https://docs.github.com/en/rest/reference/projects#cards
"""
def _initAttributes(self) -> None:
self._archived: Attribute[bool] = NotSet
self._column_url: Attribute[str] = NotSet
self._content_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._creator: Attribute[github.NamedUser.NamedUser] = NotSet
self._id: Attribute[int] = NotSet
self._node_id: Attribute[str] = NotSet
self._note: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def archived(self) -> bool:
return self._archived.value
@property
def column_url(self) -> str:
return self._column_url.value
@property
def content_url(self) -> str:
return self._content_url.value
@property
def created_at(self) -> datetime:
return self._created_at.value
@property
def creator(self) -> github.NamedUser.NamedUser:
return self._creator.value
@property
def id(self) -> int:
return self._id.value
@property
def node_id(self) -> str:
return self._node_id.value
@property
def note(self) -> str:
return self._note.value
@property
def updated_at(self) -> datetime:
return self._updated_at.value
@property
def url(self) -> str:
return self._url.value
# Note that the content_url for any card will be an "issue" URL, from
# which you can retrieve either an Issue or a PullRequest. Unfortunately
# the API doesn't make it clear which you are dealing with.
def get_content(
self, content_type: Opt[str] = NotSet
) -> github.PullRequest.PullRequest | github.Issue.Issue | None:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number} <https://docs.github.com/en/rest/reference/pulls#get-a-pull-request>`_
"""
assert content_type is NotSet or isinstance(content_type, str), content_type
if self.content_url is None:
return None
retclass: type[github.PullRequest.PullRequest] | type[github.Issue.Issue]
if content_type == "PullRequest":
url = self.content_url.replace("issues", "pulls")
retclass = github.PullRequest.PullRequest
elif content_type is NotSet or content_type == "Issue":
url = self.content_url
retclass = github.Issue.Issue
else:
raise ValueError(f"Unknown content type: {content_type}")
headers, data = self._requester.requestJsonAndCheck("GET", url)
return retclass(self._requester, headers, data, completed=True)
def move(self, position: str, column: github.ProjectColumn.ProjectColumn | int) -> bool:
"""
:calls: `POST /projects/columns/cards/{card_id}/moves <https://docs.github.com/en/rest/reference/projects#cards>`_
"""
assert isinstance(position, str), position
assert isinstance(column, github.ProjectColumn.ProjectColumn) or isinstance(column, int), column
post_parameters = {
"position": position,
"column_id": column.id if isinstance(column, github.ProjectColumn.ProjectColumn) else column,
}
status, _, _ = self._requester.requestJson(
"POST",
f"{self.url}/moves",
input=post_parameters,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
return status == 201
def delete(self) -> bool:
"""
:calls: `DELETE /projects/columns/cards/{card_id} <https://docs.github.com/en/rest/reference/projects#cards>`_
"""
status, _, _ = self._requester.requestJson(
"DELETE",
self.url,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
return status == 204
def edit(self, note: Opt[str] = NotSet, archived: Opt[bool] = NotSet) -> None:
"""
:calls: `PATCH /projects/columns/cards/{card_id} <https://docs.github.com/en/rest/reference/projects#cards>`_
"""
assert note is NotSet or isinstance(note, str), note
assert archived is NotSet or isinstance(archived, bool), archived
patch_parameters: dict[str, Any] = NotSet.remove_unset_items({"note": note, "archived": archived})
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
self._useAttributes(data)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "archived" in attributes: # pragma no branch
self._archived = self._makeBoolAttribute(attributes["archived"])
if "column_url" in attributes: # pragma no branch
self._column_url = self._makeStringAttribute(attributes["column_url"])
if "content_url" in attributes: # pragma no branch
self._content_url = self._makeStringAttribute(attributes["content_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "creator" in attributes: # pragma no branch
self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "note" in attributes: # pragma no branch
self._note = self._makeStringAttribute(attributes["note"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 10,524
|
Python
|
.py
| 192
| 48.28125
| 128
| 0.591597
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,412
|
MainClass.py
|
PyGithub_PyGithub/github/MainClass.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Dima Kukushkin <dima@kukushkin.me> #
# Copyright 2012 Luke Cawood <luke.cawood@99designs.com> #
# Copyright 2012 Michael Woodworth <mwoodworth@upverter.com> #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Ed Jackson <ed.jackson@gmail.com> #
# Copyright 2013 Jonathan J Hunt <hunt@braincorporation.com> #
# Copyright 2013 Steve Brown <steve@evolvedlight.co.uk> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 C. R. Oldham <cro@ncbt.org> #
# Copyright 2014 Thialfihar <thi@thialfihar.org> #
# Copyright 2014 Tyler Treat <ttreat31@gmail.com> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Daniel Pocock <daniel@pocock.pro> #
# Copyright 2015 Joseph Rawson <joseph.rawson.works@littledebian.org> #
# Copyright 2015 Uriel Corfa <uriel@corfa.fr> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Colin Hoglund <colinhoglund@users.noreply.github.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2018 Agor Maxime <maxime.agor23@gmail.com> #
# Copyright 2018 Arda Kuyumcu <kuyumcuarda@gmail.com> #
# Copyright 2018 Benoit Latinier <benoit@latinier.fr> #
# Copyright 2018 Bruce Richardson <itsbruce@workshy.org> #
# Copyright 2018 Joshua Hoblitt <josh@hoblitt.com> #
# Copyright 2018 Maarten Fonville <mfonville@users.noreply.github.com> #
# Copyright 2018 Mike Miller <github@mikeage.net> #
# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Svend Sorensen <svend@svends.net> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 Yossarian King <yggy@blackbirdinteractive.com> #
# Copyright 2018 h.shi <10385628+AnYeMoWang@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Caleb Sweeney <caleb.w.sweeney@gmail.com> #
# Copyright 2019 Hamel Husain <hamelsmu@github.com> #
# Copyright 2019 Isac Souza <isouza@daitan.com> #
# Copyright 2019 Jake Klingensmith <jklingen92@users.noreply.github.com> #
# Copyright 2019 Jake Wilkins <jakewilkins@github.com> #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Tomas Tomecek <nereone@gmail.com> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2019 chillipeper <miguel.tpy@gmail.com> #
# Copyright 2019 秋葉 <ambiguous404@gmail.com> #
# Copyright 2020 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2020 Denis Blanchette <dblanchette@coveo.com> #
# Copyright 2020 Florent Clarret <florent.clarret@gmail.com> #
# Copyright 2020 Mahesh Raju <coder@mahesh.net> #
# Copyright 2020 Nikolay Edigaryev <edigaryev@gmail.com> #
# Copyright 2020 Omar Brikaa <brikaaomar@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Amador Pahim <apahim@redhat.com> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Sachi King <nakato@nakato.io> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Denis Blanchette <dblanchette@coveo.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Hemslo Wang <hemslo.wang@gmail.com> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Mark Amery <markamery@btinternet.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 YugoHino <henom06@gmail.com> #
# Copyright 2023 chantra <chantra@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import pickle
import urllib.parse
import warnings
from datetime import datetime
from typing import TYPE_CHECKING, Any, BinaryIO, TypeVar
import urllib3
from urllib3.util import Retry
import github.ApplicationOAuth
import github.Auth
import github.AuthenticatedUser
import github.Enterprise
import github.Event
import github.Gist
import github.GithubApp
import github.GithubIntegration
import github.GithubRetry
import github.GitignoreTemplate
import github.GlobalAdvisory
import github.License
import github.NamedUser
import github.Topic
from github import Consts
from github.GithubIntegration import GithubIntegration
from github.GithubObject import GithubObject, NotSet, Opt, is_defined
from github.GithubRetry import GithubRetry
from github.HookDelivery import HookDelivery, HookDeliverySummary
from github.HookDescription import HookDescription
from github.PaginatedList import PaginatedList
from github.RateLimit import RateLimit
from github.Requester import Requester
if TYPE_CHECKING:
from github.AppAuthentication import AppAuthentication
from github.ApplicationOAuth import ApplicationOAuth
from github.AuthenticatedUser import AuthenticatedUser
from github.Commit import Commit
from github.ContentFile import ContentFile
from github.Event import Event
from github.Gist import Gist
from github.GithubApp import GithubApp
from github.GitignoreTemplate import GitignoreTemplate
from github.GlobalAdvisory import GlobalAdvisory
from github.Issue import Issue
from github.License import License
from github.NamedUser import NamedUser
from github.Organization import Organization
from github.Project import Project
from github.ProjectColumn import ProjectColumn
from github.Repository import Repository
from github.Topic import Topic
TGithubObject = TypeVar("TGithubObject", bound=GithubObject)
class Github:
"""
This is the main class you instantiate to access the Github API v3.
Optional parameters allow different authentication methods.
"""
__requester: Requester
default_retry = GithubRetry()
# keep non-deprecated arguments in-sync with Requester
# v3: remove login_or_token, password, jwt and app_auth
# v3: move auth to the front of arguments
# v3: add * before first argument so all arguments must be named,
# allows to reorder / add new arguments / remove deprecated arguments without breaking user code
def __init__(
self,
login_or_token: str | None = None,
password: str | None = None,
jwt: str | None = None,
app_auth: AppAuthentication | None = None,
base_url: str = Consts.DEFAULT_BASE_URL,
timeout: int = Consts.DEFAULT_TIMEOUT,
user_agent: str = Consts.DEFAULT_USER_AGENT,
per_page: int = Consts.DEFAULT_PER_PAGE,
verify: bool | str = True,
retry: int | Retry | None = default_retry,
pool_size: int | None = None,
seconds_between_requests: float | None = Consts.DEFAULT_SECONDS_BETWEEN_REQUESTS,
seconds_between_writes: float | None = Consts.DEFAULT_SECONDS_BETWEEN_WRITES,
auth: github.Auth.Auth | None = None,
) -> None:
"""
:param login_or_token: string deprecated, use auth=github.Auth.Login(...) or auth=github.Auth.Token(...) instead
:param password: string deprecated, use auth=github.Auth.Login(...) instead
:param jwt: string deprecated, use auth=github.Auth.AppAuth(...) or auth=github.Auth.AppAuthToken(...) instead
:param app_auth: github.AppAuthentication deprecated, use auth=github.Auth.AppInstallationAuth(...) instead
:param base_url: string
:param timeout: integer
:param user_agent: string
:param per_page: int
:param verify: boolean or string
:param retry: int or urllib3.util.retry.Retry object,
defaults to github.Github.default_retry,
set to None to disable retries
:param pool_size: int
:param seconds_between_requests: float
:param seconds_between_writes: float
:param auth: authentication method
"""
assert login_or_token is None or isinstance(login_or_token, str), login_or_token
assert password is None or isinstance(password, str), password
assert jwt is None or isinstance(jwt, str), jwt
assert isinstance(base_url, str), base_url
assert isinstance(timeout, int), timeout
assert user_agent is None or isinstance(user_agent, str), user_agent
assert isinstance(per_page, int), per_page
assert isinstance(verify, (bool, str)), verify
assert retry is None or isinstance(retry, int) or isinstance(retry, urllib3.util.Retry), retry
assert pool_size is None or isinstance(pool_size, int), pool_size
assert seconds_between_requests is None or seconds_between_requests >= 0
assert seconds_between_writes is None or seconds_between_writes >= 0
assert auth is None or isinstance(auth, github.Auth.Auth), auth
if password is not None:
warnings.warn(
"Arguments login_or_token and password are deprecated, please use "
"auth=github.Auth.Login(...) instead",
category=DeprecationWarning,
)
auth = github.Auth.Login(login_or_token, password) # type: ignore
elif login_or_token is not None:
warnings.warn(
"Argument login_or_token is deprecated, please use " "auth=github.Auth.Token(...) instead",
category=DeprecationWarning,
)
auth = github.Auth.Token(login_or_token)
elif jwt is not None:
warnings.warn(
"Argument jwt is deprecated, please use "
"auth=github.Auth.AppAuth(...) or "
"auth=github.Auth.AppAuthToken(...) instead",
category=DeprecationWarning,
)
auth = github.Auth.AppAuthToken(jwt)
elif app_auth is not None:
warnings.warn(
"Argument app_auth is deprecated, please use " "auth=github.Auth.AppInstallationAuth(...) instead",
category=DeprecationWarning,
)
auth = app_auth
self.__requester = Requester(
auth,
base_url,
timeout,
user_agent,
per_page,
verify,
retry,
pool_size,
seconds_between_requests,
seconds_between_writes,
)
def close(self) -> None:
"""Close connections to the server. Alternatively, use the Github
object as a context manager:
.. code-block:: python
with github.Github(...) as gh:
# do something
"""
self.__requester.close()
def __enter__(self) -> Github:
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.close()
@property
def requester(self) -> Requester:
"""
Return my Requester object.
For example, to make requests to API endpoints not yet supported by PyGitHub.
"""
return self.__requester
@property
def FIX_REPO_GET_GIT_REF(self) -> bool:
return self.__requester.FIX_REPO_GET_GIT_REF
@FIX_REPO_GET_GIT_REF.setter
def FIX_REPO_GET_GIT_REF(self, value: bool) -> None:
self.__requester.FIX_REPO_GET_GIT_REF = value
# v3: Remove this property? Why should it be necessary to read/modify it after construction
@property
def per_page(self) -> int:
return self.__requester.per_page
@per_page.setter
def per_page(self, value: int) -> None:
self.__requester.per_page = value
# v3: Provide a unified way to access values of headers of last response
# v3: (and add/keep ad hoc properties for specific useful headers like rate limiting, oauth scopes, etc.)
# v3: Return an instance of a class: using a tuple did not allow to add a field "resettime"
@property
def rate_limiting(self) -> tuple[int, int]:
"""
First value is requests remaining, second value is request limit.
"""
remaining, limit = self.__requester.rate_limiting
if limit < 0:
self.get_rate_limit()
return self.__requester.rate_limiting
@property
def rate_limiting_resettime(self) -> int:
"""
Unix timestamp indicating when rate limiting will reset.
"""
if self.__requester.rate_limiting_resettime == 0:
self.get_rate_limit()
return self.__requester.rate_limiting_resettime
def get_rate_limit(self) -> RateLimit:
"""
Rate limit status for different resources (core/search/graphql).
:calls: `GET /rate_limit
<https://docs.github.com/en/rest/reference/rate-limit>`_
"""
headers, data = self.__requester.requestJsonAndCheck("GET", "/rate_limit")
return RateLimit(self.__requester, headers, data["resources"], True)
@property
def oauth_scopes(self) -> list[str] | None:
"""
:type: list of string
"""
return self.__requester.oauth_scopes
def get_license(self, key: Opt[str] = NotSet) -> License:
"""
:calls: `GET /license/{license} <https://docs.github.com/en/rest/reference/licenses#get-a-license>`_
"""
assert isinstance(key, str), key
key = urllib.parse.quote(key)
headers, data = self.__requester.requestJsonAndCheck("GET", f"/licenses/{key}")
return github.License.License(self.__requester, headers, data, completed=True)
def get_licenses(self) -> PaginatedList[License]:
"""
:calls: `GET /licenses <https://docs.github.com/en/rest/reference/licenses#get-all-commonly-used-licenses>`_
"""
url_parameters: dict[str, Any] = {}
return PaginatedList(github.License.License, self.__requester, "/licenses", url_parameters)
def get_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /events <https://docs.github.com/en/rest/reference/activity#list-public-events>`_
"""
return PaginatedList(github.Event.Event, self.__requester, "/events", None)
def get_user(self, login: Opt[str] = NotSet) -> NamedUser | AuthenticatedUser:
"""
:calls: `GET /users/{user} <https://docs.github.com/en/rest/reference/users>`_ or `GET /user <https://docs.github.com/en/rest/reference/users>`_
"""
if login is NotSet:
return github.AuthenticatedUser.AuthenticatedUser(self.__requester, {}, {"url": "/user"}, completed=False)
else:
assert isinstance(login, str), login
login = urllib.parse.quote(login)
headers, data = self.__requester.requestJsonAndCheck("GET", f"/users/{login}")
return github.NamedUser.NamedUser(self.__requester, headers, data, completed=True)
def get_user_by_id(self, user_id: int) -> NamedUser:
"""
:calls: `GET /user/{id} <https://docs.github.com/en/rest/reference/users>`_
:param user_id: int
:rtype: :class:`github.NamedUser.NamedUser`
"""
assert isinstance(user_id, int), user_id
headers, data = self.__requester.requestJsonAndCheck("GET", f"/user/{user_id}")
return github.NamedUser.NamedUser(self.__requester, headers, data, completed=True)
def get_users(self, since: Opt[int] = NotSet) -> PaginatedList[NamedUser]:
"""
:calls: `GET /users <https://docs.github.com/en/rest/reference/users>`_
"""
assert since is NotSet or isinstance(since, int), since
url_parameters = dict()
if since is not NotSet:
url_parameters["since"] = since
return PaginatedList(github.NamedUser.NamedUser, self.__requester, "/users", url_parameters)
def get_organization(self, login: str) -> Organization:
"""
:calls: `GET /orgs/{org} <https://docs.github.com/en/rest/reference/orgs>`_
"""
assert isinstance(login, str), login
login = urllib.parse.quote(login)
headers, data = self.__requester.requestJsonAndCheck("GET", f"/orgs/{login}")
return github.Organization.Organization(self.__requester, headers, data, completed=True)
def get_organizations(self, since: Opt[int] = NotSet) -> PaginatedList[Organization]:
"""
:calls: `GET /organizations <https://docs.github.com/en/rest/reference/orgs#list-organizations>`_
"""
assert since is NotSet or isinstance(since, int), since
url_parameters = dict()
if since is not NotSet:
url_parameters["since"] = since
return PaginatedList(
github.Organization.Organization,
self.__requester,
"/organizations",
url_parameters,
)
def get_enterprise(self, enterprise: str) -> github.Enterprise.Enterprise:
"""
:calls: `GET /enterprises/{enterprise} <https://docs.github.com/en/enterprise-cloud@latest/rest/enterprise-admin>`_
:param enterprise: string
:rtype: :class:`Enterprise`
"""
assert isinstance(enterprise, str), enterprise
# There is no native "/enterprises/{enterprise}" api, so this function is a hub for apis that start with "/enterprise/{enterprise}".
return github.Enterprise.Enterprise(self.__requester, enterprise)
def get_repo(self, full_name_or_id: int | str, lazy: bool = False) -> Repository:
"""
:calls: `GET /repos/{owner}/{repo} <https://docs.github.com/en/rest/reference/repos>`_ or `GET /repositories/{id} <https://docs.github.com/en/rest/reference/repos>`_
"""
assert isinstance(full_name_or_id, (str, int)), full_name_or_id
url_base = "/repositories/" if isinstance(full_name_or_id, int) else "/repos/"
url = f"{url_base}{full_name_or_id}"
if lazy:
return github.Repository.Repository(self.__requester, {}, {"url": url}, completed=False)
headers, data = self.__requester.requestJsonAndCheck("GET", url)
return github.Repository.Repository(self.__requester, headers, data, completed=True)
def get_repos(
self,
since: Opt[int] = NotSet,
visibility: Opt[str] = NotSet,
) -> PaginatedList[Repository]:
"""
:calls: `GET /repositories <https://docs.github.com/en/rest/reference/repos#list-public-repositories>`_
:param since: integer
:param visibility: string ('all','public')
"""
assert since is NotSet or isinstance(since, int), since
url_parameters: dict[str, Any] = {}
if since is not NotSet:
url_parameters["since"] = since
if visibility is not NotSet:
assert visibility in ("public", "all"), visibility
url_parameters["visibility"] = visibility
return PaginatedList(
github.Repository.Repository,
self.__requester,
"/repositories",
url_parameters,
)
def get_project(self, id: int) -> Project:
"""
:calls: `GET /projects/{project_id} <https://docs.github.com/en/rest/reference/projects#get-a-project>`_
"""
headers, data = self.__requester.requestJsonAndCheck(
"GET",
f"/projects/{id:d}",
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
return github.Project.Project(self.__requester, headers, data, completed=True)
def get_project_column(self, id: int) -> ProjectColumn:
"""
:calls: `GET /projects/columns/{column_id} <https://docs.github.com/en/rest/reference/projects#get-a-project-column>`_
"""
headers, data = self.__requester.requestJsonAndCheck(
"GET",
"/projects/columns/%d" % id,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
return github.ProjectColumn.ProjectColumn(self.__requester, headers, data, completed=True)
def get_gist(self, id: str) -> Gist:
"""
:calls: `GET /gists/{id} <https://docs.github.com/en/rest/reference/gists>`_
"""
assert isinstance(id, str), id
headers, data = self.__requester.requestJsonAndCheck("GET", f"/gists/{id}")
return github.Gist.Gist(self.__requester, headers, data, completed=True)
def get_gists(self, since: Opt[datetime] = NotSet) -> PaginatedList[Gist]:
"""
:calls: `GET /gists/public <https://docs.github.com/en/rest/reference/gists>`_
"""
assert since is NotSet or isinstance(since, datetime), since
url_parameters = dict()
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(github.Gist.Gist, self.__requester, "/gists/public", url_parameters)
def get_global_advisory(self, ghsa_id: str) -> GlobalAdvisory:
"""
:calls: `GET /advisories/{ghsa_id} <https://docs.github.com/en/rest/security-advisories/global-advisories>`_
:param ghsa_id: string
:rtype: :class:`github.GlobalAdvisory.GlobalAdvisory`
"""
assert isinstance(ghsa_id, str), ghsa_id
ghsa_id = urllib.parse.quote(ghsa_id)
headers, data = self.__requester.requestJsonAndCheck("GET", f"/advisories/{ghsa_id}")
return github.GlobalAdvisory.GlobalAdvisory(self.__requester, headers, data, completed=True)
def get_global_advisories(
self,
type: Opt[str] = NotSet,
ghsa_id: Opt[str] = NotSet,
cve_id: Opt[str] = NotSet,
ecosystem: Opt[str] = NotSet,
severity: Opt[str] = NotSet,
cwes: list[Opt[str]] | Opt[str] = NotSet,
is_withdrawn: Opt[bool] = NotSet,
affects: list[str] | Opt[str] = NotSet,
published: Opt[str] = NotSet,
updated: Opt[str] = NotSet,
modified: Opt[str] = NotSet,
keywords: Opt[str] = NotSet,
before: Opt[str] = NotSet,
after: Opt[str] = NotSet,
per_page: Opt[str] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
) -> PaginatedList[GlobalAdvisory]:
"""
:calls: `GET /advisories <https://docs.github.com/en/rest/security-advisories/global-advisories>`
:param type: Optional string
:param ghsa_id: Optional string
:param cve_id: Optional string
:param ecosystem: Optional string
:param severity: Optional string
:param cwes: Optional comma separated string or list of integer or string
:param is_withdrawn: Optional bool
:param affects: Optional comma separated string or list of string
:param published: Optional string
:param updated: Optional string
:param modified: Optional string
:param before: Optional string
:param after: Optional string
:param sort: Optional string
:param direction: Optional string
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GlobalAdvisory.GlobalAdvisory`
"""
assert type is github.GithubObject.NotSet or isinstance(type, str), type
assert ghsa_id is github.GithubObject.NotSet or isinstance(ghsa_id, str)
assert cve_id is github.GithubObject.NotSet or isinstance(cve_id, str), cve_id
assert ecosystem is github.GithubObject.NotSet or isinstance(ecosystem, str), ecosystem
assert severity is github.GithubObject.NotSet or isinstance(severity, str), severity
assert cwes is github.GithubObject.NotSet or isinstance(cwes, list) or isinstance(cwes, str), cwes
assert is_withdrawn is github.GithubObject.NotSet or isinstance(is_withdrawn, bool), is_withdrawn
assert affects is github.GithubObject.NotSet or isinstance(affects, list) or isinstance(affects, str), affects
assert published is github.GithubObject.NotSet or isinstance(published, str), published
assert updated is github.GithubObject.NotSet or isinstance(updated, str), updated
assert modified is github.GithubObject.NotSet or isinstance(modified, str), modified
assert before is github.GithubObject.NotSet or isinstance(before, str), before
assert after is github.GithubObject.NotSet or isinstance(after, str), after
assert sort is github.GithubObject.NotSet or isinstance(sort, str), sort
assert direction is github.GithubObject.NotSet or isinstance(direction, str), direction
url_parameters: dict[str, Opt[str | bool]] = dict()
if type is not github.GithubObject.NotSet: # pragma no branch (Should be covered)
assert type in ("reviewed", "unreviewed", "malware"), type
url_parameters["type"] = type
if ghsa_id is not github.GithubObject.NotSet:
url_parameters["ghsa_id"] = ghsa_id
if cve_id is not github.GithubObject.NotSet:
url_parameters["cve_id"] = cve_id
# Can be one of: actions, composer, erlang, go, maven, npm, nuget, other, pip, pub, rubygems, rust
# Not asserting in that list so that the package doesn't need to be updated when a new ecosystem is added
if ecosystem is not github.GithubObject.NotSet:
url_parameters["ecosystem"] = ecosystem
if severity is not github.GithubObject.NotSet:
assert severity in ("null", "low", "medium", "high", "critical"), severity
url_parameters["severity"] = severity
if cwes is not github.GithubObject.NotSet:
if isinstance(cwes, list):
cwes = ",".join([str(cwe) for cwe in cwes])
url_parameters["cwes"] = cwes
if is_withdrawn is not github.GithubObject.NotSet:
url_parameters["is_withdrawn"] = is_withdrawn
if affects is not github.GithubObject.NotSet:
if isinstance(affects, list):
affects = ",".join(affects)
url_parameters["affects"] = affects
if published is not github.GithubObject.NotSet:
url_parameters["published"] = published
if updated is not github.GithubObject.NotSet:
url_parameters["updated"] = updated
if modified is not github.GithubObject.NotSet:
url_parameters["modified"] = modified
if before is not github.GithubObject.NotSet:
url_parameters["before"] = before
if after is not github.GithubObject.NotSet:
url_parameters["after"] = after
if sort is not github.GithubObject.NotSet:
assert sort in ("published", "updated"), sort
url_parameters["sort"] = sort
if direction is not github.GithubObject.NotSet:
assert direction in ("asc", "desc"), direction
url_parameters["direction"] = direction
return github.PaginatedList.PaginatedList(
github.GlobalAdvisory.GlobalAdvisory,
self.__requester,
"/advisories",
url_parameters,
)
def search_repositories(
self,
query: str,
sort: Opt[str] = NotSet,
order: Opt[str] = NotSet,
**qualifiers: Any,
) -> PaginatedList[Repository]:
"""
:calls: `GET /search/repositories <https://docs.github.com/en/rest/reference/search>`_
:param query: string
:param sort: string ('stars', 'forks', 'updated')
:param order: string ('asc', 'desc')
:param qualifiers: keyword dict query qualifiers
"""
assert isinstance(query, str), query
url_parameters = dict()
if sort is not NotSet: # pragma no branch (Should be covered)
assert sort in ("stars", "forks", "updated"), sort
url_parameters["sort"] = sort
if order is not NotSet: # pragma no branch (Should be covered)
assert order in ("asc", "desc"), order
url_parameters["order"] = order
query_chunks = []
if query: # pragma no branch (Should be covered)
query_chunks.append(query)
for qualifier, value in qualifiers.items():
query_chunks.append(f"{qualifier}:{value}")
url_parameters["q"] = " ".join(query_chunks)
assert url_parameters["q"], "need at least one qualifier"
return PaginatedList(
github.Repository.Repository,
self.__requester,
"/search/repositories",
url_parameters,
)
def search_users(
self,
query: str,
sort: Opt[str] = NotSet,
order: Opt[str] = NotSet,
**qualifiers: Any,
) -> PaginatedList[NamedUser]:
"""
:calls: `GET /search/users <https://docs.github.com/en/rest/reference/search>`_
:param query: string
:param sort: string ('followers', 'repositories', 'joined')
:param order: string ('asc', 'desc')
:param qualifiers: keyword dict query qualifiers
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
assert isinstance(query, str), query
url_parameters = dict()
if sort is not NotSet:
assert sort in ("followers", "repositories", "joined"), sort
url_parameters["sort"] = sort
if order is not NotSet:
assert order in ("asc", "desc"), order
url_parameters["order"] = order
query_chunks = []
if query:
query_chunks.append(query)
for qualifier, value in qualifiers.items():
query_chunks.append(f"{qualifier}:{value}")
url_parameters["q"] = " ".join(query_chunks)
assert url_parameters["q"], "need at least one qualifier"
return PaginatedList(
github.NamedUser.NamedUser,
self.__requester,
"/search/users",
url_parameters,
)
def search_issues(
self,
query: str,
sort: Opt[str] = NotSet,
order: Opt[str] = NotSet,
**qualifiers: Any,
) -> PaginatedList[Issue]:
"""
:calls: `GET /search/issues <https://docs.github.com/en/rest/reference/search>`_
:param query: string
:param sort: string ('comments', 'created', 'updated')
:param order: string ('asc', 'desc')
:param qualifiers: keyword dict query qualifiers
:rtype: :class:`PaginatedList` of :class:`github.Issue.Issue`
"""
assert isinstance(query, str), query
url_parameters = dict()
if sort is not NotSet:
assert sort in ("comments", "created", "updated"), sort
url_parameters["sort"] = sort
if order is not NotSet:
assert order in ("asc", "desc"), order
url_parameters["order"] = order
query_chunks = []
if query: # pragma no branch (Should be covered)
query_chunks.append(query)
for qualifier, value in qualifiers.items():
query_chunks.append(f"{qualifier}:{value}")
url_parameters["q"] = " ".join(query_chunks)
assert url_parameters["q"], "need at least one qualifier"
return PaginatedList(github.Issue.Issue, self.__requester, "/search/issues", url_parameters)
def search_code(
self,
query: str,
sort: Opt[str] = NotSet,
order: Opt[str] = NotSet,
highlight: bool = False,
**qualifiers: Any,
) -> PaginatedList[ContentFile]:
"""
:calls: `GET /search/code <https://docs.github.com/en/rest/reference/search>`_
:param query: string
:param sort: string ('indexed')
:param order: string ('asc', 'desc')
:param highlight: boolean (True, False)
:param qualifiers: keyword dict query qualifiers
:rtype: :class:`PaginatedList` of :class:`github.ContentFile.ContentFile`
"""
assert isinstance(query, str), query
url_parameters = dict()
if sort is not NotSet: # pragma no branch (Should be covered)
assert sort in ("indexed",), sort
url_parameters["sort"] = sort
if order is not NotSet: # pragma no branch (Should be covered)
assert order in ("asc", "desc"), order
url_parameters["order"] = order
query_chunks = []
if query: # pragma no branch (Should be covered)
query_chunks.append(query)
for qualifier, value in qualifiers.items():
query_chunks.append(f"{qualifier}:{value}")
url_parameters["q"] = " ".join(query_chunks)
assert url_parameters["q"], "need at least one qualifier"
headers = {"Accept": Consts.highLightSearchPreview} if highlight else None
return PaginatedList(
github.ContentFile.ContentFile,
self.__requester,
"/search/code",
url_parameters,
headers=headers,
)
def search_commits(
self,
query: str,
sort: Opt[str] = NotSet,
order: Opt[str] = NotSet,
**qualifiers: Any,
) -> PaginatedList[Commit]:
"""
:calls: `GET /search/commits <https://docs.github.com/en/rest/reference/search>`_
:param query: string
:param sort: string ('author-date', 'committer-date')
:param order: string ('asc', 'desc')
:param qualifiers: keyword dict query qualifiers
:rtype: :class:`PaginatedList` of :class:`github.Commit.Commit`
"""
assert isinstance(query, str), query
url_parameters = dict()
if sort is not NotSet:
assert sort in ("author-date", "committer-date"), sort
url_parameters["sort"] = sort
if order is not NotSet:
assert order in ("asc", "desc"), order
url_parameters["order"] = order
query_chunks = []
if query:
query_chunks.append(query)
for qualifier, value in qualifiers.items():
query_chunks.append(f"{qualifier}:{value}")
url_parameters["q"] = " ".join(query_chunks)
assert url_parameters["q"], "need at least one qualifier"
return PaginatedList(
github.Commit.Commit,
self.__requester,
"/search/commits",
url_parameters,
headers={"Accept": Consts.mediaTypeCommitSearchPreview},
)
def search_topics(self, query: str, **qualifiers: Any) -> PaginatedList[Topic]:
"""
:calls: `GET /search/topics <https://docs.github.com/en/rest/reference/search>`_
:param query: string
:param qualifiers: keyword dict query qualifiers
:rtype: :class:`PaginatedList` of :class:`github.Topic.Topic`
"""
assert isinstance(query, str), query
url_parameters = dict()
query_chunks = []
if query: # pragma no branch (Should be covered)
query_chunks.append(query)
for qualifier, value in qualifiers.items():
query_chunks.append(f"{qualifier}:{value}")
url_parameters["q"] = " ".join(query_chunks)
assert url_parameters["q"], "need at least one qualifier"
return PaginatedList(
github.Topic.Topic,
self.__requester,
"/search/topics",
url_parameters,
headers={"Accept": Consts.mediaTypeTopicsPreview},
)
def render_markdown(self, text: str, context: Opt[Repository] = NotSet) -> str:
"""
:calls: `POST /markdown <https://docs.github.com/en/rest/reference/markdown>`_
:param text: string
:param context: :class:`github.Repository.Repository`
:rtype: string
"""
assert isinstance(text, str), text
assert context is NotSet or isinstance(context, github.Repository.Repository), context
post_parameters = {"text": text}
if is_defined(context):
post_parameters["mode"] = "gfm"
post_parameters["context"] = context._identity
status, headers, data = self.__requester.requestJson("POST", "/markdown", input=post_parameters)
return data
def get_hook(self, name: str) -> HookDescription:
"""
:calls: `GET /hooks/{name} <https://docs.github.com/en/rest/reference/repos#webhooks>`_
"""
assert isinstance(name, str), name
name = urllib.parse.quote(name)
headers, attributes = self.__requester.requestJsonAndCheck("GET", f"/hooks/{name}")
return HookDescription(self.__requester, headers, attributes, completed=True)
def get_hooks(self) -> list[HookDescription]:
"""
:calls: `GET /hooks <https://docs.github.com/en/rest/reference/repos#webhooks>`_
:rtype: list of :class:`github.HookDescription.HookDescription`
"""
headers, data = self.__requester.requestJsonAndCheck("GET", "/hooks")
return [HookDescription(self.__requester, headers, attributes, completed=True) for attributes in data]
def get_hook_delivery(self, hook_id: int, delivery_id: int) -> HookDelivery:
"""
:calls: `GET /hooks/{hook_id}/deliveries/{delivery_id} <https://docs.github.com/en/rest/reference/repos#webhooks>`_
:param hook_id: integer
:param delivery_id: integer
:rtype: :class:`HookDelivery`
"""
assert isinstance(hook_id, int), hook_id
assert isinstance(delivery_id, int), delivery_id
headers, attributes = self.__requester.requestJsonAndCheck("GET", f"/hooks/{hook_id}/deliveries/{delivery_id}")
return HookDelivery(self.__requester, headers, attributes, completed=True)
def get_hook_deliveries(self, hook_id: int) -> list[HookDeliverySummary]:
"""
:calls: `GET /hooks/{hook_id}/deliveries <https://docs.github.com/en/rest/reference/repos#webhooks>`_
:param hook_id: integer
:rtype: list of :class:`HookDeliverySummary`
"""
assert isinstance(hook_id, int), hook_id
headers, data = self.__requester.requestJsonAndCheck("GET", f"/hooks/{hook_id}/deliveries")
return [HookDeliverySummary(self.__requester, headers, attributes, completed=True) for attributes in data]
def get_gitignore_templates(self) -> list[str]:
"""
:calls: `GET /gitignore/templates <https://docs.github.com/en/rest/reference/gitignore>`_
"""
headers, data = self.__requester.requestJsonAndCheck("GET", "/gitignore/templates")
return data
def get_gitignore_template(self, name: str) -> GitignoreTemplate:
"""
:calls: `GET /gitignore/templates/{name} <https://docs.github.com/en/rest/reference/gitignore>`_
"""
assert isinstance(name, str), name
name = urllib.parse.quote(name)
headers, attributes = self.__requester.requestJsonAndCheck("GET", f"/gitignore/templates/{name}")
return github.GitignoreTemplate.GitignoreTemplate(self.__requester, headers, attributes, completed=True)
def get_emojis(self) -> dict[str, str]:
"""
:calls: `GET /emojis <https://docs.github.com/en/rest/reference/emojis>`_
:rtype: dictionary of type => url for emoji`
"""
headers, attributes = self.__requester.requestJsonAndCheck("GET", "/emojis")
return attributes
def create_from_raw_data(
self, klass: type[TGithubObject], raw_data: dict[str, Any], headers: dict[str, str | int] | None = None
) -> TGithubObject:
"""
Creates an object from raw_data previously obtained by :attr:`GithubObject.raw_data`, and optionally headers
previously obtained by :attr:`GithubObject.raw_headers`.
:param klass: the class of the object to create
:param raw_data: dict
:param headers: dict
:rtype: instance of class ``klass``
"""
if headers is None:
headers = {}
return klass(self.__requester, headers, raw_data, completed=True)
def dump(self, obj: GithubObject, file: BinaryIO, protocol: int = 0) -> None:
"""
Dumps (pickles) a PyGithub object to a file-like object. Some effort is made to not pickle sensitive
information like the Github credentials used in the :class:`Github` instance. But NO EFFORT is made to remove
sensitive information from the object's attributes.
:param obj: the object to pickle :param file: the file-like object to pickle to :param protocol: the
`pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-stream-format>`_
:param obj: the object to pickle :param file: the file-like object to pickle to :param protocol: the
`pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
:param obj: the object to pickle :param file: the file-like object to pickle to :param protocol: the
`pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
stream-format>`_ :param obj: the object to pickle :param file: the file-like object to pickle to :param
protocol: the
`pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
:param obj: the object to pickle
:param file: the file-like object to pickle to
:param protocol: the `pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
stream-format>`_
:param obj: the object to pickle
:param file: the file-like object to pickle to
:param protocol: the `pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
:param obj: the object to pickle
:param file: the file-like object to pickle to
:param protocol: the `pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
stream-format>`_
:param obj: the object to pickle
:param file: the file-like object to pickle to
:param protocol: the `pickling protocol <https://python.readthedocs.io/en/latest/library/pickle.html#data-
stream-format>`_
"""
pickle.dump((obj.__class__, obj.raw_data, obj.raw_headers), file, protocol)
def load(self, f: BinaryIO) -> Any:
"""
Loads (unpickles) a PyGithub object from a file-like object.
:param f: the file-like object to unpickle from
:return: the unpickled object
"""
return self.create_from_raw_data(*pickle.load(f))
def get_oauth_application(self, client_id: str, client_secret: str) -> ApplicationOAuth:
return github.ApplicationOAuth.ApplicationOAuth(
self.__requester,
headers={},
attributes={"client_id": client_id, "client_secret": client_secret},
completed=False,
)
def get_app(self, slug: Opt[str] = NotSet) -> GithubApp:
"""
:calls: `GET /apps/{slug} <https://docs.github.com/en/rest/reference/apps>`_ or `GET /app <https://docs.github.com/en/rest/reference/apps>`_
"""
if slug is NotSet:
# with no slug given, calling /app returns the authenticated app,
# including the actual /apps/{slug}
warnings.warn(
"Argument slug is mandatory, calling this method without the slug argument is deprecated, please use "
"github.GithubIntegration(auth=github.Auth.AppAuth(...)).get_app() instead",
category=DeprecationWarning,
)
return GithubIntegration(**self.__requester.kwargs).get_app()
else:
assert isinstance(slug, str), slug
# with a slug given, we can lazily load the GithubApp
slug = urllib.parse.quote(slug)
return github.GithubApp.GithubApp(self.__requester, {}, {"url": f"/apps/{slug}"}, completed=False)
| 47,429
|
Python
|
.py
| 917
| 43.287895
| 173
| 0.618103
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,413
|
CodeScanAlertInstance.py
|
PyGithub_PyGithub/github/CodeScanAlertInstance.py
|
############################ Copyrights and license ############################
# #
# Copyright 2022 Eric Nieuwland <eric.nieuwland@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.CodeScanAlertInstanceLocation
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.CodeScanAlertInstanceLocation import CodeScanAlertInstanceLocation
class CodeScanAlertInstance(NonCompletableGithubObject):
"""
This class represents code scanning alert instances.
The reference can be found here
https://docs.github.com/en/rest/reference/code-scanning.
"""
def _initAttributes(self) -> None:
self._ref: Attribute[str] = NotSet
self._analysis_key: Attribute[str] = NotSet
self._environment: Attribute[str] = NotSet
self._state: Attribute[str] = NotSet
self._commit_sha: Attribute[str] = NotSet
self._message: Attribute[dict[str, Any]] = NotSet
self._location: Attribute[CodeScanAlertInstanceLocation] = NotSet
self._classifications: Attribute[list[str]] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"ref": self.ref, "analysis_key": self.analysis_key})
@property
def ref(self) -> str:
return self._ref.value
@property
def analysis_key(self) -> str:
return self._analysis_key.value
@property
def environment(self) -> str:
return self._environment.value
@property
def state(self) -> str:
return self._state.value
@property
def commit_sha(self) -> str:
return self._commit_sha.value
@property
def message(self) -> dict[str, Any]:
return self._message.value
@property
def location(self) -> CodeScanAlertInstanceLocation:
return self._location.value
@property
def classifications(self) -> list[str]:
return self._classifications.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "ref" in attributes: # pragma no branch
self._ref = self._makeStringAttribute(attributes["ref"])
if "analysis_key" in attributes: # pragma no branch
self._analysis_key = self._makeStringAttribute(attributes["analysis_key"])
if "environment" in attributes: # pragma no branch
self._environment = self._makeStringAttribute(attributes["environment"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "environment" in attributes: # pragma no branch
self._environment = self._makeStringAttribute(attributes["environment"])
if "commit_sha" in attributes: # pragma no branch
self._commit_sha = self._makeStringAttribute(attributes["commit_sha"])
if "message" in attributes: # pragma no branch
self._message = self._makeDictAttribute(attributes["message"])
if "location" in attributes: # pragma no branch
self._location = self._makeClassAttribute(
github.CodeScanAlertInstanceLocation.CodeScanAlertInstanceLocation,
attributes["location"],
)
if "classifications" in attributes: # pragma no branch
self._classifications = self._makeListOfStringsAttribute(attributes["classifications"])
| 5,382
|
Python
|
.py
| 95
| 50.610526
| 99
| 0.574791
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,414
|
Permissions.py
|
PyGithub_PyGithub/github/Permissions.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 karsten-wagner <39054096+karsten-wagner@users.noreply.github.com>#
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class Permissions(NonCompletableGithubObject):
"""
This class represents Permissions.
"""
def _initAttributes(self) -> None:
self._admin: Attribute[bool] = NotSet
self._maintain: Attribute[bool] = NotSet
self._pull: Attribute[bool] = NotSet
self._push: Attribute[bool] = NotSet
self._triage: Attribute[bool] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"admin": self._admin.value,
"maintain": self._maintain.value,
"pull": self._pull.value,
"push": self._push.value,
"triage": self._triage.value,
}
)
@property
def admin(self) -> bool:
return self._admin.value
@property
def maintain(self) -> bool:
return self._maintain.value
@property
def pull(self) -> bool:
return self._pull.value
@property
def push(self) -> bool:
return self._push.value
@property
def triage(self) -> bool:
return self._triage.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "admin" in attributes: # pragma no branch
self._admin = self._makeBoolAttribute(attributes["admin"])
if "maintain" in attributes: # pragma no branch
self._maintain = self._makeBoolAttribute(attributes["maintain"])
if "pull" in attributes: # pragma no branch
self._pull = self._makeBoolAttribute(attributes["pull"])
if "push" in attributes: # pragma no branch
self._push = self._makeBoolAttribute(attributes["push"])
if "triage" in attributes: # pragma no branch
self._triage = self._makeBoolAttribute(attributes["triage"])
| 4,899
|
Python
|
.py
| 85
| 52.211765
| 83
| 0.509788
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,415
|
CommitComment.py
|
PyGithub_PyGithub/github/CommitComment.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Nicolas Agustín Torres <nicolastrres@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 per1234 <accounts@perglass.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Huan-Cheng Chang <changhc84@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.GithubObject
import github.NamedUser
from github import Consts
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.Reaction import Reaction
class CommitComment(CompletableGithubObject):
"""
This class represents CommitComments.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#comments
"""
def _initAttributes(self) -> None:
self._body: Attribute[str] = NotSet
self._commit_id: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._line: Attribute[int] = NotSet
self._path: Attribute[str] = NotSet
self._position: Attribute[int] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._user: Attribute[github.NamedUser.NamedUser] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "user": self.user})
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def commit_id(self) -> str:
self._completeIfNotSet(self._commit_id)
return self._commit_id.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def line(self) -> int:
self._completeIfNotSet(self._line)
return self._line.value
@property
def path(self) -> str:
self._completeIfNotSet(self._path)
return self._path.value
@property
def position(self) -> int:
self._completeIfNotSet(self._position)
return self._position.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def user(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/comments/{id} <https://docs.github.com/en/rest/reference/repos#comments>`_
:rtype: None
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(self, body: str) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/comments/{id} <https://docs.github.com/en/rest/reference/repos#comments>`_
"""
assert isinstance(body, str), body
post_parameters = {
"body": body,
}
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def get_reactions(self) -> PaginatedList[Reaction]:
"""
:calls: `GET /repos/{owner}/{repo}/comments/{id}/reactions
<https://docs.github.com/en/rest/reference/reactions#list-reactions-for-a-commit-comment>`_
:return: :class: :class:`github.PaginatedList.PaginatedList` of :class:`github.Reaction.Reaction`
"""
return PaginatedList(
github.Reaction.Reaction,
self._requester,
f"{self.url}/reactions",
None,
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
def create_reaction(self, reaction_type: str) -> Reaction:
"""
:calls: `POST /repos/{owner}/{repo}/comments/{id}/reactions
<https://docs.github.com/en/rest/reference/reactions#create-reaction-for-a-commit-comment>`_
"""
assert isinstance(reaction_type, str), reaction_type
post_parameters = {
"content": reaction_type,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/reactions",
input=post_parameters,
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)
def delete_reaction(self, reaction_id: int) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}
<https://docs.github.com/en/rest/reference/reactions#delete-a-commit-comment-reaction>`_
:param reaction_id: integer
:rtype: bool
"""
assert isinstance(reaction_id, int), reaction_id
status, _, _ = self._requester.requestJson(
"DELETE",
f"{self.url}/reactions/{reaction_id}",
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
return status == 204
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "body" in attributes: # pragma no branch
self._body = self._makeStringAttribute(attributes["body"])
if "commit_id" in attributes: # pragma no branch
self._commit_id = self._makeStringAttribute(attributes["commit_id"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "line" in attributes: # pragma no branch
self._line = self._makeIntAttribute(attributes["line"])
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(attributes["path"])
if "position" in attributes: # pragma no branch
self._position = self._makeIntAttribute(attributes["position"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 10,200
|
Python
|
.py
| 198
| 44.580808
| 120
| 0.577143
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,416
|
InputGitTreeElement.py
|
PyGithub_PyGithub/github/InputGitTreeElement.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
from github.GithubObject import NotSet, Opt, is_defined, is_optional
class InputGitTreeElement:
"""
This class represents InputGitTreeElements.
"""
def __init__(
self,
path: str,
mode: str,
type: str,
content: Opt[str] = NotSet,
sha: Opt[str | None] = NotSet,
):
assert isinstance(path, str), path
assert isinstance(mode, str), mode
assert isinstance(type, str), type
assert is_optional(content, str), content
assert sha is None or is_optional(sha, str), sha
self.__path = path
self.__mode = mode
self.__type = type
self.__content = content
self.__sha: Opt[str] | None = sha
@property
def _identity(self) -> dict[str, Any]:
identity: dict[str, Any] = {
"path": self.__path,
"mode": self.__mode,
"type": self.__type,
}
if is_defined(self.__sha):
identity["sha"] = self.__sha
if is_defined(self.__content):
identity["content"] = self.__content
return identity
| 3,933
|
Python
|
.py
| 71
| 50.690141
| 80
| 0.474708
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,417
|
CheckRunAnnotation.py
|
PyGithub_PyGithub/github/CheckRunAnnotation.py
|
############################ Copyrights and license ############################
# #
# Copyright 2020 Dhruv Manilawala <dhruvmanila@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class CheckRunAnnotation(NonCompletableGithubObject):
"""
This class represents check run annotations.
The reference can be found here: https://docs.github.com/en/rest/reference/checks#list-check-run-annotations
"""
def _initAttributes(self) -> None:
self._annotation_level: Attribute[str] = NotSet
self._end_column: Attribute[int] = NotSet
self._end_line: Attribute[int] = NotSet
self._message: Attribute[str] = NotSet
self._path: Attribute[str] = NotSet
self._raw_details: Attribute[str] = NotSet
self._start_column: Attribute[int] = NotSet
self._start_line: Attribute[int] = NotSet
self._title: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"title": self._title.value})
@property
def annotation_level(self) -> str:
return self._annotation_level.value
@property
def end_column(self) -> int:
return self._end_column.value
@property
def end_line(self) -> int:
return self._end_line.value
@property
def message(self) -> str:
return self._message.value
@property
def path(self) -> str:
return self._path.value
@property
def raw_details(self) -> str:
return self._raw_details.value
@property
def start_column(self) -> int:
return self._start_column.value
@property
def start_line(self) -> int:
return self._start_line.value
@property
def title(self) -> str:
return self._title.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "annotation_level" in attributes: # pragma no branch
self._annotation_level = self._makeStringAttribute(attributes["annotation_level"])
if "end_column" in attributes: # pragma no branch
self._end_column = self._makeIntAttribute(attributes["end_column"])
if "end_line" in attributes: # pragma no branch
self._end_line = self._makeIntAttribute(attributes["end_line"])
if "message" in attributes: # pragma no branch
self._message = self._makeStringAttribute(attributes["message"])
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(attributes["path"])
if "raw_details" in attributes: # pragma no branch
self._raw_details = self._makeStringAttribute(attributes["raw_details"])
if "start_column" in attributes: # pragma no branch
self._start_column = self._makeIntAttribute(attributes["start_column"])
if "start_line" in attributes: # pragma no branch
self._start_line = self._makeIntAttribute(attributes["start_line"])
if "title" in attributes: # pragma no branch
self._title = self._makeStringAttribute(attributes["title"])
| 5,181
|
Python
|
.py
| 92
| 50.423913
| 112
| 0.555117
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,418
|
CVSS.py
|
PyGithub_PyGithub/github/CVSS.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2022 Eric Nieuwland <eric.nieuwland@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 decimal import Decimal
from typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class CVSS(NonCompletableGithubObject):
"""
This class represents a CVSS.
The reference can be found here
<https://docs.github.com/en/rest/security-advisories/global-advisories>
"""
def _initAttributes(self) -> None:
self._vector_string: Attribute[str] = NotSet
self._score: Attribute[Decimal] = NotSet
self._version: Attribute[Decimal] = NotSet
@property
def score(self) -> Decimal:
return self._score.value
@property
def version(self) -> Decimal:
return self._version.value
@property
def vector_string(self) -> str:
return self._vector_string.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "score" in attributes and attributes["score"] is not None: # pragma no branch
# ensure string so we don't have all the float extra nonsense
self._score = self._makeDecimalAttribute(Decimal(str(attributes["score"])))
if "vector_string" in attributes and attributes["vector_string"] is not None: # pragma no branch
self._vector_string = self._makeStringAttribute(attributes["vector_string"])
self._version = self._makeDecimalAttribute(Decimal(self.vector_string.split(":")[1].split("/")[0]))
| 4,577
|
Python
|
.py
| 68
| 63.735294
| 111
| 0.521343
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,419
|
EnvironmentDeploymentBranchPolicy.py
|
PyGithub_PyGithub/github/EnvironmentDeploymentBranchPolicy.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 alson <git@alm.nufan.net> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class EnvironmentDeploymentBranchPolicy(NonCompletableGithubObject):
"""
This class represents a deployment branch policy for an environment.
The reference can be found here
https://docs.github.com/en/rest/reference/deployments#environments
"""
def _initAttributes(self) -> None:
self._protected_branches: Attribute[bool] = NotSet
self._custom_branch_policies: Attribute[bool] = NotSet
def __repr__(self) -> str:
return self.get__repr__({})
@property
def protected_branches(self) -> bool:
return self._protected_branches.value
@property
def custom_branch_policies(self) -> bool:
return self._custom_branch_policies.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "protected_branches" in attributes: # pragma no branch
self._protected_branches = self._makeBoolAttribute(attributes["protected_branches"])
if "custom_branch_policies" in attributes: # pragma no branch
self._custom_branch_policies = self._makeBoolAttribute(attributes["custom_branch_policies"])
class EnvironmentDeploymentBranchPolicyParams:
"""
This class presents the deployment branch policy parameters as can be configured for an Environment.
"""
def __init__(self, protected_branches: bool = False, custom_branch_policies: bool = False):
assert isinstance(protected_branches, bool)
assert isinstance(custom_branch_policies, bool)
self.protected_branches = protected_branches
self.custom_branch_policies = custom_branch_policies
def _asdict(self) -> dict:
return {
"protected_branches": self.protected_branches,
"custom_branch_policies": self.custom_branch_policies,
}
| 4,009
|
Python
|
.py
| 64
| 57.96875
| 104
| 0.548601
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,420
|
GithubApp.py
|
PyGithub_PyGithub/github/GithubApp.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Matt Babineau <mbabineau@dataxu.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Martijn Koster <mak-github@greenhills.co.uk> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Colby Gallup <colbygallup@gmail.com> #
# Copyright 2020 Mahesh Raju <coder@mahesh.net> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.GithubObject
import github.NamedUser
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class GithubApp(CompletableGithubObject):
"""
This class represents github apps.
The reference can be found here
https://docs.github.com/en/rest/reference/apps
"""
def _initAttributes(self) -> None:
self._created_at: Attribute[datetime] = NotSet
self._description: Attribute[str] = NotSet
self._events: Attribute[list[str]] = NotSet
self._external_url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._name: Attribute[str] = NotSet
self._owner: Attribute[github.NamedUser.NamedUser] = NotSet
self._permissions: Attribute[dict[str, str]] = NotSet
self._slug: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "url": self._url.value})
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def description(self) -> str:
self._completeIfNotSet(self._description)
return self._description.value
@property
def events(self) -> list[str]:
self._completeIfNotSet(self._events)
return self._events.value
@property
def external_url(self) -> str:
self._completeIfNotSet(self._external_url)
return self._external_url.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def owner(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._owner)
return self._owner.value
@property
def permissions(self) -> dict[str, str]:
self._completeIfNotSet(self._permissions)
return self._permissions.value
@property
def slug(self) -> str:
self._completeIfNotSet(self._slug)
return self._slug.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
return self._url.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "events" in attributes: # pragma no branch
self._events = self._makeListOfStringsAttribute(attributes["events"])
if "external_url" in attributes: # pragma no branch
self._external_url = self._makeStringAttribute(attributes["external_url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "owner" in attributes: # pragma no branch
self._owner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["owner"])
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeDictAttribute(attributes["permissions"])
if "slug" in attributes: # pragma no branch
self._slug = self._makeStringAttribute(attributes["slug"])
self._url = self._makeStringAttribute(f"/apps/{attributes['slug']}")
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes:
self._url = self._makeStringAttribute(attributes["url"])
| 7,864
|
Python
|
.py
| 142
| 49.521127
| 99
| 0.570519
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,421
|
HookResponse.py
|
PyGithub_PyGithub/github/HookResponse.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class HookResponse(NonCompletableGithubObject):
"""
This class represents HookResponses.
"""
def _initAttributes(self) -> None:
self._code: Attribute[int] = NotSet
self._message: Attribute[str] = NotSet
self._status: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"status": self._status.value})
@property
def code(self) -> int:
return self._code.value
@property
def message(self) -> str:
return self._message.value
@property
def status(self) -> str:
return self._status.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "code" in attributes: # pragma no branch
self._code = self._makeIntAttribute(attributes["code"])
if "message" in attributes: # pragma no branch
self._message = self._makeStringAttribute(attributes["message"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
| 4,088
|
Python
|
.py
| 64
| 60.15625
| 80
| 0.498754
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,422
|
NotificationSubject.py
|
PyGithub_PyGithub/github/NotificationSubject.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class NotificationSubject(NonCompletableGithubObject):
"""
This class represents Subjects of Notifications.
The reference can be found here
https://docs.github.com/en/rest/reference/activity#list-notifications-for-the-authenticated-user
"""
def _initAttributes(self) -> None:
self._title: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
self._latest_comment_url: Attribute[str] = NotSet
self._type: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"title": self._title.value})
@property
def title(self) -> str:
return self._title.value
@property
def url(self) -> str:
return self._url.value
@property
def latest_comment_url(self) -> str:
return self._latest_comment_url.value
@property
def type(self) -> str:
return self._type.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "title" in attributes: # pragma no branch
self._title = self._makeStringAttribute(attributes["title"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "latest_comment_url" in attributes: # pragma no branch
self._latest_comment_url = self._makeStringAttribute(attributes["latest_comment_url"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
| 4,787
|
Python
|
.py
| 75
| 59.76
| 100
| 0.523627
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,423
|
Repository.py
|
PyGithub_PyGithub/github/Repository.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Christopher Gilbert <christopher.john.gilbert@gmail.com> #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Adrian Petrescu <adrian.petrescu@maluuba.com> #
# Copyright 2013 Cameron White <cawhite@pdx.edu> #
# Copyright 2013 David Farr <david.farr@sap.com> #
# Copyright 2013 Mark Roddy <markroddy@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Aaron Levine <allevin@sandia.gov> #
# Copyright 2015 Christopher Wilcox <git@crwilcox.com> #
# Copyright 2015 Dan Vanderkam <danvdk@gmail.com> #
# Copyright 2015 Ed Holland <eholland@alertlogic.com> #
# Copyright 2015 Enix Yu <enix223@163.com> #
# Copyright 2015 Jay <ja.geb@me.com> #
# Copyright 2015 Jonathan Debonis <jon@ip-172-20-10-5.ec2.internal> #
# Copyright 2015 Kevin Lewandowski <kevinsl@gmail.com> #
# Copyright 2015 Kyle Hornberg <khornberg@users.noreply.github.com> #
# Copyright 2016 @tmshn <tmshn@r.recruit.co.jp> #
# Copyright 2016 Dustin Spicuzza <dustin@virtualroadside.com> #
# Copyright 2016 Enix Yu <enix223@163.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Per Øyvind Karlsen <proyvind@moondrake.org> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 Sylvus <Sylvus@users.noreply.github.com> #
# Copyright 2016 fukatani <nannyakannya@gmail.com> #
# Copyright 2016 ghfan <gavintofan@gmail.com> #
# Copyright 2017 Andreas Lutro <anlutro@gmail.com> #
# Copyright 2017 Ben Firshman <ben@firshman.co.uk> #
# Copyright 2017 Chris McBride <thehighlander@users.noreply.github.com> #
# Copyright 2017 Hugo <hugovk@users.noreply.github.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2017 Jason White <jasonwhite@users.noreply.github.com> #
# Copyright 2017 Jimmy Zelinskie <jimmy.zelinskie+git@gmail.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Aaron L. Levine <allevin@sandia.gov> #
# Copyright 2018 AetherDeity <aetherdeity+github@gmail.com> #
# Copyright 2018 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2018 Andrew Smith <espadav8@gmail.com> #
# Copyright 2018 Benoit Latinier <benoit@latinier.fr> #
# Copyright 2018 Brian Torres-Gil <btorres-gil@paloaltonetworks.com> #
# Copyright 2018 Hayden Fuss <wifu1234@gmail.com> #
# Copyright 2018 Ilya Konstantinov <ilya.konstantinov@gmail.com> #
# Copyright 2018 Jacopo Notarstefano <jacopo.notarstefano@gmail.com> #
# Copyright 2018 John Hui <j-hui@users.noreply.github.com> #
# Copyright 2018 Justin Kufro <jkufro@andrew.cmu.edu> #
# Copyright 2018 Mateusz Loskot <mateusz@loskot.net> #
# Copyright 2018 Michael Behrisch <oss@behrisch.de> #
# Copyright 2018 Nicholas Buse <NicholasBuse@users.noreply.github.com> #
# Copyright 2018 Philip May <eniak.info@gmail.com> #
# Copyright 2018 Raihaan <31362124+res0nance@users.noreply.github.com> #
# Copyright 2018 Shinichi TAMURA <shnch.tmr@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Vinay Hegde <hegde.vi@husky.neu.edu> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 Will Yardley <wyardley@users.noreply.github.com> #
# Copyright 2018 Yossarian King <yggy@blackbirdinteractive.com> #
# Copyright 2018 per1234 <accounts@perglass.com> #
# Copyright 2018 sechastain <sechastain@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Alex <alexmusa@users.noreply.github.com> #
# Copyright 2019 Kevin LaFlamme <k@lamfl.am> #
# Copyright 2019 Olof-Joachim Frahm (欧雅福) <olof@macrolet.net> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Tim Gates <tim.gates@iress.com> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2019 Will Li <cuichen.li94@gmail.com> #
# Copyright 2020 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2020 Anuj Bansal <bansalanuj1996@gmail.com> #
# Copyright 2020 Chris de Graaf <chrisadegraaf@gmail.com> #
# Copyright 2020 Dhruv Manilawala <dhruvmanila@gmail.com> #
# Copyright 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> #
# Copyright 2020 Florent Clarret <florent.clarret@gmail.com> #
# Copyright 2020 Glenn McDonald <testworksau@users.noreply.github.com> #
# Copyright 2020 Huw Jones <huwcbjones@outlook.com> #
# Copyright 2020 Mark Bromell <markbromell.business@gmail.com> #
# Copyright 2020 Max Wittig <max.wittig@siemens.com> #
# Copyright 2020 Pascal Hofmann <mail@pascalhofmann.de> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Tim Gates <tim.gates@iress.com> #
# Copyright 2020 Victor Zeng <zacker150@users.noreply.github.com> #
# Copyright 2020 ton-katsu <sakamoto.yoshihisa@gmail.com> #
# Copyright 2021 Chris Keating <christopherkeating@gmail.com> #
# Copyright 2021 Floyd Hightower <floyd.hightower27@gmail.com> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Tanner <51724788+lightningboltemoji@users.noreply.github.com> #
# Copyright 2021 xmo-odoo <xmo@odoo.com> #
# Copyright 2022 Aleksei Fedotov <lexa@cfotr.com> #
# Copyright 2022 Eric Nieuwland <eric.nieuwland@gmail.com> #
# Copyright 2022 Ibrahim Hussaini <ibrahimhussainialias@outlook.com> #
# Copyright 2022 KimSia Sim <245021+simkimsia@users.noreply.github.com> #
# Copyright 2022 Marco Köpcke <hello@parakoopa.de> #
# Copyright 2023 Andrew Collington <andy@amnuts.com> #
# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> #
# Copyright 2023 Armen Martirosyan <armartirosyan@gmail.com> #
# Copyright 2023 BradChengIRESS <49461141+BradChengIRESS@users.noreply.github.com>#
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Felipe Peter <mr-peipei@web.de> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Kevin Grandjean <Muscaw@users.noreply.github.com> #
# Copyright 2023 Mark Amery <markamery@btinternet.com> #
# Copyright 2023 Mauricio Alejandro Martínez Pacheco <mauricio.martinez@premise.com>#
# Copyright 2023 Mauricio Alejandro Martínez Pacheco <n_othing@hotmail.com> #
# Copyright 2023 Max Mehl <6170081+mxmehl@users.noreply.github.com> #
# Copyright 2023 Micael <10292135+notmicaelfilipe@users.noreply.github.com> #
# Copyright 2023 Mikhail f. Shiryaev <mr.felixoid@gmail.com> #
# Copyright 2023 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com>#
# Copyright 2023 Philipp A <flying-sheep@web.de> #
# Copyright 2023 Roberto Pastor Muela <37798125+RobPasMue@users.noreply.github.com>#
# Copyright 2023 Sol Redfern <59831933+Tsuesun@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 Wojciech Barczyński <104033489+WojciechBarczynski@users.noreply.github.com>#
# Copyright 2023 alson <git@alm.nufan.net> #
# Copyright 2023 chantra <chantra@users.noreply.github.com> #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Caleb McCombs <caleb@mccombalot.net> #
# Copyright 2024 Chris Wells <ping@cwlls.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Heitor Polidoro <heitor.polidoro@gmail.com> #
# Copyright 2024 Heitor de Bittencourt <heitorpbittencourt@gmail.com> #
# Copyright 2024 Jacky Lam <jacky.lam@r2studiohk.com> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# Copyright 2024 Thomas Crowley <15927917+thomascrowley@users.noreply.github.com>#
# Copyright 2024 jodelasur <34933233+jodelasur@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import collections
import urllib.parse
from base64 import b64encode
from collections.abc import Iterable
from datetime import date, datetime, timezone
from typing import TYPE_CHECKING, Any
from deprecated import deprecated
import github.AdvisoryCredit
import github.AdvisoryVulnerability
import github.Artifact
import github.AuthenticatedUser
import github.Autolink
import github.Branch
import github.CheckRun
import github.CheckSuite
import github.Clones
import github.CodeScanAlert
import github.Commit
import github.CommitComment
import github.Comparison
import github.ContentFile
import github.DependabotAlert
import github.Deployment
import github.Download
import github.Environment
import github.EnvironmentDeploymentBranchPolicy
import github.EnvironmentProtectionRule
import github.EnvironmentProtectionRuleReviewer
import github.Event
import github.GitBlob
import github.GitCommit
import github.GithubObject
import github.GitRef
import github.GitRelease
import github.GitReleaseAsset
import github.GitTag
import github.GitTree
import github.Hook
import github.HookDelivery
import github.Invitation
import github.Issue
import github.IssueComment
import github.IssueEvent
import github.Label
import github.License
import github.Milestone
import github.NamedUser
import github.Notification
import github.Organization
import github.PaginatedList
import github.Path
import github.Permissions
import github.Project
import github.PublicKey
import github.PullRequest
import github.PullRequestComment
import github.Referrer
import github.RepositoryAdvisory
import github.RepositoryKey
import github.RepositoryPreferences
import github.Secret
import github.SecurityAndAnalysis
import github.SelfHostedActionsRunner
import github.SourceImport
import github.Stargazer
import github.StatsCodeFrequency
import github.StatsCommitActivity
import github.StatsContributor
import github.StatsParticipation
import github.StatsPunchCard
import github.Tag
import github.Team
import github.Variable
import github.View
import github.Workflow
import github.WorkflowRun
from github import Consts
from github.Environment import Environment
from github.GithubObject import (
Attribute,
CompletableGithubObject,
NotSet,
Opt,
_NotSetType,
is_defined,
is_optional,
is_optional_list,
is_undefined,
)
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
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
from github.Clones import Clones
from github.CodeScanAlert import CodeScanAlert
from github.Commit import Commit
from github.CommitComment import CommitComment
from github.Comparison import Comparison
from github.ContentFile import ContentFile
from github.DependabotAlert import DependabotAlert
from github.Deployment import Deployment
from github.Download import Download
from github.EnvironmentDeploymentBranchPolicy import EnvironmentDeploymentBranchPolicyParams
from github.EnvironmentProtectionRuleReviewer import ReviewerParams
from github.Event import Event
from github.GitBlob import GitBlob
from github.GitCommit import GitCommit
from github.GitRef import GitRef
from github.GitRelease import GitRelease
from github.GitReleaseAsset import GitReleaseAsset
from github.GitTag import GitTag
from github.GitTree import GitTree
from github.Hook import Hook
from github.InputGitAuthor import InputGitAuthor
from github.InputGitTreeElement import InputGitTreeElement
from github.Invitation import Invitation
from github.Issue import Issue
from github.IssueComment import IssueComment
from github.IssueEvent import IssueEvent
from github.Label import Label
from github.License import License
from github.Milestone import Milestone
from github.NamedUser import NamedUser
from github.Notification import Notification
from github.Organization import Organization
from github.Path import Path
from github.Permissions import Permissions
from github.Project import Project
from github.PublicKey import PublicKey
from github.PullRequest import PullRequest
from github.PullRequestComment import PullRequestComment
from github.Referrer import Referrer
from github.RepositoryKey import RepositoryKey
from github.RepositoryPreferences import RepositoryPreferences
from github.SecurityAndAnalysis import SecurityAndAnalysis
from github.SelfHostedActionsRunner import SelfHostedActionsRunner
from github.SourceImport import SourceImport
from github.Stargazer import Stargazer
from github.StatsCodeFrequency import StatsCodeFrequency
from github.StatsCommitActivity import StatsCommitActivity
from github.StatsContributor import StatsContributor
from github.StatsParticipation import StatsParticipation
from github.StatsPunchCard import StatsPunchCard
from github.Tag import Tag
from github.Team import Team
from github.View import View
from github.Workflow import Workflow
from github.WorkflowRun import WorkflowRun
class Repository(CompletableGithubObject):
"""
This class represents Repositories.
The reference can be found here
https://docs.github.com/en/rest/reference/repos
"""
def __repr__(self) -> str:
return self.get__repr__({"full_name": self._full_name.value})
@property
def allow_auto_merge(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._allow_auto_merge)
return self._allow_auto_merge.value
@property
def allow_forking(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._allow_forking)
return self._allow_forking.value
@property
def allow_merge_commit(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._allow_merge_commit)
return self._allow_merge_commit.value
@property
def allow_rebase_merge(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._allow_rebase_merge)
return self._allow_rebase_merge.value
@property
def allow_squash_merge(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._allow_squash_merge)
return self._allow_squash_merge.value
@property
def allow_update_branch(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._allow_update_branch)
return self._allow_update_branch.value
@property
def archived(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._archived)
return self._archived.value
@property
def archive_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._archive_url)
return self._archive_url.value
@property
def assignees_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._assignees_url)
return self._assignees_url.value
@property
def blobs_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._blobs_url)
return self._blobs_url.value
@property
def branches_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._branches_url)
return self._branches_url.value
@property
def clone_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._clone_url)
return self._clone_url.value
@property
def collaborators_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._collaborators_url)
return self._collaborators_url.value
@property
def comments_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._comments_url)
return self._comments_url.value
@property
def commits_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._commits_url)
return self._commits_url.value
@property
def compare_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._compare_url)
return self._compare_url.value
@property
def contents_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._contents_url)
return self._contents_url.value
@property
def contributors_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._contributors_url)
return self._contributors_url.value
@property
def created_at(self) -> datetime:
"""
:type: datetime
"""
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def custom_properties(self) -> dict[str, None | str | list]:
"""
:type: dict[str, None | str | list]
"""
self._completeIfNotSet(self._custom_properties)
return self._custom_properties.value
@property
def default_branch(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._default_branch)
return self._default_branch.value
@property
def delete_branch_on_merge(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._delete_branch_on_merge)
return self._delete_branch_on_merge.value
@property
def deployments_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._deployments_url)
return self._deployments_url.value
@property
def description(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._description)
return self._description.value
@property
def downloads_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._downloads_url)
return self._downloads_url.value
@property
def events_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._events_url)
return self._events_url.value
@property
def fork(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._fork)
return self._fork.value
@property
def forks(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._forks)
return self._forks.value
@property
def forks_count(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._forks_count)
return self._forks_count.value
@property
def forks_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._forks_url)
return self._forks_url.value
@property
def full_name(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._full_name)
return self._full_name.value
@property
def git_commits_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._git_commits_url)
return self._git_commits_url.value
@property
def git_refs_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._git_refs_url)
return self._git_refs_url.value
@property
def git_tags_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._git_tags_url)
return self._git_tags_url.value
@property
def git_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._git_url)
return self._git_url.value
@property
def has_downloads(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._has_downloads)
return self._has_downloads.value
@property
def has_issues(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._has_issues)
return self._has_issues.value
@property
def has_pages(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._has_pages)
return self._has_pages.value
@property
def has_projects(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._has_projects)
return self._has_projects.value
@property
def has_wiki(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._has_wiki)
return self._has_wiki.value
@property
def has_discussions(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._has_discussions)
return self._has_discussions.value
@property
def homepage(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._homepage)
return self._homepage.value
@property
def hooks_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._hooks_url)
return self._hooks_url.value
@property
def html_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._id)
return self._id.value
@property
def is_template(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._is_template)
return self._is_template.value
@property
def issue_comment_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._issue_comment_url)
return self._issue_comment_url.value
@property
def issue_events_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._issue_events_url)
return self._issue_events_url.value
@property
def issues_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._issues_url)
return self._issues_url.value
@property
def keys_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._keys_url)
return self._keys_url.value
@property
def labels_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._labels_url)
return self._labels_url.value
@property
def language(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._language)
return self._language.value
@property
def languages_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._languages_url)
return self._languages_url.value
@property
def license(self) -> License:
self._completeIfNotSet(self._license)
return self._license.value
@property
def master_branch(self) -> str:
self._completeIfNotSet(self._master_branch)
return self._master_branch.value
@property
def merge_commit_message(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._merge_commit_message)
return self._merge_commit_message.value
@property
def merge_commit_title(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._merge_commit_title)
return self._merge_commit_title.value
@property
def merges_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._merges_url)
return self._merges_url.value
@property
def milestones_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._milestones_url)
return self._milestones_url.value
@property
def mirror_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._mirror_url)
return self._mirror_url.value
@property
def name(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._name)
return self._name.value
@property
def network_count(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._network_count)
return self._network_count.value
@property
def notifications_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._notifications_url)
return self._notifications_url.value
@property
def open_issues(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._open_issues)
return self._open_issues.value
@property
def open_issues_count(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._open_issues_count)
return self._open_issues_count.value
@property
def organization(self) -> Organization:
"""
:type: :class:`github.Organization.Organization`
"""
self._completeIfNotSet(self._organization)
return self._organization.value
@property
def owner(self) -> NamedUser:
"""
:type: :class:`github.NamedUser.NamedUser`
"""
self._completeIfNotSet(self._owner)
return self._owner.value
@property
def parent(self) -> Repository:
"""
:type: :class:`github.Repository.Repository`
"""
self._completeIfNotSet(self._parent)
return self._parent.value
@property
def permissions(self) -> Permissions:
"""
:type: :class:`github.Permissions.Permissions`
"""
self._completeIfNotSet(self._permissions)
return self._permissions.value
@property
def private(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._private)
return self._private.value
@property
def pulls_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._pulls_url)
return self._pulls_url.value
@property
def pushed_at(self) -> datetime:
"""
:type: datetime
"""
self._completeIfNotSet(self._pushed_at)
return self._pushed_at.value
@property
def releases_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._releases_url)
return self._releases_url.value
@property
def security_and_analysis(self) -> SecurityAndAnalysis:
"""
:type: :class:`github.SecurityAndAnalysis.SecurityAndAnalysis`
"""
self._completeIfNotSet(self._security_and_analysis)
return self._security_and_analysis.value
@property
def size(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._size)
return self._size.value
@property
def source(self) -> Repository | None:
"""
:type: :class:`github.Repository.Repository`
"""
self._completeIfNotSet(self._source)
return self._source.value
@property
def squash_merge_commit_message(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._squash_merge_commit_message)
return self._squash_merge_commit_message.value
@property
def squash_merge_commit_title(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._squash_merge_commit_title)
return self._squash_merge_commit_title.value
@property
def ssh_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._ssh_url)
return self._ssh_url.value
@property
def stargazers_count(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._stargazers_count) # pragma no cover (Should be covered)
return self._stargazers_count.value # pragma no cover (Should be covered)
@property
def stargazers_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._stargazers_url)
return self._stargazers_url.value
@property
def statuses_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._statuses_url)
return self._statuses_url.value
@property
def subscribers_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._subscribers_url)
return self._subscribers_url.value
@property
def subscribers_count(self) -> int:
"""
:type: integer
"""
self._completeIfNotSet(self._subscribers_count)
return self._subscribers_count.value
@property
def subscription_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._subscription_url)
return self._subscription_url.value
@property
def svn_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._svn_url)
return self._svn_url.value
@property
def tags_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._tags_url)
return self._tags_url.value
@property
def teams_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._teams_url)
return self._teams_url.value
@property
def topics(self) -> list[str]:
"""
:type: list of strings
"""
self._completeIfNotSet(self._topics)
return self._topics.value
@property
def trees_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._trees_url)
return self._trees_url.value
@property
def updated_at(self) -> datetime:
"""
:type: datetime
"""
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def use_squash_pr_title_as_default(self) -> bool:
self._completeIfNotSet(self._use_squash_pr_title_as_default)
return self._use_squash_pr_title_as_default.value
@property
def visibility(self) -> str:
self._completeIfNotSet(self._visibility)
return self._visibility.value
@property
def watchers(self) -> int:
self._completeIfNotSet(self._watchers)
return self._watchers.value
@property
def watchers_count(self) -> int:
self._completeIfNotSet(self._watchers_count)
return self._watchers_count.value
@property
def web_commit_signoff_required(self) -> bool:
"""
:type: bool
"""
self._completeIfNotSet(self._web_commit_signoff_required)
return self._web_commit_signoff_required.value
def add_to_collaborators(self, collaborator: str | NamedUser, permission: Opt[str] = NotSet) -> Invitation | None:
"""
:calls: `PUT /repos/{owner}/{repo}/collaborators/{user} <https://docs.github.com/en/rest/collaborators/collaborators#add-a-repository-collaborator>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:param permission: string 'pull', 'push', 'admin', 'maintain', 'triage', or a custom repository role name, if the owning organization has defined any
:rtype: None
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator
assert is_optional(permission, str), permission
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
else:
collaborator = urllib.parse.quote(collaborator)
if is_defined(permission):
put_parameters = {"permission": permission}
else:
put_parameters = None
headers, data = self._requester.requestJsonAndCheck(
"PUT", f"{self.url}/collaborators/{collaborator}", input=put_parameters
)
# return an invitation object if there's data returned by the API. If data is empty
# there's a pending invitation for the given user.
return (
github.Invitation.Invitation(self._requester, headers, data, completed=True) if data is not None else None
)
def get_collaborator_permission(self, collaborator: str | NamedUser) -> str:
"""
:calls: `GET /repos/{owner}/{repo}/collaborators/{username}/permission <https://docs.github.com/en/rest/reference/repos#collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: string
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
else:
collaborator = urllib.parse.quote(collaborator)
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/collaborators/{collaborator}/permission",
)
return data["permission"]
def get_pending_invitations(self) -> PaginatedList[Invitation]:
"""
:calls: `GET /repos/{owner}/{repo}/invitations <https://docs.github.com/en/rest/reference/repos#invitations>`_
:rtype: :class:`PaginatedList` of :class:`github.Invitation.Invitation`
"""
return PaginatedList(
github.Invitation.Invitation,
self._requester,
f"{self.url}/invitations",
None,
)
def remove_invitation(self, invite_id: int) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/invitations/{invitation_id} <https://docs.github.com/en/rest/reference/repos#invitations>`_
:rtype: None
"""
assert isinstance(invite_id, int), invite_id
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/invitations/{invite_id}")
def compare(self, base: str, head: str) -> Comparison:
"""
:calls: `GET /repos/{owner}/{repo}/compare/{base...:head} <https://docs.github.com/en/rest/commits/commits#compare-two-commits>`_
:param base: string
:param head: string
:rtype: :class:`github.Comparison.Comparison`
"""
assert isinstance(base, str), base
assert isinstance(head, str), head
base = urllib.parse.quote(base)
head = urllib.parse.quote(head)
# the compare API has a per_page default of 250, which is different to Consts.DEFAULT_PER_PAGE
per_page = self._requester.per_page if self._requester.per_page != Consts.DEFAULT_PER_PAGE else 250
# only with page=1 we get the pagination headers for the commits element
params = {"page": 1, "per_page": per_page}
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/compare/{base}...{head}", params)
return github.Comparison.Comparison(self._requester, headers, data, completed=True)
def create_autolink(
self, key_prefix: str, url_template: str, is_alphanumeric: Opt[bool] = NotSet
) -> github.Autolink.Autolink:
"""
:calls: `POST /repos/{owner}/{repo}/autolinks <http://docs.github.com/en/rest/reference/repos>`_
:param key_prefix: string
:param url_template: string
:param is_alphanumeric: bool
:rtype: :class:`github.Autolink.Autolink`
"""
assert isinstance(key_prefix, str), key_prefix
assert isinstance(url_template, str), url_template
assert is_optional(is_alphanumeric, bool), is_alphanumeric
post_parameters = NotSet.remove_unset_items(
{"key_prefix": key_prefix, "url_template": url_template, "is_alphanumeric": is_alphanumeric}
)
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: str, encoding: str) -> GitBlob:
"""
:calls: `POST /repos/{owner}/{repo}/git/blobs <https://docs.github.com/en/rest/reference/git#blobs>`_
:param content: string
:param encoding: string
:rtype: :class:`github.GitBlob.GitBlob`
"""
assert isinstance(content, str), content
assert isinstance(encoding, str), encoding
post_parameters = {
"content": content,
"encoding": encoding,
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/blobs", input=post_parameters)
return github.GitBlob.GitBlob(self._requester, headers, data, completed=True)
def create_git_commit(
self,
message: str,
tree: GitTree,
parents: list[GitCommit],
author: Opt[InputGitAuthor] = NotSet,
committer: Opt[InputGitAuthor] = NotSet,
) -> GitCommit:
"""
:calls: `POST /repos/{owner}/{repo}/git/commits <https://docs.github.com/en/rest/reference/git#commits>`_
:param message: string
:param tree: :class:`github.GitTree.GitTree`
:param parents: list of :class:`github.GitCommit.GitCommit`
:param author: :class:`github.InputGitAuthor.InputGitAuthor`
:param committer: :class:`github.InputGitAuthor.InputGitAuthor`
:rtype: :class:`github.GitCommit.GitCommit`
"""
assert isinstance(message, str), message
assert isinstance(tree, github.GitTree.GitTree), tree
assert all(isinstance(element, github.GitCommit.GitCommit) for element in parents), parents
assert is_optional(author, github.InputGitAuthor), author
assert is_optional(committer, github.InputGitAuthor), committer
post_parameters: dict[str, Any] = {
"message": message,
"tree": tree._identity,
"parents": [element._identity for element in parents],
}
if is_defined(author):
post_parameters["author"] = author._identity
if is_defined(committer):
post_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/commits", input=post_parameters)
return github.GitCommit.GitCommit(self._requester, headers, data, completed=True)
def create_git_ref(self, ref: str, sha: str) -> GitRef:
"""
:calls: `POST /repos/{owner}/{repo}/git/refs <https://docs.github.com/en/rest/reference/git#references>`_
:param ref: string
:param sha: string
:rtype: :class:`github.GitRef.GitRef`
"""
assert isinstance(ref, str), ref
assert isinstance(sha, str), sha
post_parameters = {
"ref": ref,
"sha": sha,
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/refs", input=post_parameters)
return github.GitRef.GitRef(self._requester, headers, data, completed=True)
# TODO: v3: reorder arguments and add default value `NotSet` where `Opt[str]`
def create_git_tag_and_release(
self,
tag: str,
tag_message: str,
release_name: Opt[str],
release_message: Opt[str],
object: str,
type: str,
tagger: Opt[InputGitAuthor] = NotSet,
draft: bool = False,
prerelease: bool = False,
generate_release_notes: bool = False,
) -> GitRelease:
"""
Convenience function that calls :meth:`Repository.create_git_tag` and :meth:`Repository.create_git_release`.
:param tag: string
:param tag_message: string
:param release_name: string
:param release_message: string
:param object: string
:param type: string
:param tagger: :class:github.InputGitAuthor.InputGitAuthor
:param draft: bool
:param prerelease: bool
:param generate_release_notes: bool
:rtype: :class:`github.GitRelease.GitRelease`
"""
self.create_git_tag(tag, tag_message, object, type, tagger)
return self.create_git_release(
tag,
release_name,
release_message,
draft,
prerelease,
generate_release_notes,
target_commitish=object,
)
def create_git_release(
self,
tag: str,
name: Opt[str] = NotSet,
message: Opt[str] = NotSet,
draft: bool = False,
prerelease: bool = False,
generate_release_notes: bool = False,
target_commitish: Opt[str] = NotSet,
) -> GitRelease:
"""
:calls: `POST /repos/{owner}/{repo}/releases <https://docs.github.com/en/rest/reference/repos#releases>`_
:param tag: string
:param name: string
:param message: string
:param draft: bool
:param prerelease: bool
:param generate_release_notes: bool
:param target_commitish: string or :class:`github.Branch.Branch` or :class:`github.Commit.Commit` or :class:`github.GitCommit.GitCommit`
:rtype: :class:`github.GitRelease.GitRelease`
"""
assert isinstance(tag, str), tag
assert isinstance(generate_release_notes, bool), generate_release_notes
assert isinstance(name, str) or generate_release_notes and is_optional(name, str), name
assert isinstance(message, str) or generate_release_notes and is_optional(message, str), message
assert isinstance(draft, bool), draft
assert isinstance(prerelease, bool), prerelease
assert is_optional(
target_commitish,
(str, github.Branch.Branch, github.Commit.Commit, github.GitCommit.GitCommit),
), target_commitish
post_parameters = {
"tag_name": tag,
"draft": draft,
"prerelease": prerelease,
"generate_release_notes": generate_release_notes,
}
if is_defined(name):
post_parameters["name"] = name
if is_defined(message):
post_parameters["body"] = message
if isinstance(target_commitish, str):
post_parameters["target_commitish"] = target_commitish
elif isinstance(target_commitish, github.Branch.Branch):
post_parameters["target_commitish"] = target_commitish.name
elif isinstance(target_commitish, (github.Commit.Commit, github.GitCommit.GitCommit)):
post_parameters["target_commitish"] = target_commitish.sha
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/releases", input=post_parameters)
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def create_git_tag(
self,
tag: str,
message: str,
object: str,
type: str,
tagger: Opt[InputGitAuthor] = NotSet,
) -> GitTag:
"""
:calls: `POST /repos/{owner}/{repo}/git/tags <https://docs.github.com/en/rest/reference/git#tags>`_
"""
assert isinstance(tag, str), tag
assert isinstance(message, str), message
assert isinstance(object, str), object
assert isinstance(type, str), type
assert is_optional(tagger, github.InputGitAuthor), tagger
post_parameters: dict[str, Any] = {
"tag": tag,
"message": message,
"object": object,
"type": type,
}
if is_defined(tagger):
post_parameters["tagger"] = tagger._identity
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/tags", input=post_parameters)
return github.GitTag.GitTag(self._requester, headers, data, completed=True)
def create_git_tree(self, tree: list[InputGitTreeElement], base_tree: Opt[GitTree] = NotSet) -> GitTree:
"""
:calls: `POST /repos/{owner}/{repo}/git/trees <https://docs.github.com/en/rest/reference/git#trees>`_
:param tree: list of :class:`github.InputGitTreeElement.InputGitTreeElement`
:param base_tree: :class:`github.GitTree.GitTree`
:rtype: :class:`github.GitTree.GitTree`
"""
assert all(isinstance(element, github.InputGitTreeElement) for element in tree), tree
assert is_optional(base_tree, github.GitTree.GitTree), base_tree
post_parameters: dict[str, Any] = {
"tree": [element._identity for element in tree],
}
if is_defined(base_tree):
post_parameters["base_tree"] = base_tree._identity
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/git/trees", input=post_parameters)
return github.GitTree.GitTree(self._requester, headers, data, completed=True)
def create_hook(
self,
name: str,
config: dict[str, str],
events: Opt[list[str]] = NotSet,
active: Opt[bool] = NotSet,
) -> Hook:
"""
:calls: `POST /repos/{owner}/{repo}/hooks <https://docs.github.com/en/rest/reference/repos#webhooks>`_
:param name: string
:param config: dict
:param events: list of string
:param active: bool
:rtype: :class:`github.Hook.Hook`
"""
assert isinstance(name, str), name
assert isinstance(config, dict), config
assert is_optional_list(events, str), events
assert is_optional(active, bool), active
post_parameters = NotSet.remove_unset_items(
{"name": name, "config": config, "events": events, "active": active}
)
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/hooks", input=post_parameters)
return github.Hook.Hook(self._requester, headers, data, completed=True)
def create_issue(
self,
title: str,
body: Opt[str] = NotSet,
assignee: NamedUser | Opt[str] = NotSet,
milestone: Opt[Milestone] = NotSet,
labels: list[Label] | Opt[list[str]] = NotSet,
assignees: Opt[list[str]] | list[NamedUser] = NotSet,
) -> Issue:
"""
:calls: `POST /repos/{owner}/{repo}/issues <https://docs.github.com/en/rest/reference/issues>`_
:param title: string
:param body: string
:param assignee: string or :class:`github.NamedUser.NamedUser`
:param assignees: list of string or :class:`github.NamedUser.NamedUser`
:param milestone: :class:`github.Milestone.Milestone`
:param labels: list of :class:`github.Label.Label`
:rtype: :class:`github.Issue.Issue`
"""
assert isinstance(title, str), title
assert is_optional(body, str), body
assert is_optional(assignee, (str, github.NamedUser.NamedUser)), assignee
assert is_optional_list(assignees, (github.NamedUser.NamedUser, str)), assignees
assert is_optional(milestone, github.Milestone.Milestone), milestone
assert is_optional_list(labels, (github.Label.Label, str)), labels
post_parameters: dict[str, Any] = {
"title": title,
}
if is_defined(body):
post_parameters["body"] = body
if is_defined(assignee):
if isinstance(assignee, github.NamedUser.NamedUser):
post_parameters["assignee"] = assignee._identity
else:
post_parameters["assignee"] = assignee
if is_defined(assignees):
post_parameters["assignees"] = [
element._identity if isinstance(element, github.NamedUser.NamedUser) else element
for element in assignees # type: ignore
]
if is_defined(milestone):
post_parameters["milestone"] = milestone._identity
if is_defined(labels):
post_parameters["labels"] = [
element.name if isinstance(element, github.Label.Label) else element
for element in labels # type: ignore
]
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/issues", input=post_parameters)
return github.Issue.Issue(self._requester, headers, data, completed=True)
def create_key(self, title: str, key: str, read_only: bool = False) -> RepositoryKey:
"""
:calls: `POST /repos/{owner}/{repo}/keys <https://docs.github.com/en/rest/reference/repos#deploy-keys>`_
:param title: string
:param key: string
:param read_only: bool
:rtype: :class:`github.RepositoryKey.RepositoryKey`
"""
assert isinstance(title, str), title
assert isinstance(key, str), key
assert isinstance(read_only, bool), read_only
post_parameters = {
"title": title,
"key": key,
"read_only": read_only,
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/keys", input=post_parameters)
return github.RepositoryKey.RepositoryKey(self._requester, headers, data, completed=True)
def create_label(self, name: str, color: str, description: Opt[str] = NotSet) -> Label:
"""
:calls: `POST /repos/{owner}/{repo}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
:param name: string
:param color: string
:param description: string
:rtype: :class:`github.Label.Label`
"""
assert isinstance(name, str), name
assert isinstance(color, str), color
assert is_optional(description, str), description
post_parameters = {
"name": name,
"color": color,
}
if is_defined(description):
post_parameters["description"] = description
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/labels",
input=post_parameters,
headers={"Accept": Consts.mediaTypeLabelDescriptionSearchPreview},
)
return github.Label.Label(self._requester, headers, data, completed=True)
def create_milestone(
self,
title: str,
state: Opt[str] = NotSet,
description: Opt[str] = NotSet,
due_on: Opt[date] = NotSet,
) -> Milestone:
"""
:calls: `POST /repos/{owner}/{repo}/milestones <https://docs.github.com/en/rest/reference/issues#milestones>`_
:param title: string
:param state: string
:param description: string
:param due_on: datetime
:rtype: :class:`github.Milestone.Milestone`
"""
assert isinstance(title, str), title
assert is_optional(state, str), state
assert is_optional(description, str), description
assert is_optional(due_on, (datetime, date)), due_on
post_parameters = {
"title": title,
}
if is_defined(state):
post_parameters["state"] = state
if is_defined(description):
post_parameters["description"] = description
if is_defined(due_on):
if isinstance(due_on, date):
post_parameters["due_on"] = due_on.strftime("%Y-%m-%dT%H:%M:%SZ")
else:
post_parameters["due_on"] = due_on.isoformat()
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/milestones", input=post_parameters)
return github.Milestone.Milestone(self._requester, headers, data, completed=True)
def create_project(self, name: str, body: Opt[str] = NotSet) -> Project:
"""
:calls: `POST /repos/{owner}/{repo}/projects <https://docs.github.com/en/rest/reference/projects#create-a-repository-project>`_
:param name: string
:param body: string
:rtype: :class:`github.Project.Project`
"""
assert isinstance(name, str), name
assert is_optional(body, str), body
post_parameters = {
"name": name,
}
import_header = {"Accept": Consts.mediaTypeProjectsPreview}
if is_defined(body):
post_parameters["body"] = body
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.url}/projects", headers=import_header, input=post_parameters
)
return github.Project.Project(self._requester, headers, data, completed=True)
def create_pull(
self,
base: str,
head: str,
*,
title: Opt[str] = NotSet,
body: Opt[str] = NotSet,
maintainer_can_modify: Opt[bool] = NotSet,
draft: Opt[bool] = NotSet,
issue: Opt[github.Issue.Issue] = NotSet,
) -> github.PullRequest.PullRequest:
"""
:calls: `POST /repos/{owner}/{repo}/pulls <https://docs.github.com/en/free-pro-team@latest/rest/pulls/pulls?apiVersion=2022-11-28#create-a-pull-request>`_
"""
assert isinstance(base, str), base
assert isinstance(head, str), head
assert is_optional(title, str), title
assert is_optional(body, str), body
assert is_optional(maintainer_can_modify, bool), maintainer_can_modify
assert is_optional(draft, bool), draft
assert is_optional(issue, github.Issue.Issue), issue
post_parameters = NotSet.remove_unset_items(
{
"base": base,
"head": head,
"title": title,
"body": body,
"maintainer_can_modify": maintainer_can_modify,
"draft": draft,
}
)
if is_defined(issue):
post_parameters["issue"] = issue._identity
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/pulls", input=post_parameters)
return github.PullRequest.PullRequest(self._requester, headers, data, completed=True)
def create_repository_advisory(
self,
summary: str,
description: str,
severity_or_cvss_vector_string: str,
cve_id: str | None = None,
vulnerabilities: Iterable[github.AdvisoryVulnerability.AdvisoryVulnerabilityInput] | None = None,
cwe_ids: Iterable[str] | None = None,
credits: Iterable[github.AdvisoryCredit.AdvisoryCredit] | None = None,
) -> github.RepositoryAdvisory.RepositoryAdvisory:
"""
:calls: `POST /repos/{owner}/{repo}/security-advisories <https://docs.github.com/en/rest/security-advisories/repository-advisories>`_
:param summary: string
:param description: string
:param severity_or_cvss_vector_string: string
:param cve_id: string
:param vulnerabilities: iterable of :class:`github.AdvisoryVulnerability.AdvisoryVulnerabilityInput`
:param cwe_ids: iterable of string
:param credits: iterable of :class:`github.AdvisoryCredit.AdvisoryCredit`
:rtype: :class:`github.RepositoryAdvisory.RepositoryAdvisory`
"""
return self.__create_repository_advisory(
summary=summary,
description=description,
severity_or_cvss_vector_string=severity_or_cvss_vector_string,
cve_id=cve_id,
vulnerabilities=vulnerabilities,
cwe_ids=cwe_ids,
credits=credits,
private_vulnerability_reporting=False,
)
def report_security_vulnerability(
self,
summary: str,
description: str,
severity_or_cvss_vector_string: str,
cve_id: str | None = None,
vulnerabilities: Iterable[github.AdvisoryVulnerability.AdvisoryVulnerabilityInput] | None = None,
cwe_ids: Iterable[str] | None = None,
credits: Iterable[github.AdvisoryCredit.AdvisoryCredit] | None = None,
) -> github.RepositoryAdvisory.RepositoryAdvisory:
"""
:calls: `POST /repos/{owner}/{repo}/security-advisories/reports <https://docs.github.com/en/rest/security-advisories/repository-advisories#privately-report-a-security-vulnerability>`_
:param summary: string
:param description: string
:param severity_or_cvss_vector_string: string
:param cve_id: string
:param vulnerabilities: iterable of :class:`github.AdvisoryVulnerability.AdvisoryVulnerabilityInput`
:param cwe_ids: iterable of string
:param credits: iterable of :class:`github.AdvisoryCredit.AdvisoryCredit`
:rtype: :class:`github.RepositoryAdvisory.RepositoryAdvisory`
"""
return self.__create_repository_advisory(
summary=summary,
description=description,
severity_or_cvss_vector_string=severity_or_cvss_vector_string,
cve_id=cve_id,
vulnerabilities=vulnerabilities,
cwe_ids=cwe_ids,
credits=credits,
private_vulnerability_reporting=True,
)
def __create_repository_advisory(
self,
summary: str,
description: str,
severity_or_cvss_vector_string: str,
cve_id: str | None,
vulnerabilities: Iterable[github.AdvisoryVulnerability.AdvisoryVulnerabilityInput] | None,
cwe_ids: Iterable[str] | None,
credits: Iterable[github.AdvisoryCredit.AdvisoryCredit] | None,
private_vulnerability_reporting: bool,
) -> github.RepositoryAdvisory.RepositoryAdvisory:
if vulnerabilities is None:
vulnerabilities = []
if cwe_ids is None:
cwe_ids = []
assert isinstance(summary, str), summary
assert isinstance(description, str), description
assert isinstance(severity_or_cvss_vector_string, str), severity_or_cvss_vector_string
assert isinstance(cve_id, (str, type(None))), cve_id
assert isinstance(vulnerabilities, Iterable), vulnerabilities
for vulnerability in vulnerabilities:
github.AdvisoryVulnerability.AdvisoryVulnerability._validate_vulnerability(vulnerability)
assert isinstance(cwe_ids, Iterable), cwe_ids
assert all(isinstance(element, str) for element in cwe_ids), cwe_ids
assert isinstance(credits, (Iterable, type(None))), credits
if credits is not None:
for credit in credits:
github.AdvisoryCredit.AdvisoryCredit._validate_credit(credit)
post_parameters = {
"summary": summary,
"description": description,
"vulnerabilities": [
github.AdvisoryVulnerability.AdvisoryVulnerability._to_github_dict(vulnerability)
for vulnerability in vulnerabilities
],
"cwe_ids": list(cwe_ids),
}
if cve_id is not None:
post_parameters["cve_id"] = cve_id
if credits is not None:
post_parameters["credits"] = [
github.AdvisoryCredit.AdvisoryCredit._to_github_dict(credit) for credit in credits
]
if severity_or_cvss_vector_string.startswith("CVSS:"):
post_parameters["cvss_vector_string"] = severity_or_cvss_vector_string
else:
post_parameters["severity"] = severity_or_cvss_vector_string
if private_vulnerability_reporting:
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.url}/security-advisories/reports", input=post_parameters
)
else:
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.url}/security-advisories", input=post_parameters
)
return github.RepositoryAdvisory.RepositoryAdvisory(self._requester, headers, data, completed=True)
def create_repository_dispatch(self, event_type: str, client_payload: Opt[dict[str, Any]] = NotSet) -> bool:
"""
:calls: POST /repos/{owner}/{repo}/dispatches <https://docs.github.com/en/rest/repos#create-a-repository-dispatch-event>
:param event_type: string
:param client_payload: dict
:rtype: bool
"""
assert isinstance(event_type, str), event_type
assert is_optional(client_payload, dict), client_payload
post_parameters = NotSet.remove_unset_items({"event_type": event_type, "client_payload": client_payload})
status, headers, data = self._requester.requestJson("POST", f"{self.url}/dispatches", input=post_parameters)
return status == 204
def create_secret(
self,
secret_name: str,
unencrypted_value: str,
secret_type: str = "actions",
) -> github.Secret.Secret:
"""
:calls: `PUT /repos/{owner}/{repo}/{secret_type}/secrets/{secret_name} <https://docs.github.com/en/rest/actions/secrets#get-a-repository-secret>`_
:param secret_type: string options actions or dependabot
"""
assert isinstance(secret_name, str), secret_name
assert isinstance(unencrypted_value, str), unencrypted_value
assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot"
secret_name = urllib.parse.quote(secret_name)
public_key = self.get_public_key(secret_type=secret_type)
payload = public_key.encrypt(unencrypted_value)
put_parameters = {
"key_id": public_key.key_id,
"encrypted_value": payload,
}
self._requester.requestJsonAndCheck(
"PUT", f"{self.url}/{secret_type}/secrets/{secret_name}", input=put_parameters
)
return github.Secret.Secret(
requester=self._requester,
headers={},
attributes={
"name": secret_name,
"url": f"{self.url}/{secret_type}/secrets/{secret_name}",
},
completed=False,
)
def get_secrets(
self,
secret_type: str = "actions",
) -> PaginatedList[github.Secret.Secret]:
"""
Gets all repository secrets :param secret_type: string options actions or dependabot.
"""
assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot"
return PaginatedList(
github.Secret.Secret,
self._requester,
f"{self.url}/{secret_type}/secrets",
None,
attributesTransformer=PaginatedList.override_attributes(
{"secrets_url": f"{self.url}/{secret_type}/secrets"}
),
list_item="secrets",
)
def get_secret(self, secret_name: str, secret_type: str = "actions") -> github.Secret.Secret:
"""
:calls: 'GET /repos/{owner}/{repo}/actions/secrets/{secret_name} <https://docs.github.com/en/rest/actions/secrets#get-an-organization-secret>`_
:param secret_type: string options actions or dependabot
"""
assert isinstance(secret_name, str), secret_name
assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot"
secret_name = urllib.parse.quote(secret_name)
return github.Secret.Secret(
requester=self._requester,
headers={},
attributes={"url": f"{self.url}/{secret_type}/secrets/{secret_name}"},
completed=False,
)
def create_variable(self, variable_name: str, value: str) -> github.Variable.Variable:
"""
:calls: `POST /repos/{owner}/{repo}/actions/variables/{variable_name} <https://docs.github.com/en/rest/actions/variables#create-a-repository-variable>`_
"""
assert isinstance(variable_name, str), variable_name
assert isinstance(value, str), value
post_parameters = {
"name": variable_name,
"value": value,
}
self._requester.requestJsonAndCheck("POST", f"{self.url}/actions/variables", input=post_parameters)
return github.Variable.Variable(
self._requester,
headers={},
attributes={
"name": variable_name,
"value": value,
"url": f"{self.url}/actions/variables/{variable_name}",
},
completed=False,
)
def get_variables(self) -> PaginatedList[github.Variable.Variable]:
"""
Gets all repository variables :rtype: :class:`PaginatedList` of :class:`github.Variable.Variable`
"""
return PaginatedList(
github.Variable.Variable,
self._requester,
f"{self.url}/actions/variables",
None,
attributesTransformer=PaginatedList.override_attributes({"variables_url": f"{self.url}/actions/variables"}),
list_item="variables",
)
def get_variable(self, variable_name: str) -> github.Variable.Variable:
"""
:calls: 'GET /orgs/{org}/actions/variables/{variable_name} <https://docs.github.com/en/rest/actions/variables#get-an-organization-variable>`_
:param variable_name: string
:rtype: github.Variable.Variable
"""
assert isinstance(variable_name, str), variable_name
variable_name = urllib.parse.quote(variable_name)
return github.Variable.Variable(
requester=self._requester,
headers={},
attributes={"url": f"{self.url}/actions/variables/{variable_name}"},
completed=False,
)
def delete_secret(self, secret_name: str, secret_type: str = "actions") -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/{secret_type}/secrets/{secret_name} <https://docs.github.com/en/rest/reference/actions#delete-a-repository-secret>`_
:param secret_name: string
:param secret_type: string options actions or dependabot
:rtype: bool
"""
assert isinstance(secret_name, str), secret_name
assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot"
secret_name = urllib.parse.quote(secret_name)
status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/{secret_type}/secrets/{secret_name}")
return status == 204
def delete_variable(self, variable_name: str) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/actions/variables/{variable_name} <https://docs.github.com/en/rest/reference/actions#delete-a-repository-variable>`_
:param variable_name: string
:rtype: bool
"""
assert isinstance(variable_name, str), variable_name
variable_name = urllib.parse.quote(variable_name)
status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/actions/variables/{variable_name}")
return status == 204
def create_source_import(
self,
vcs: str,
vcs_url: str,
vcs_username: Opt[str] = NotSet,
vcs_password: Opt[str] = NotSet,
) -> SourceImport:
"""
:calls: `PUT /repos/{owner}/{repo}/import <https://docs.github.com/en/rest/reference/migrations#start-an-import>`_
:param vcs: string
:param vcs_url: string
:param vcs_username: string
:param vcs_password: string
:rtype: :class:`github.SourceImport.SourceImport`
"""
assert isinstance(vcs, str), vcs
assert isinstance(vcs_url, str), vcs_url
assert is_optional(vcs_username, str), vcs_username
assert is_optional(vcs_password, str), vcs_password
put_parameters = {"vcs": vcs, "vcs_url": vcs_url}
if is_defined(vcs_username):
put_parameters["vcs_username"] = vcs_username
if is_defined(vcs_password):
put_parameters["vcs_password"] = vcs_password
import_header = {"Accept": Consts.mediaTypeImportPreview}
headers, data = self._requester.requestJsonAndCheck(
"PUT", f"{self.url}/import", headers=import_header, input=put_parameters
)
return github.SourceImport.SourceImport(self._requester, headers, data, completed=False)
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo} <https://docs.github.com/en/rest/reference/repos>`_
:rtype: None
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(
self,
name: str | None = None,
description: Opt[str] = NotSet,
homepage: Opt[str] = NotSet,
private: Opt[bool] = NotSet,
visibility: Opt[str] = NotSet,
has_issues: Opt[bool] = NotSet,
has_projects: Opt[bool] = NotSet,
has_wiki: Opt[bool] = NotSet,
has_discussions: Opt[bool] = NotSet,
is_template: Opt[bool] = NotSet,
default_branch: Opt[str] = NotSet,
allow_squash_merge: Opt[bool] = NotSet,
allow_merge_commit: Opt[bool] = NotSet,
allow_rebase_merge: Opt[bool] = NotSet,
allow_auto_merge: Opt[bool] = NotSet,
delete_branch_on_merge: Opt[bool] = NotSet,
allow_update_branch: Opt[bool] = NotSet,
use_squash_pr_title_as_default: Opt[bool] = NotSet,
squash_merge_commit_title: Opt[str] = NotSet,
squash_merge_commit_message: Opt[str] = NotSet,
merge_commit_title: Opt[str] = NotSet,
merge_commit_message: Opt[str] = NotSet,
archived: Opt[bool] = NotSet,
allow_forking: Opt[bool] = NotSet,
web_commit_signoff_required: Opt[bool] = NotSet,
) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo} <https://docs.github.com/en/rest/reference/repos>`_
"""
if name is None:
name = self.name
assert isinstance(name, str), name
assert is_optional(description, str), description
assert is_optional(homepage, str), homepage
assert is_optional(private, bool), private
assert visibility in ["public", "private", "internal", NotSet], visibility
assert is_optional(has_issues, bool), has_issues
assert is_optional(has_projects, bool), has_projects
assert is_optional(has_wiki, bool), has_wiki
assert is_optional(has_discussions, bool), has_discussions
assert is_optional(is_template, bool), is_template
assert is_optional(default_branch, str), default_branch
assert is_optional(allow_squash_merge, bool), allow_squash_merge
assert is_optional(allow_merge_commit, bool), allow_merge_commit
assert is_optional(allow_rebase_merge, bool), allow_rebase_merge
assert is_optional(allow_auto_merge, bool), allow_auto_merge
assert is_optional(delete_branch_on_merge, bool), delete_branch_on_merge
assert is_optional(allow_update_branch, bool), allow_update_branch
assert is_optional(use_squash_pr_title_as_default, bool), use_squash_pr_title_as_default
assert squash_merge_commit_title in ["PR_TITLE", "COMMIT_OR_PR_TITLE", NotSet], squash_merge_commit_title
assert squash_merge_commit_message in [
"PR_BODY",
"COMMIT_MESSAGES",
"BLANK",
NotSet,
], squash_merge_commit_message
assert merge_commit_title in ["PR_TITLE", "MERGE_MESSAGE", NotSet], merge_commit_title
assert merge_commit_message in ["PR_TITLE", "PR_BODY", "BLANK", NotSet], merge_commit_message
assert is_optional(archived, bool), archived
assert is_optional(allow_forking, bool), allow_forking
assert is_optional(web_commit_signoff_required, bool), web_commit_signoff_required
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"name": name,
"description": description,
"homepage": homepage,
"private": private,
"visibility": visibility,
"has_issues": has_issues,
"has_projects": has_projects,
"has_wiki": has_wiki,
"has_discussions": has_discussions,
"is_template": is_template,
"default_branch": default_branch,
"allow_squash_merge": allow_squash_merge,
"allow_merge_commit": allow_merge_commit,
"allow_rebase_merge": allow_rebase_merge,
"allow_auto_merge": allow_auto_merge,
"delete_branch_on_merge": delete_branch_on_merge,
"allow_update_branch": allow_update_branch,
"use_squash_pr_title_as_default": use_squash_pr_title_as_default,
"squash_merge_commit_title": squash_merge_commit_title,
"squash_merge_commit_message": squash_merge_commit_message,
"merge_commit_title": merge_commit_title,
"merge_commit_message": merge_commit_message,
"archived": archived,
"allow_forking": allow_forking,
"web_commit_signoff_required": web_commit_signoff_required,
}
)
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def get_archive_link(self, archive_format: str, ref: Opt[str] = NotSet) -> str:
"""
:calls: `GET /repos/{owner}/{repo}/{archive_format}/{ref} <https://docs.github.com/en/rest/reference/repos#contents>`_
:param archive_format: string
:param ref: string
:rtype: string
"""
assert isinstance(archive_format, str), archive_format
archive_format = urllib.parse.quote(archive_format)
assert is_optional(ref, str), ref
url = f"{self.url}/{archive_format}"
if is_defined(ref):
ref = urllib.parse.quote(ref)
url += f"/{ref}"
headers, data = self._requester.requestJsonAndCheck("GET", url)
return headers["location"]
def get_assignees(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/assignees <https://docs.github.com/en/rest/reference/issues#assignees>`_
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/assignees", None)
def get_branch(self, branch: str) -> Branch:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch} <https://docs.github.com/en/rest/reference/repos#get-a-branch>`_
:param branch: string
:rtype: :class:`github.Branch.Branch`
"""
assert isinstance(branch, str), branch
branch = urllib.parse.quote(branch)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/branches/{branch}")
return github.Branch.Branch(self._requester, headers, data, completed=True)
def rename_branch(self, branch: str | Branch, new_name: str) -> bool:
"""
:calls: `POST /repos/{owner}/{repo}/branches/{branch}/rename <https://docs.github.com/en/rest/reference/repos#branches>`_
:param branch: :class:`github.Branch.Branch` or string
:param new_name: string
:rtype: bool
NOTE: This method does not return the branch since it may take some
time to fully complete server-side.
"""
is_branch = isinstance(branch, github.Branch.Branch)
assert isinstance(new_name, str), new_name
if is_branch:
branch = branch.name # type: ignore
else:
assert isinstance(branch, str), branch
branch = urllib.parse.quote(branch)
parameters = {"new_name": new_name}
status, _, _ = self._requester.requestJson("POST", f"{self.url}/branches/{branch}/rename", input=parameters)
return status == 201
def get_branches(self) -> PaginatedList[Branch]:
"""
:calls: `GET /repos/{owner}/{repo}/branches <https://docs.github.com/en/rest/reference/repos>`_
:rtype: :class:`PaginatedList` of :class:`github.Branch.Branch`
"""
return PaginatedList(github.Branch.Branch, self._requester, f"{self.url}/branches", None)
def get_collaborators(
self, affiliation: Opt[str] = NotSet, permission: Opt[str] = NotSet
) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/collaborators <https://docs.github.com/en/rest/collaborators/collaborators>`_
:param affiliation: string
:param permission: string
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
url_parameters = dict()
allowed_affiliations = ["outside", "direct", "all"]
allowed_permissions = ["pull", "triage", "push", "maintain", "admin"]
if is_defined(affiliation):
assert isinstance(affiliation, str), affiliation
assert affiliation in allowed_affiliations, f"Affiliation can be one of {', '.join(allowed_affiliations)}"
url_parameters["affiliation"] = affiliation
if is_defined(permission):
assert isinstance(permission, str), permission
assert permission in allowed_permissions, f"permission can be one of {', '.join(allowed_permissions)}"
url_parameters["permission"] = permission
return PaginatedList(
github.NamedUser.NamedUser,
self._requester,
f"{self.url}/collaborators",
url_parameters,
)
def get_comment(self, id: int) -> CommitComment:
"""
:calls: `GET /repos/{owner}/{repo}/comments/{id} <https://docs.github.com/en/rest/reference/repos#comments>`_
:param id: integer
:rtype: :class:`github.CommitComment.CommitComment`
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/comments/{id}")
return github.CommitComment.CommitComment(self._requester, headers, data, completed=True)
def get_comments(self) -> PaginatedList[CommitComment]:
"""
:calls: `GET /repos/{owner}/{repo}/comments <https://docs.github.com/en/rest/reference/repos#comments>`_
:rtype: :class:`PaginatedList` of :class:`github.CommitComment.CommitComment`
"""
return PaginatedList(
github.CommitComment.CommitComment,
self._requester,
f"{self.url}/comments",
None,
)
def get_commit(self, sha: str) -> Commit:
"""
:calls: `GET /repos/{owner}/{repo}/commits/{sha} <https://docs.github.com/en/rest/reference/repos#commits>`_
:param sha: string
:rtype: :class:`github.Commit.Commit`
"""
assert isinstance(sha, str), sha
sha = urllib.parse.quote(sha)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/commits/{sha}")
return github.Commit.Commit(self._requester, headers, data, completed=True)
def get_commits(
self,
sha: Opt[str] = NotSet,
path: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
until: Opt[datetime] = NotSet,
author: Opt[AuthenticatedUser | NamedUser | str] = NotSet,
) -> PaginatedList[Commit]:
"""
:calls: `GET /repos/{owner}/{repo}/commits <https://docs.github.com/en/rest/reference/repos#commits>`_
:param sha: string
:param path: string
:param since: datetime
:param until: datetime
:param author: string or :class:`github.NamedUser.NamedUser` or :class:`github.AuthenticatedUser.AuthenticatedUser`
:rtype: :class:`PaginatedList` of :class:`github.Commit.Commit`
"""
assert is_optional(sha, str), sha
assert is_optional(path, str), path
assert is_optional(since, datetime), since
assert is_optional(until, datetime), until
assert is_optional(
author,
(str, github.NamedUser.NamedUser, github.AuthenticatedUser.AuthenticatedUser),
), author
url_parameters: dict[str, Any] = {}
if is_defined(sha):
url_parameters["sha"] = sha
if is_defined(path):
url_parameters["path"] = path
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
if is_defined(until):
url_parameters["until"] = until.strftime("%Y-%m-%dT%H:%M:%SZ")
if is_defined(author):
if isinstance(
author,
(github.NamedUser.NamedUser, github.AuthenticatedUser.AuthenticatedUser),
):
url_parameters["author"] = author.login
else:
url_parameters["author"] = author
return PaginatedList(github.Commit.Commit, self._requester, f"{self.url}/commits", url_parameters)
def get_contents(self, path: str, ref: Opt[str] = NotSet) -> list[ContentFile] | ContentFile:
"""
:calls: `GET /repos/{owner}/{repo}/contents/{path} <https://docs.github.com/en/rest/reference/repos#contents>`_
:param path: string
:param ref: string
:rtype: :class:`github.ContentFile.ContentFile` or a list of them
"""
assert isinstance(path, str), path
assert is_optional(ref, str), ref
# Path of '/' should be the empty string.
if path == "/":
path = ""
url_parameters = dict()
if is_defined(ref):
url_parameters["ref"] = ref
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/contents/{urllib.parse.quote(path)}",
parameters=url_parameters,
)
# Handle 302 redirect response
if headers.get("status") == "302 Found" and headers.get("location"):
headers, data = self._requester.requestJsonAndCheck("GET", headers["location"], parameters=url_parameters)
if isinstance(data, list):
return [
# Lazy completion only makes sense for files. See discussion
# here: https://github.com/jacquev6/PyGithub/issues/140#issuecomment-13481130
github.ContentFile.ContentFile(self._requester, headers, item, completed=(item["type"] != "file"))
for item in data
]
return github.ContentFile.ContentFile(self._requester, headers, data, completed=True)
def get_deployments(
self,
sha: Opt[str] = NotSet,
ref: Opt[str] = NotSet,
task: Opt[str] = NotSet,
environment: Opt[str] = NotSet,
) -> PaginatedList[Deployment]:
"""
:calls: `GET /repos/{owner}/{repo}/deployments <https://docs.github.com/en/rest/reference/repos#deployments>`_
:param: sha: string
:param: ref: string
:param: task: string
:param: environment: string
:rtype: :class:`PaginatedList` of :class:`github.Deployment.Deployment`
"""
assert is_optional(sha, str), sha
assert is_optional(ref, str), ref
assert is_optional(task, str), task
assert is_optional(environment, str), environment
parameters = {}
if is_defined(sha):
parameters["sha"] = sha
if is_defined(ref):
parameters["ref"] = ref
if is_defined(task):
parameters["task"] = task
if is_defined(environment):
parameters["environment"] = environment
return PaginatedList(
github.Deployment.Deployment,
self._requester,
f"{self.url}/deployments",
parameters,
headers={"Accept": Consts.deploymentEnhancementsPreview},
)
def get_deployment(self, id_: int) -> Deployment:
"""
:calls: `GET /repos/{owner}/{repo}/deployments/{deployment_id} <https://docs.github.com/en/rest/reference/repos#deployments>`_
:param: id_: int
:rtype: :class:`github.Deployment.Deployment`
"""
assert isinstance(id_, int), id_
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/deployments/{id_}",
headers={"Accept": Consts.deploymentEnhancementsPreview},
)
return github.Deployment.Deployment(self._requester, headers, data, completed=True)
def create_deployment(
self,
ref: str,
task: Opt[str] = NotSet,
auto_merge: Opt[bool] = NotSet,
required_contexts: Opt[list[str]] = NotSet,
payload: Opt[dict[str, Any]] = NotSet,
environment: Opt[str] = NotSet,
description: Opt[str] = NotSet,
transient_environment: Opt[bool] = NotSet,
production_environment: Opt[bool] = NotSet,
) -> Deployment:
"""
:calls: `POST /repos/{owner}/{repo}/deployments <https://docs.github.com/en/rest/reference/repos#deployments>`_
:param: ref: string
:param: task: string
:param: auto_merge: bool
:param: required_contexts: list of status contexts
:param: payload: dict
:param: environment: string
:param: description: string
:param: transient_environment: bool
:param: production_environment: bool
:rtype: :class:`github.Deployment.Deployment`
"""
assert isinstance(ref, str), ref
assert is_optional(task, str), task
assert is_optional(auto_merge, bool), auto_merge
assert is_optional(required_contexts, list), required_contexts # need to do better checking here
assert is_optional(payload, dict), payload
assert is_optional(environment, str), environment
assert is_optional(description, str), description
assert is_optional(transient_environment, bool), transient_environment
assert is_optional(production_environment, bool), production_environment
post_parameters: dict[str, Any] = {"ref": ref}
if is_defined(task):
post_parameters["task"] = task
if is_defined(auto_merge):
post_parameters["auto_merge"] = auto_merge
if is_defined(required_contexts):
post_parameters["required_contexts"] = required_contexts
if is_defined(payload):
post_parameters["payload"] = payload
if is_defined(environment):
post_parameters["environment"] = environment
if is_defined(description):
post_parameters["description"] = description
if is_defined(transient_environment):
post_parameters["transient_environment"] = transient_environment
if is_defined(production_environment):
post_parameters["production_environment"] = production_environment
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/deployments",
input=post_parameters,
headers={"Accept": Consts.deploymentEnhancementsPreview},
)
return github.Deployment.Deployment(self._requester, headers, data, completed=True)
def get_top_referrers(self) -> None | list[Referrer]:
"""
:calls: `GET /repos/{owner}/{repo}/traffic/popular/referrers <https://docs.github.com/en/rest/reference/repos#traffic>`_
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/traffic/popular/referrers")
if isinstance(data, list):
return [github.Referrer.Referrer(self._requester, headers, item, completed=True) for item in data]
def get_top_paths(self) -> None | list[Path]:
"""
:calls: `GET /repos/{owner}/{repo}/traffic/popular/paths <https://docs.github.com/en/rest/reference/repos#traffic>`_
:rtype: :class:`list` of :class:`github.Path.Path`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/traffic/popular/paths")
if isinstance(data, list):
return [github.Path.Path(self._requester, headers, item, completed=True) for item in data]
def get_views_traffic(self, per: Opt[str] = NotSet) -> None | dict[str, int | list[View]]:
"""
:calls: `GET /repos/{owner}/{repo}/traffic/views <https://docs.github.com/en/rest/reference/repos#traffic>`_
:param per: string, must be one of day or week, day by default
"""
assert per in ["day", "week", NotSet], "per must be day or week, day by default"
url_parameters = dict()
if is_defined(per):
url_parameters["per"] = per
headers, data = self._requester.requestJsonAndCheck(
"GET", f"{self.url}/traffic/views", parameters=url_parameters
)
if (isinstance(data, dict)) and ("views" in data) and (isinstance(data["views"], list)):
data["views"] = [github.View.View(self._requester, headers, item, completed=True) for item in data["views"]]
return data
def get_clones_traffic(self, per: Opt[str] = NotSet) -> dict[str, int | list[Clones]] | None:
"""
:calls: `GET /repos/{owner}/{repo}/traffic/clones <https://docs.github.com/en/rest/reference/repos#traffic>`_
:param per: string, must be one of day or week, day by default
:rtype: None or list of :class:`github.Clones.Clones`
"""
assert per in ["day", "week", NotSet], "per must be day or week, day by default"
url_parameters: dict[str, Any] = NotSet.remove_unset_items({"per": per})
headers, data = self._requester.requestJsonAndCheck(
"GET", f"{self.url}/traffic/clones", parameters=url_parameters
)
if (isinstance(data, dict)) and ("clones" in data) and (isinstance(data["clones"], list)):
data["clones"] = [
github.Clones.Clones(self._requester, headers, item, completed=True) for item in data["clones"]
]
return data
def get_projects(self, state: Opt[str] = NotSet) -> PaginatedList[Project]:
"""
:calls: `GET /repos/{owner}/{repo}/projects <https://docs.github.com/en/rest/reference/projects#list-repository-projects>`_
:rtype: :class:`PaginatedList` of :class:`github.Project.Project`
:param state: string
"""
url_parameters = dict()
if is_defined(state):
url_parameters["state"] = state
return PaginatedList(
github.Project.Project,
self._requester,
f"{self.url}/projects",
url_parameters,
{"Accept": Consts.mediaTypeProjectsPreview},
)
def get_autolinks(self) -> PaginatedList[Autolink]:
"""
:calls: `GET /repos/{owner}/{repo}/autolinks <http://docs.github.com/en/rest/reference/repos>`_
:rtype: :class:`PaginatedList` of :class:`github.Autolink.Autolink`
"""
return PaginatedList(github.Autolink.Autolink, self._requester, f"{self.url}/autolinks", None)
def create_file(
self,
path: str,
message: str,
content: str | bytes,
branch: Opt[str] = NotSet,
committer: Opt[InputGitAuthor] = NotSet,
author: Opt[InputGitAuthor] = NotSet,
) -> dict[str, ContentFile | Commit]:
"""
Create a file in this repository.
:calls: `PUT /repos/{owner}/{repo}/contents/{path} <https://docs.github.com/en/rest/reference/repos#create-or-
update-file-contents>`_
:param path: string, (required), path of the file in the repository
:param message: string, (required), commit message
:param content: string, (required), the actual data in the file
:param branch: string, (optional), branch to create the commit on. Defaults to the default branch of the
repository
:param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information
will be used. You must specify both a name and email.
:param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If
passed, you must specify both a name and email.
:rtype: { 'content': :class:`ContentFile <github.ContentFile.ContentFile>`:, 'commit': :class:`Commit
<github.Commit.Commit>`}
"""
assert isinstance(path, str)
assert isinstance(message, str)
assert isinstance(content, (str, bytes))
assert is_optional(branch, str)
assert is_optional(author, github.InputGitAuthor)
assert is_optional(committer, github.InputGitAuthor)
if not isinstance(content, bytes):
content = content.encode("utf-8")
content = b64encode(content).decode("utf-8")
put_parameters: dict[str, Any] = {"message": message, "content": content}
if is_defined(branch):
put_parameters["branch"] = branch
if is_defined(author):
put_parameters["author"] = author._identity
if is_defined(committer):
put_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"PUT",
f"{self.url}/contents/{urllib.parse.quote(path)}",
input=put_parameters,
)
return {
"content": github.ContentFile.ContentFile(self._requester, headers, data["content"], completed=False),
"commit": github.Commit.Commit(self._requester, headers, data["commit"], completed=True),
}
def get_repository_advisories(
self,
) -> PaginatedList[github.RepositoryAdvisory.RepositoryAdvisory]:
"""
:calls: `GET /repos/{owner}/{repo}/security-advisories <https://docs.github.com/en/rest/security-advisories/repository-advisories>`_
:rtype: :class:`PaginatedList` of :class:`github.RepositoryAdvisory.RepositoryAdvisory`
"""
return PaginatedList(
github.RepositoryAdvisory.RepositoryAdvisory,
self._requester,
f"{self.url}/security-advisories",
None,
)
def get_repository_advisory(self, ghsa: str) -> github.RepositoryAdvisory.RepositoryAdvisory:
"""
:calls: `GET /repos/{owner}/{repo}/security-advisories/{ghsa} <https://docs.github.com/en/rest/security-advisories/repository-advisories>`_
:param ghsa: string
:rtype: :class:`github.RepositoryAdvisory.RepositoryAdvisory`
"""
ghsa = urllib.parse.quote(ghsa)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/security-advisories/{ghsa}")
return github.RepositoryAdvisory.RepositoryAdvisory(self._requester, headers, data, completed=True)
def update_file(
self,
path: str,
message: str,
content: bytes | str,
sha: str,
branch: Opt[str] = NotSet,
committer: Opt[InputGitAuthor] = NotSet,
author: Opt[InputGitAuthor] = NotSet,
) -> dict[str, ContentFile | Commit]:
"""
This method updates a file in a repository.
:calls: `PUT /repos/{owner}/{repo}/contents/{path} <https://docs.github.com/en/rest/reference/repos#create-or-
update-file-contents>`_
:param path: string, Required. The content path.
:param message: string, Required. The commit message.
:param content: string, Required. The updated file content, either base64 encoded, or ready to be encoded.
:param sha: string, Required. The blob SHA of the file being replaced.
:param branch: string. The branch name. Default: the repository’s default branch (usually master)
:param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information
will be used. You must specify both a name and email.
:param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If
passed, you must specify both a name and email.
:rtype: { 'content': :class:`ContentFile <github.ContentFile.ContentFile>`:, 'commit': :class:`Commit
<github.Commit.Commit>`}
"""
assert isinstance(path, str)
assert isinstance(message, str)
assert isinstance(content, (str, bytes))
assert isinstance(sha, str)
assert is_optional(branch, str)
assert is_optional(author, github.InputGitAuthor)
assert is_optional(committer, github.InputGitAuthor)
if not isinstance(content, bytes):
content = content.encode("utf-8")
content = b64encode(content).decode("utf-8")
put_parameters: dict[str, Any] = {"message": message, "content": content, "sha": sha}
if is_defined(branch):
put_parameters["branch"] = branch
if is_defined(author):
put_parameters["author"] = author._identity
if is_defined(committer):
put_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"PUT",
f"{self.url}/contents/{urllib.parse.quote(path)}",
input=put_parameters,
)
return {
"commit": github.Commit.Commit(self._requester, headers, data["commit"], completed=True),
"content": github.ContentFile.ContentFile(self._requester, headers, data["content"], completed=False),
}
def delete_file(
self,
path: str,
message: str,
sha: str,
branch: Opt[str] = NotSet,
committer: Opt[InputGitAuthor] = NotSet,
author: Opt[InputGitAuthor] = NotSet,
) -> dict[str, Commit | _NotSetType]:
"""
This method deletes a file in a repository.
:calls: `DELETE /repos/{owner}/{repo}/contents/{path} <https://docs.github.com/en/rest/reference/repos#delete-a-
file>`_
:param path: string, Required. The content path.
:param message: string, Required. The commit message.
:param sha: string, Required. The blob SHA of the file being replaced.
:param branch: string. The branch name. Default: the repository’s default branch (usually master)
:param committer: InputGitAuthor, (optional), if no information is given the authenticated user's information
will be used. You must specify both a name and email.
:param author: InputGitAuthor, (optional), if omitted this will be filled in with committer information. If
passed, you must specify both a name and email.
:rtype: { 'content': :class:`null <NotSet>`:, 'commit': :class:`Commit <github.Commit.Commit>`}
"""
assert isinstance(path, str), "path must be str/unicode object"
assert isinstance(message, str), "message must be str/unicode object"
assert isinstance(sha, str), "sha must be a str/unicode object"
assert is_optional(branch, str), "branch must be a str/unicode object"
assert is_optional(author, github.InputGitAuthor), "author must be a github.InputGitAuthor object"
assert is_optional(committer, github.InputGitAuthor), "committer must be a github.InputGitAuthor object"
url_parameters: dict[str, Any] = {"message": message, "sha": sha}
if is_defined(branch):
url_parameters["branch"] = branch
if is_defined(author):
url_parameters["author"] = author._identity
if is_defined(committer):
url_parameters["committer"] = committer._identity
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
f"{self.url}/contents/{urllib.parse.quote(path)}",
input=url_parameters,
)
return {
"commit": github.Commit.Commit(self._requester, headers, data["commit"], completed=True),
"content": NotSet,
}
@deprecated(
reason="""
Repository.get_dir_contents() is deprecated, use
Repository.get_contents() instead.
"""
)
def get_dir_contents(self, path: str, ref: Opt[str] = NotSet) -> list[ContentFile]:
"""
:calls: `GET /repos/{owner}/{repo}/contents/{path} <https://docs.github.com/en/rest/reference/repos#contents>`_
"""
return self.get_contents(path, ref=ref) # type: ignore
def get_contributors(self, anon: Opt[str] = NotSet) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/contributors <https://docs.github.com/en/rest/reference/repos>`_
:param anon: string
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
url_parameters = dict()
if is_defined(anon):
url_parameters["anon"] = anon
return PaginatedList(
github.NamedUser.NamedUser,
self._requester,
f"{self.url}/contributors",
url_parameters,
)
def get_download(self, id: int) -> Download:
"""
:calls: `GET /repos/{owner}/{repo}/downloads/{id} <https://docs.github.com/en/rest/reference/repos>`_
:param id: integer
:rtype: :class:`github.Download.Download`
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/downloads/{id}")
return github.Download.Download(self._requester, headers, data, completed=True)
def get_downloads(self) -> PaginatedList[Download]:
"""
:calls: `GET /repos/{owner}/{repo}/downloads <https://docs.github.com/en/rest/reference/repos>`_
:rtype: :class:`PaginatedList` of :class:`github.Download.Download`
"""
return PaginatedList(github.Download.Download, self._requester, f"{self.url}/downloads", None)
def get_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /repos/{owner}/{repo}/events <https://docs.github.com/en/rest/reference/activity#events>`_
:rtype: :class:`PaginatedList` of :class:`github.Event.Event`
"""
return PaginatedList(github.Event.Event, self._requester, f"{self.url}/events", None)
def get_forks(self) -> PaginatedList[Repository]:
"""
:calls: `GET /repos/{owner}/{repo}/forks <https://docs.github.com/en/rest/reference/repos#forks>`_
:rtype: :class:`PaginatedList` of :class:`github.Repository.Repository`
"""
return PaginatedList(Repository, self._requester, f"{self.url}/forks", None)
def create_fork(
self,
organization: Organization | Opt[str] = NotSet,
name: Opt[str] = NotSet,
default_branch_only: Opt[bool] = NotSet,
) -> Repository:
"""
:calls: `POST /repos/{owner}/{repo}/forks <https://docs.github.com/en/rest/reference/repos#forks>`_
:param organization: :class:`github.Organization.Organization` or string
:param name: string
:param default_branch_only: bool
:rtype: :class:`github.Repository.Repository`
"""
post_parameters: dict[str, Any] = {}
if isinstance(organization, github.Organization.Organization):
post_parameters["organization"] = organization.login
elif isinstance(organization, str):
post_parameters["organization"] = organization
else:
assert is_undefined(organization), organization
assert is_optional(name, str), name
assert is_optional(default_branch_only, bool), default_branch_only
if is_defined(name):
post_parameters["name"] = name
if is_defined(default_branch_only):
post_parameters["default_branch_only"] = default_branch_only
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/forks",
input=post_parameters,
)
return Repository(self._requester, headers, data, completed=True)
def get_git_blob(self, sha: str) -> GitBlob:
"""
:calls: `GET /repos/{owner}/{repo}/git/blobs/{sha} <https://docs.github.com/en/rest/reference/git#blobs>`_
:param sha: string
:rtype: :class:`github.GitBlob.GitBlob`
"""
assert isinstance(sha, str), sha
sha = urllib.parse.quote(sha)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/git/blobs/{sha}")
return github.GitBlob.GitBlob(self._requester, headers, data, completed=True)
def get_git_commit(self, sha: str) -> GitCommit:
"""
:calls: `GET /repos/{owner}/{repo}/git/commits/{sha} <https://docs.github.com/en/rest/reference/git#commits>`_
:param sha: string
:rtype: :class:`github.GitCommit.GitCommit`
"""
assert isinstance(sha, str), sha
sha = urllib.parse.quote(sha)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/git/commits/{sha}")
return github.GitCommit.GitCommit(self._requester, headers, data, completed=True)
def get_git_ref(self, ref: str) -> GitRef:
"""
:calls: `GET /repos/{owner}/{repo}/git/refs/{ref} <https://docs.github.com/en/rest/reference/git#references>`_
:param ref: string
:rtype: :class:`github.GitRef.GitRef`
"""
prefix = "/git/refs/"
if not self._requester.FIX_REPO_GET_GIT_REF:
prefix = "/git/"
assert isinstance(ref, str), ref
ref = urllib.parse.quote(ref)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}{prefix}{ref}")
return github.GitRef.GitRef(self._requester, headers, data, completed=True)
def get_git_refs(self) -> PaginatedList[GitRef]:
"""
:calls: `GET /repos/{owner}/{repo}/git/refs <https://docs.github.com/en/rest/reference/git#references>`_
:rtype: :class:`PaginatedList` of :class:`github.GitRef.GitRef`
"""
return PaginatedList(github.GitRef.GitRef, self._requester, f"{self.url}/git/refs", None)
def get_git_matching_refs(self, ref: str) -> PaginatedList[GitRef]:
"""
:calls: `GET /repos/{owner}/{repo}/git/matching-refs/{ref} <https://docs.github.com/en/rest/reference/git#list-matching-references>`_
:rtype: :class:`PaginatedList` of :class:`github.GitRef.GitRef`
"""
assert isinstance(ref, str), ref
ref = urllib.parse.quote(ref)
return PaginatedList(
github.GitRef.GitRef,
self._requester,
f"{self.url}/git/matching-refs/{ref}",
None,
)
def get_git_tag(self, sha: str) -> GitTag:
"""
:calls: `GET /repos/{owner}/{repo}/git/tags/{sha} <https://docs.github.com/en/rest/reference/git#tags>`_
:param sha: string
:rtype: :class:`github.GitTag.GitTag`
"""
assert isinstance(sha, str), sha
sha = urllib.parse.quote(sha)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/git/tags/{sha}")
return github.GitTag.GitTag(self._requester, headers, data, completed=True)
def get_git_tree(self, sha: str, recursive: Opt[bool] = NotSet) -> GitTree:
"""
:calls: `GET /repos/{owner}/{repo}/git/trees/{sha} <https://docs.github.com/en/rest/reference/git#trees>`_
:param sha: string
:param recursive: bool
:rtype: :class:`github.GitTree.GitTree`
"""
assert isinstance(sha, str), sha
assert is_optional(recursive, bool), recursive
sha = urllib.parse.quote(sha)
url_parameters = dict()
if is_defined(recursive) and recursive:
# GitHub API requires the recursive parameter be set to 1.
url_parameters["recursive"] = 1
headers, data = self._requester.requestJsonAndCheck(
"GET", f"{self.url}/git/trees/{sha}", parameters=url_parameters
)
return github.GitTree.GitTree(self._requester, headers, data, completed=True)
def get_hook(self, id: int) -> Hook:
"""
:calls: `GET /repos/{owner}/{repo}/hooks/{id} <https://docs.github.com/en/rest/reference/repos#webhooks>`_
:param id: integer
:rtype: :class:`github.Hook.Hook`
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/hooks/{id}")
return github.Hook.Hook(self._requester, headers, data, completed=True)
def get_hooks(self) -> PaginatedList[Hook]:
"""
:calls: `GET /repos/{owner}/{repo}/hooks <https://docs.github.com/en/rest/reference/repos#webhooks>`_
:rtype: :class:`PaginatedList` of :class:`github.Hook.Hook`
"""
return PaginatedList(github.Hook.Hook, self._requester, f"{self.url}/hooks", None)
def get_hook_delivery(self, hook_id: int, delivery_id: int) -> github.HookDelivery.HookDelivery:
"""
:calls: `GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id} <https://docs.github.com/en/rest/webhooks/repo-deliveries>`_
:param hook_id: integer
:param delivery_id: integer
:rtype: :class:`github.HookDelivery.HookDelivery`
"""
assert isinstance(hook_id, int), hook_id
assert isinstance(delivery_id, int), delivery_id
headers, data = self._requester.requestJsonAndCheck(
"GET", f"{self.url}/hooks/{hook_id}/deliveries/{delivery_id}"
)
return github.HookDelivery.HookDelivery(self._requester, headers, data, completed=True)
def get_hook_deliveries(self, hook_id: int) -> PaginatedList[github.HookDelivery.HookDeliverySummary]:
"""
:calls: `GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries <https://docs.github.com/en/rest/webhooks/repo-deliveries>`_
:param hook_id: integer
:rtype: :class:`PaginatedList` of :class:`github.HookDelivery.HookDeliverySummary`
"""
assert isinstance(hook_id, int), hook_id
return PaginatedList(
github.HookDelivery.HookDeliverySummary,
self._requester,
f"{self.url}/hooks/{hook_id}/deliveries",
None,
)
def get_issue(self, number: int) -> Issue:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number} <https://docs.github.com/en/rest/reference/issues>`_
:param number: integer
:rtype: :class:`github.Issue.Issue`
"""
assert isinstance(number, int), number
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/issues/{number}")
return github.Issue.Issue(self._requester, headers, data, completed=True)
def get_issues(
self,
milestone: Milestone | Opt[str] = NotSet,
state: Opt[str] = NotSet,
assignee: NamedUser | Opt[str] = NotSet,
mentioned: Opt[NamedUser] = NotSet,
labels: Opt[list[str] | list[Label]] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
creator: Opt[NamedUser] = NotSet,
) -> PaginatedList[Issue]:
"""
:calls: `GET /repos/{owner}/{repo}/issues <https://docs.github.com/en/rest/reference/issues>`_
:param milestone: :class:`github.Milestone.Milestone` or "none" or "*"
:param state: string. `open`, `closed`, or `all`. If this is not set the GitHub API default behavior will be used. At the moment this is to return only open issues. This might change anytime on GitHub API side and it could be clever to explicitly specify the state value.
:param assignee: string or :class:`github.NamedUser.NamedUser` or "none" or "*"
:param mentioned: :class:`github.NamedUser.NamedUser`
:param labels: list of string or :class:`github.Label.Label`
:param sort: string
:param direction: string
:param since: datetime
:param creator: string or :class:`github.NamedUser.NamedUser`
:rtype: :class:`PaginatedList` of :class:`github.Issue.Issue`
"""
assert milestone in ["*", "none", NotSet] or isinstance(milestone, github.Milestone.Milestone), milestone
assert is_optional(state, str), state
assert is_optional(assignee, (str, github.NamedUser.NamedUser)), assignee
assert is_optional(mentioned, github.NamedUser.NamedUser), mentioned
assert is_optional_list(labels, (github.Label.Label, str)), labels
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(since, datetime), since
assert is_optional(creator, (str, github.NamedUser.NamedUser)), creator
url_parameters: dict[str, Any] = {}
if is_defined(milestone):
if isinstance(milestone, github.Milestone.Milestone):
url_parameters["milestone"] = milestone._identity
else:
url_parameters["milestone"] = milestone
if is_defined(state):
url_parameters["state"] = state
if is_defined(assignee):
if isinstance(assignee, github.NamedUser.NamedUser):
url_parameters["assignee"] = assignee._identity
else:
url_parameters["assignee"] = assignee
if is_defined(mentioned):
url_parameters["mentioned"] = mentioned._identity
if is_defined(labels):
url_parameters["labels"] = ",".join(
[label.name if isinstance(label, github.Label.Label) else label for label in labels] # type: ignore
)
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
if is_defined(creator):
if isinstance(creator, str):
url_parameters["creator"] = creator
else:
url_parameters["creator"] = creator._identity
return PaginatedList(github.Issue.Issue, self._requester, f"{self.url}/issues", url_parameters)
def get_issues_comments(
self,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[IssueComment]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/comments <https://docs.github.com/en/rest/reference/issues#comments>`_
:param sort: string
:param direction: string
:param since: datetime
:rtype: :class:`PaginatedList` of :class:`github.IssueComment.IssueComment`
"""
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(since, datetime), since
url_parameters = dict()
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(
github.IssueComment.IssueComment,
self._requester,
f"{self.url}/issues/comments",
url_parameters,
)
def get_issues_event(self, id: int) -> IssueEvent:
"""
:calls: `GET /repos/{owner}/{repo}/issues/events/{id} <https://docs.github.com/en/rest/reference/issues#events>`_
:param id: integer
:rtype: :class:`github.IssueEvent.IssueEvent`
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/issues/events/{id}",
headers={"Accept": Consts.mediaTypeLockReasonPreview},
)
return github.IssueEvent.IssueEvent(self._requester, headers, data, completed=True)
def get_issues_events(self) -> PaginatedList[IssueEvent]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/events <https://docs.github.com/en/rest/reference/issues#events>`_
:rtype: :class:`PaginatedList` of :class:`github.IssueEvent.IssueEvent`
"""
return PaginatedList(
github.IssueEvent.IssueEvent,
self._requester,
f"{self.url}/issues/events",
None,
headers={"Accept": Consts.mediaTypeLockReasonPreview},
)
def get_key(self, id: int) -> RepositoryKey:
"""
:calls: `GET /repos/{owner}/{repo}/keys/{id} <https://docs.github.com/en/rest/reference/repos#deploy-keys>`_
:param id: integer
:rtype: :class:`github.RepositoryKey.RepositoryKey`
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/keys/{id}")
return github.RepositoryKey.RepositoryKey(self._requester, headers, data, completed=True)
def get_keys(self) -> PaginatedList[RepositoryKey]:
"""
:calls: `GET /repos/{owner}/{repo}/keys <https://docs.github.com/en/rest/reference/repos#deploy-keys>`_
:rtype: :class:`PaginatedList` of :class:`github.RepositoryKey.RepositoryKey`
"""
return PaginatedList(
github.RepositoryKey.RepositoryKey,
self._requester,
f"{self.url}/keys",
None,
)
def get_label(self, name: str) -> Label:
"""
:calls: `GET /repos/{owner}/{repo}/labels/{name} <https://docs.github.com/en/rest/reference/issues#labels>`_
:param name: string
:rtype: :class:`github.Label.Label`
"""
assert isinstance(name, str), name
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/labels/{urllib.parse.quote(name)}")
return github.Label.Label(self._requester, headers, data, completed=True)
def get_labels(self) -> PaginatedList[Label]:
"""
:calls: `GET /repos/{owner}/{repo}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
:rtype: :class:`PaginatedList` of :class:`github.Label.Label`
"""
return PaginatedList(github.Label.Label, self._requester, f"{self.url}/labels", None)
def get_languages(self) -> dict[str, int]:
"""
:calls: `GET /repos/{owner}/{repo}/languages <https://docs.github.com/en/rest/reference/repos>`_
:rtype: dict of string to integer
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/languages")
return data
def get_license(self) -> ContentFile:
"""
:calls: `GET /repos/{owner}/{repo}/license <https://docs.github.com/en/rest/reference/licenses>`_
:rtype: :class:`github.ContentFile.ContentFile`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/license")
return github.ContentFile.ContentFile(self._requester, headers, data, completed=True)
def get_milestone(self, number: int) -> Milestone:
"""
:calls: `GET /repos/{owner}/{repo}/milestones/{number} <https://docs.github.com/en/rest/reference/issues#milestones>`_
:param number: integer
:rtype: :class:`github.Milestone.Milestone`
"""
assert isinstance(number, int), number
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/milestones/{number}")
return github.Milestone.Milestone(self._requester, headers, data, completed=True)
def get_milestones(
self,
state: Opt[str] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
) -> PaginatedList[Milestone]:
"""
:calls: `GET /repos/{owner}/{repo}/milestones <https://docs.github.com/en/rest/reference/issues#milestones>`_
:param state: string
:param sort: string
:param direction: string
:rtype: :class:`PaginatedList` of :class:`github.Milestone.Milestone`
"""
assert is_optional(state, str), state
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
url_parameters = dict()
if is_defined(state):
url_parameters["state"] = state
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
return PaginatedList(
github.Milestone.Milestone,
self._requester,
f"{self.url}/milestones",
url_parameters,
)
def get_network_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /networks/{owner}/{repo}/events <https://docs.github.com/en/rest/reference/activity#events>`_
:rtype: :class:`PaginatedList` of :class:`github.Event.Event`
"""
return PaginatedList(
github.Event.Event,
self._requester,
f"/networks/{self.owner.login}/{self.name}/events",
None,
)
def get_public_key(self, secret_type: str = "actions") -> PublicKey:
"""
:calls: `GET /repos/{owner}/{repo}/actions/secrets/public-key <https://docs.github.com/en/rest/reference/actions#get-a-repository-public-key>`_
:param secret_type: string options actions or dependabot
:rtype: :class:`github.PublicKey.PublicKey`
"""
assert secret_type in ["actions", "dependabot"], "secret_type should be actions or dependabot"
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/{secret_type}/secrets/public-key")
return github.PublicKey.PublicKey(self._requester, headers, data, completed=True)
def get_pull(self, number: int) -> PullRequest:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number} <https://docs.github.com/en/rest/reference/pulls>`_
:param number: integer
:rtype: :class:`github.PullRequest.PullRequest`
"""
assert isinstance(number, int), number
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/pulls/{number}")
return github.PullRequest.PullRequest(self._requester, headers, data, completed=True)
def get_pulls(
self,
state: Opt[str] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
base: Opt[str] = NotSet,
head: Opt[str] = NotSet,
) -> PaginatedList[PullRequest]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls <https://docs.github.com/en/rest/reference/pulls>`_
:param state: string
:param sort: string
:param direction: string
:param base: string
:param head: string
:rtype: :class:`PaginatedList` of :class:`github.PullRequest.PullRequest`
"""
assert is_optional(state, str), state
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(base, str), base
assert is_optional(head, str), head
url_parameters = dict()
if is_defined(state):
url_parameters["state"] = state
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
if is_defined(base):
url_parameters["base"] = base
if is_defined(head):
url_parameters["head"] = head
return PaginatedList(
github.PullRequest.PullRequest,
self._requester,
f"{self.url}/pulls",
url_parameters,
)
def get_pulls_comments(
self,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[PullRequestComment]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/comments <https://docs.github.com/en/rest/reference/pulls#comments>`_
:param sort: string
:param direction: string
:param since: datetime
:rtype: :class:`PaginatedList` of :class:`github.PullRequestComment.PullRequestComment`
"""
return self.get_pulls_review_comments(sort, direction, since)
def get_pulls_review_comments(
self,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[PullRequestComment]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/comments <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
:param sort: string 'created', 'updated', 'created_at'
:param direction: string 'asc' or 'desc'
:param since: datetime
:rtype: :class:`PaginatedList` of :class:`github.PullRequestComment.PullRequestComment`
"""
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(since, datetime), since
url_parameters = dict()
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(
github.PullRequestComment.PullRequestComment,
self._requester,
f"{self.url}/pulls/comments",
url_parameters,
)
def get_readme(self, ref: Opt[str] = NotSet) -> ContentFile:
"""
:calls: `GET /repos/{owner}/{repo}/readme <https://docs.github.com/en/rest/reference/repos#contents>`_
:param ref: string
:rtype: :class:`github.ContentFile.ContentFile`
"""
assert is_optional(ref, str), ref
url_parameters = dict()
if is_defined(ref):
url_parameters["ref"] = ref
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/readme", parameters=url_parameters)
return github.ContentFile.ContentFile(self._requester, headers, data, completed=True)
def get_self_hosted_runner(self, runner_id: int) -> SelfHostedActionsRunner:
"""
:calls: `GET /repos/{owner}/{repo}/actions/runners/{id} <https://docs.github.com/en/rest/reference/actions#get-a-self-hosted-runner-for-a-repository>`_
:param runner_id: int
:rtype: :class:`github.SelfHostedActionsRunner.SelfHostedActionsRunner`
"""
assert isinstance(runner_id, int), runner_id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/runners/{runner_id}")
return github.SelfHostedActionsRunner.SelfHostedActionsRunner(self._requester, headers, data, completed=True)
def get_self_hosted_runners(self) -> PaginatedList[SelfHostedActionsRunner]:
"""
:calls: `GET /repos/{owner}/{repo}/actions/runners <https://docs.github.com/en/rest/reference/actions#list-self-hosted-runners-for-a-repository>`_
:rtype: :class:`PaginatedList` of :class:`github.SelfHostedActionsRunner.SelfHostedActionsRunner`
"""
return PaginatedList(
github.SelfHostedActionsRunner.SelfHostedActionsRunner,
self._requester,
f"{self.url}/actions/runners",
None,
list_item="runners",
)
def get_source_import(self) -> SourceImport | None:
"""
:calls: `GET /repos/{owner}/{repo}/import <https://docs.github.com/en/rest/reference/migrations#source-imports>`_
"""
import_header = {"Accept": Consts.mediaTypeImportPreview}
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/import",
headers=import_header,
)
if not data:
return None
else:
return github.SourceImport.SourceImport(self._requester, headers, data, completed=True)
def get_stargazers(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/stargazers <https://docs.github.com/en/rest/reference/activity#starring>`_
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/stargazers", None)
def get_stargazers_with_dates(self) -> PaginatedList[Stargazer]:
"""
:calls: `GET /repos/{owner}/{repo}/stargazers <https://docs.github.com/en/rest/reference/activity#starring>`_
:rtype: :class:`PaginatedList` of :class:`github.Stargazer.Stargazer`
"""
return PaginatedList(
github.Stargazer.Stargazer,
self._requester,
f"{self.url}/stargazers",
None,
headers={"Accept": Consts.mediaTypeStarringPreview},
)
def get_stats_contributors(self) -> list[StatsContributor] | None:
"""
:calls: `GET /repos/{owner}/{repo}/stats/contributors <https://docs.github.com/en/rest/reference/repos#get-all-contributor-commit-activity>`_
:rtype: None or list of :class:`github.StatsContributor.StatsContributor`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/contributors")
if not data:
return None
else:
return [
github.StatsContributor.StatsContributor(self._requester, headers, attributes, completed=True)
for attributes in data
]
def get_stats_commit_activity(self) -> list[StatsCommitActivity] | None:
"""
:calls: `GET /repos/{owner}/{repo}/stats/commit_activity <https://docs.github.com/en/rest/reference/repos#get-the-last-year-of-commit-activity>`_
:rtype: None or list of :class:`github.StatsCommitActivity.StatsCommitActivity`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/commit_activity")
if not data:
return None
else:
return [
github.StatsCommitActivity.StatsCommitActivity(self._requester, headers, attributes, completed=True)
for attributes in data
]
def get_stats_code_frequency(self) -> list[StatsCodeFrequency] | None:
"""
:calls: `GET /repos/{owner}/{repo}/stats/code_frequency <https://docs.github.com/en/rest/reference/repos#get-the-weekly-commit-activity>`_
:rtype: None or list of :class:`github.StatsCodeFrequency.StatsCodeFrequency`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/code_frequency")
if not data:
return None
else:
return [
github.StatsCodeFrequency.StatsCodeFrequency(self._requester, headers, attributes, completed=True)
for attributes in data
]
def get_stats_participation(self) -> StatsParticipation | None:
"""
:calls: `GET /repos/{owner}/{repo}/stats/participation <https://docs.github.com/en/rest/reference/repos#get-the-weekly-commit-count>`_
:rtype: None or :class:`github.StatsParticipation.StatsParticipation`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/participation")
if not data:
return None
else:
return github.StatsParticipation.StatsParticipation(self._requester, headers, data, completed=True)
def get_stats_punch_card(self) -> StatsPunchCard | None:
"""
:calls: `GET /repos/{owner}/{repo}/stats/punch_card <https://docs.github.com/en/rest/reference/repos#get-the-hourly-commit-count-for-each-day>`_
:rtype: None or :class:`github.StatsPunchCard.StatsPunchCard`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/stats/punch_card")
if not data:
return None
else:
return github.StatsPunchCard.StatsPunchCard(self._requester, headers, data, completed=True)
def get_subscribers(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/subscribers <https://docs.github.com/en/rest/reference/activity#watching>`_
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/subscribers", None)
def get_tags(self) -> PaginatedList[Tag]:
"""
:calls: `GET /repos/{owner}/{repo}/tags <https://docs.github.com/en/rest/reference/repos>`_
:rtype: :class:`PaginatedList` of :class:`github.Tag.Tag`
"""
return PaginatedList(github.Tag.Tag, self._requester, f"{self.url}/tags", None)
def get_releases(self) -> PaginatedList[GitRelease]:
"""
:calls: `GET /repos/{owner}/{repo}/releases <https://docs.github.com/en/rest/reference/repos#list-releases>`_
:rtype: :class:`PaginatedList` of :class:`github.GitRelease.GitRelease`
"""
return PaginatedList(github.GitRelease.GitRelease, self._requester, f"{self.url}/releases", None)
def get_release(self, id: int | str) -> GitRelease:
"""
:calls: `GET /repos/{owner}/{repo}/releases/{id} <https://docs.github.com/en/rest/reference/repos#get-a-release>`_
:param id: int (release id), str (tag name)
:rtype: None or :class:`github.GitRelease.GitRelease`
"""
if isinstance(id, int):
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/{id}")
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
elif isinstance(id, str):
id = urllib.parse.quote(id)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/tags/{id}")
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def get_latest_release(self) -> GitRelease:
"""
:calls: `GET /repos/{owner}/{repo}/releases/latest <https://docs.github.com/en/rest/reference/repos#get-the-latest-release>`_
:rtype: :class:`github.GitRelease.GitRelease`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/latest")
return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
def get_teams(self) -> PaginatedList[Team]:
"""
:calls: `GET /repos/{owner}/{repo}/teams <https://docs.github.com/en/rest/reference/repos>`_
:rtype: :class:`PaginatedList` of :class:`github.Team.Team`
"""
return PaginatedList(github.Team.Team, self._requester, f"{self.url}/teams", None)
def get_topics(self) -> list[str]:
"""
:calls: `GET /repos/{owner}/{repo}/topics <https://docs.github.com/en/rest/reference/repos#replace-all-repository-topics>`_
:rtype: list of strings
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/topics",
headers={"Accept": Consts.mediaTypeTopicsPreview},
)
return data["names"]
def get_watchers(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/watchers <https://docs.github.com/en/rest/reference/activity#starring>`_
:rtype: :class:`PaginatedList` of :class:`github.NamedUser.NamedUser`
"""
return PaginatedList(github.NamedUser.NamedUser, self._requester, f"{self.url}/watchers", None)
def get_workflows(self) -> PaginatedList[Workflow]:
"""
:calls: `GET /repos/{owner}/{repo}/actions/workflows <https://docs.github.com/en/rest/reference/actions#workflows>`_
:rtype: :class:`PaginatedList` of :class:`github.Workflow.Workflow`
"""
return PaginatedList(
github.Workflow.Workflow,
self._requester,
f"{self.url}/actions/workflows",
None,
list_item="workflows",
)
def get_workflow(self, id_or_file_name: str | int) -> Workflow:
"""
:calls: `GET /repos/{owner}/{repo}/actions/workflows/{workflow_id} <https://docs.github.com/en/rest/reference/actions#workflows>`_
:param id_or_file_name: int or string. Can be either a workflow ID or a filename.
:rtype: :class:`github.Workflow.Workflow`
"""
assert isinstance(id_or_file_name, (int, str)), id_or_file_name
id_or_file_name = urllib.parse.quote(str(id_or_file_name))
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/workflows/{id_or_file_name}")
return github.Workflow.Workflow(self._requester, headers, data, completed=True)
def get_workflow_runs(
self,
actor: Opt[NamedUser] = NotSet,
branch: Opt[Branch] = NotSet,
event: Opt[str] = NotSet,
status: Opt[str] = NotSet,
exclude_pull_requests: Opt[bool] = NotSet,
head_sha: Opt[str] = NotSet,
created: Opt[str] = NotSet,
check_suite_id: Opt[int] = NotSet,
) -> PaginatedList[WorkflowRun]:
"""
:calls: `GET /repos/{owner}/{repo}/actions/runs <https://docs.github.com/en/rest/reference/actions#list-workflow-runs-for-a-repository>`_
:param actor: :class:`github.NamedUser.NamedUser` or string
:param branch: :class:`github.Branch.Branch` or string
:param event: string
:param status: string `queued`, `in_progress`, `completed`, `success`, `failure`, `neutral`, `cancelled`, `skipped`, `timed_out`, or `action_required`
:param exclude_pull_requests: bool
:param head_sha: string
:param created: string Created filter, see https://docs.github.com/en/search-github/getting-started-with-searching-on-github/understanding-the-search-syntax#query-for-dates
:param check_suite_id: int
:rtype: :class:`PaginatedList` of :class:`github.WorkflowRun.WorkflowRun`
"""
assert is_optional(actor, (github.NamedUser.NamedUser, str)), actor
assert is_optional(branch, (github.Branch.Branch, str)), branch
assert is_optional(event, str), event
assert is_optional(status, str), status
assert is_optional(exclude_pull_requests, bool), exclude_pull_requests
assert is_optional(head_sha, str), head_sha
assert is_optional(created, str), created
assert is_optional(check_suite_id, int), check_suite_id
url_parameters: dict[str, Any] = {}
if is_defined(actor):
if isinstance(actor, github.NamedUser.NamedUser):
url_parameters["actor"] = actor._identity
else:
url_parameters["actor"] = actor
if is_defined(branch):
if isinstance(branch, github.Branch.Branch):
url_parameters["branch"] = branch.name
else:
url_parameters["branch"] = branch
if is_defined(event):
url_parameters["event"] = event
if is_defined(status):
url_parameters["status"] = status
if is_defined(exclude_pull_requests) and exclude_pull_requests:
url_parameters["exclude_pull_requests"] = 1
if is_defined(head_sha):
url_parameters["head_sha"] = head_sha
if is_defined(created):
url_parameters["created"] = created
if is_defined(check_suite_id):
url_parameters["check_suite_id"] = check_suite_id
return PaginatedList(
github.WorkflowRun.WorkflowRun,
self._requester,
f"{self.url}/actions/runs",
url_parameters,
list_item="workflow_runs",
)
def get_workflow_run(self, id_: int) -> WorkflowRun:
"""
:calls: `GET /repos/{owner}/{repo}/actions/runs/{run_id} <https://docs.github.com/en/rest/reference/actions#workflow-runs>`_
:param id_: int
:rtype: :class:`github.WorkflowRun.WorkflowRun`
"""
assert isinstance(id_, int)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/runs/{id_}")
return github.WorkflowRun.WorkflowRun(self._requester, headers, data, completed=True)
def has_in_assignees(self, assignee: str | NamedUser) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/assignees/{assignee} <https://docs.github.com/en/rest/reference/issues#assignees>`_
:param assignee: string or :class:`github.NamedUser.NamedUser`
:rtype: bool
"""
assert isinstance(assignee, github.NamedUser.NamedUser) or isinstance(assignee, str), assignee
if isinstance(assignee, github.NamedUser.NamedUser):
assignee = assignee._identity
else:
assignee = urllib.parse.quote(assignee)
status, headers, data = self._requester.requestJson("GET", f"{self.url}/assignees/{assignee}")
return status == 204
def has_in_collaborators(self, collaborator: str | NamedUser) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/collaborators/{user} <https://docs.github.com/en/rest/reference/repos#collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: bool
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
else:
collaborator = urllib.parse.quote(collaborator)
status, headers, data = self._requester.requestJson("GET", f"{self.url}/collaborators/{collaborator}")
return status == 204
def _legacy_convert_issue(self, attributes: dict[str, Any]) -> dict[str, Any]:
convertedAttributes = {
"number": attributes["number"],
"url": f"/repos{urllib.parse.urlparse(attributes['html_url']).path}",
"user": {
"login": attributes["user"],
"url": f"/users/{attributes['user']}",
},
}
if "labels" in attributes: # pragma no branch
convertedAttributes["labels"] = [{"name": label} for label in attributes["labels"]]
for attr in ("title", "created_at", "comments", "body", "updated_at", "state"):
if attr in attributes: # pragma no branch
convertedAttributes[attr] = attributes[attr]
return convertedAttributes
def legacy_search_issues(self, state: str, keyword: str) -> list[Issue]:
"""
:calls: `GET /legacy/issues/search/{owner}/{repository}/{state}/{keyword} <https://docs.github.com/en/rest/reference/search>`_
:param state: "open" or "closed"
:param keyword: string
:rtype: List of :class:`github.Issue.Issue`
"""
assert state in ["open", "closed"], state
assert isinstance(keyword, str), keyword
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"/legacy/issues/search/{self.owner.login}/{self.name}/{state}/{urllib.parse.quote(keyword)}",
)
return [
github.Issue.Issue(
self._requester,
headers,
self._legacy_convert_issue(element),
completed=False,
)
for element in data["issues"]
]
def get_notifications(
self,
all: Opt[bool] = NotSet,
participating: Opt[bool] = NotSet,
since: Opt[datetime] = NotSet,
before: Opt[datetime] = NotSet,
) -> PaginatedList[Notification]:
"""
:calls: `GET /repos/{owner}/{repo}/notifications <https://docs.github.com/en/rest/reference/activity#notifications>`_
:param all: bool
:param participating: bool
:param since: datetime
:param before: datetime
:rtype: :class:`PaginatedList` of :class:`github.Notification.Notification`
"""
assert is_optional(all, bool), all
assert is_optional(participating, bool), participating
assert is_optional(since, datetime), since
assert is_optional(before, datetime), before
params = NotSet.remove_unset_items({"all": all, "participating": participating})
if is_defined(since):
params["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
if is_defined(before):
params["before"] = before.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(
github.Notification.Notification,
self._requester,
f"{self.url}/notifications",
params,
)
def mark_notifications_as_read(self, last_read_at: datetime = datetime.now(timezone.utc)) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/notifications <https://docs.github.com/en/rest/reference/activity#notifications>`_
:param last_read_at: datetime
"""
assert isinstance(last_read_at, datetime)
put_parameters = {"last_read_at": last_read_at.strftime("%Y-%m-%dT%H:%M:%SZ")}
headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/notifications", input=put_parameters)
def merge(self, base: str, head: str, commit_message: Opt[str] = NotSet) -> Commit | None:
"""
:calls: `POST /repos/{owner}/{repo}/merges <https://docs.github.com/en/rest/reference/repos#merging>`_
:param base: string
:param head: string
:param commit_message: string
:rtype: :class:`github.Commit.Commit`
"""
assert isinstance(base, str), base
assert isinstance(head, str), head
assert is_optional(commit_message, str), commit_message
post_parameters = {
"base": base,
"head": head,
}
if is_defined(commit_message):
post_parameters["commit_message"] = commit_message
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/merges", input=post_parameters)
if data is None:
return None
else:
return github.Commit.Commit(self._requester, headers, data, completed=True)
def replace_topics(self, topics: list[str]) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/topics <https://docs.github.com/en/rest/reference/repos>`_
:param topics: list of strings
:rtype: None
"""
post_parameters = {"names": topics}
headers, data = self._requester.requestJsonAndCheck(
"PUT",
f"{self.url}/topics",
headers={"Accept": Consts.mediaTypeTopicsPreview},
input=post_parameters,
)
def get_vulnerability_alert(self) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/vulnerability-alerts <https://docs.github.com/en/rest/reference/repos>`_
:rtype: bool
"""
status, _, _ = self._requester.requestJson(
"GET",
f"{self.url}/vulnerability-alerts",
headers={"Accept": Consts.vulnerabilityAlertsPreview},
)
return status == 204
def enable_vulnerability_alert(self) -> bool:
"""
:calls: `PUT /repos/{owner}/{repo}/vulnerability-alerts <https://docs.github.com/en/rest/reference/repos>`_
:rtype: bool
"""
status, _, _ = self._requester.requestJson(
"PUT",
f"{self.url}/vulnerability-alerts",
headers={"Accept": Consts.vulnerabilityAlertsPreview},
)
return status == 204
def disable_vulnerability_alert(self) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/vulnerability-alerts <https://docs.github.com/en/rest/reference/repos>`_
:rtype: bool
"""
status, _, _ = self._requester.requestJson(
"DELETE",
f"{self.url}/vulnerability-alerts",
headers={"Accept": Consts.vulnerabilityAlertsPreview},
)
return status == 204
def enable_automated_security_fixes(self) -> bool:
"""
:calls: `PUT /repos/{owner}/{repo}/automated-security-fixes <https://docs.github.com/en/rest/reference/repos>`_
:rtype: bool
"""
status, _, _ = self._requester.requestJson(
"PUT",
f"{self.url}/automated-security-fixes",
headers={"Accept": Consts.automatedSecurityFixes},
)
return status == 204
def disable_automated_security_fixes(self) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/automated-security-fixes <https://docs.github.com/en/rest/reference/repos>`_
:rtype: bool
"""
status, _, _ = self._requester.requestJson(
"DELETE",
f"{self.url}/automated-security-fixes",
headers={"Accept": Consts.automatedSecurityFixes},
)
return status == 204
def remove_from_collaborators(self, collaborator: str | NamedUser) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/collaborators/{user} <https://docs.github.com/en/rest/reference/repos#collaborators>`_
:param collaborator: string or :class:`github.NamedUser.NamedUser`
:rtype: None
"""
assert isinstance(collaborator, github.NamedUser.NamedUser) or isinstance(collaborator, str), collaborator
if isinstance(collaborator, github.NamedUser.NamedUser):
collaborator = collaborator._identity
else:
collaborator = urllib.parse.quote(collaborator)
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/collaborators/{collaborator}")
def remove_self_hosted_runner(self, runner: SelfHostedActionsRunner | int) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/actions/runners/{runner_id} <https://docs.github.com/en/rest/reference/actions#delete-a-self-hosted-runner-from-a-repository>`_
:param runner: int or :class:`github.SelfHostedActionsRunner.SelfHostedActionsRunner`
:rtype: bool
"""
assert isinstance(runner, github.SelfHostedActionsRunner.SelfHostedActionsRunner) or isinstance(
runner, int
), runner
if isinstance(runner, github.SelfHostedActionsRunner.SelfHostedActionsRunner):
runner = runner.id
status, _, _ = self._requester.requestJson("DELETE", f"{self.url}/actions/runners/{runner}")
return status == 204
def remove_autolink(self, autolink: Autolink | int) -> bool:
"""
: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
"""
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}" # type: ignore
)
return status == 204
def subscribe_to_hub(self, event: str, callback: str, secret: Opt[str] = NotSet) -> None:
"""
:calls: `POST /hub <https://docs.github.com/en/rest/reference/repos#pubsubhubbub>`_
:param event: string
:param callback: string
:param secret: string
:rtype: None
"""
return self._hub("subscribe", event, callback, secret)
def unsubscribe_from_hub(self, event: str, callback: str) -> None:
"""
:calls: `POST /hub <https://docs.github.com/en/rest/reference/repos#pubsubhubbub>`_
:param event: string
:param callback: string
:param secret: string
:rtype: None
"""
return self._hub("unsubscribe", event, callback, NotSet)
def create_check_suite(self, head_sha: str) -> CheckSuite:
"""
:calls: `POST /repos/{owner}/{repo}/check-suites <https://docs.github.com/en/rest/reference/checks#create-a-check-suite>`_
:param head_sha: string
:rtype: :class:`github.CheckSuite.CheckSuite`
"""
assert isinstance(head_sha, str), head_sha
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/check-suites",
input={"head_sha": head_sha},
)
return github.CheckSuite.CheckSuite(self._requester, headers, data, completed=True)
def get_check_suite(self, check_suite_id: int) -> CheckSuite:
"""
:calls: `GET /repos/{owner}/{repo}/check-suites/{check_suite_id} <https://docs.github.com/en/rest/reference/checks#get-a-check-suite>`_
:param check_suite_id: int
:rtype: :class:`github.CheckSuite.CheckSuite`
"""
assert isinstance(check_suite_id, int), check_suite_id
requestHeaders = {"Accept": "application/vnd.github.v3+json"}
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/check-suites/{check_suite_id}",
headers=requestHeaders,
)
return github.CheckSuite.CheckSuite(self._requester, headers, data, completed=True)
def update_check_suites_preferences(
self, auto_trigger_checks: list[dict[str, bool | int]]
) -> RepositoryPreferences:
"""
:calls: `PATCH /repos/{owner}/{repo}/check-suites/preferences <https://docs.github.com/en/rest/reference/checks#update-repository-preferences-for-check-suites>`_
:param auto_trigger_checks: list of dict
:rtype: :class:`github.RepositoryPreferences.RepositoryPreferences`
"""
assert all(isinstance(element, dict) for element in auto_trigger_checks), auto_trigger_checks
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
f"{self.url}/check-suites/preferences",
input={"auto_trigger_checks": auto_trigger_checks},
)
return github.RepositoryPreferences.RepositoryPreferences(self._requester, headers, data, completed=True)
def _hub(self, mode: str, event: str, callback: str, secret: Opt[str]) -> None:
assert isinstance(mode, str), mode
assert isinstance(event, str), event
assert isinstance(callback, str), callback
assert is_optional(secret, str), secret
event = urllib.parse.quote(event)
post_parameters = collections.OrderedDict()
post_parameters["hub.callback"] = callback
post_parameters["hub.topic"] = f"https://github.com/{self.full_name}/events/{event}"
post_parameters["hub.mode"] = mode
if is_defined(secret):
post_parameters["hub.secret"] = secret
headers, output = self._requester.requestMultipartAndCheck("POST", "/hub", input=post_parameters)
@property
def _identity(self) -> str:
return f"{self.owner.login}/{self.name}"
def get_release_asset(self, id: int) -> GitReleaseAsset:
assert isinstance(id, (int)), id
resp_headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/releases/assets/{id}")
return github.GitReleaseAsset.GitReleaseAsset(self._requester, resp_headers, data, completed=True)
def create_check_run(
self,
name: str,
head_sha: str,
details_url: Opt[str] = NotSet,
external_id: Opt[str] = NotSet,
status: Opt[str] = NotSet,
started_at: Opt[datetime] = NotSet,
conclusion: Opt[str] = NotSet,
completed_at: Opt[datetime] = NotSet,
output: Opt[dict[str, str | list[dict[str, str | int]]]] = NotSet,
actions: Opt[list[dict[str, str]]] = NotSet,
) -> CheckRun:
"""
:calls: `POST /repos/{owner}/{repo}/check-runs <https://docs.github.com/en/rest/reference/checks#create-a-check-run>`_
:param name: string
:param head_sha: string
:param details_url: string
:param external_id: string
:param status: string
:param started_at: datetime
:param conclusion: string
:param completed_at: datetime
:param output: dict
:param actions: list of dict
:rtype: :class:`github.CheckRun.CheckRun`
"""
assert isinstance(name, str), name
assert isinstance(head_sha, str), head_sha
assert is_optional(details_url, str), details_url
assert is_optional(external_id, str), external_id
assert is_optional(status, str), status
assert is_optional(started_at, datetime), started_at
assert is_optional(conclusion, str), conclusion
assert is_optional(completed_at, datetime), completed_at
assert is_optional(output, dict), output
assert is_optional_list(actions, dict), actions
post_parameters = NotSet.remove_unset_items(
{
"name": name,
"head_sha": head_sha,
"details_url": details_url,
"external_id": external_id,
"status": status,
"conclusion": conclusion,
"output": output,
"actions": actions,
}
)
if is_defined(started_at):
post_parameters["started_at"] = started_at.strftime("%Y-%m-%dT%H:%M:%SZ")
if is_defined(completed_at):
post_parameters["completed_at"] = completed_at.strftime("%Y-%m-%dT%H:%M:%SZ")
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/check-runs",
input=post_parameters,
)
return github.CheckRun.CheckRun(self._requester, headers, data, completed=True)
def get_check_run(self, check_run_id: int) -> CheckRun:
"""
:calls: `GET /repos/{owner}/{repo}/check-runs/{check_run_id} <https://docs.github.com/en/rest/reference/checks#get-a-check-run>`_
:param check_run_id: int
:rtype: :class:`github.CheckRun.CheckRun`
"""
assert isinstance(check_run_id, int), check_run_id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/check-runs/{check_run_id}")
return github.CheckRun.CheckRun(self._requester, headers, data, completed=True)
def get_artifacts(self, name: Opt[str] = NotSet) -> PaginatedList[Artifact]:
"""
:calls: `GET /repos/{owner}/{repo}/actions/artifacts <https://docs.github.com/en/rest/actions/artifacts#list-artifacts-for-a-repository>`_
:param name: str
:rtype: :class:`PaginatedList` of :class:`github.Artifact.Artifact`
"""
assert is_optional(name, str), name
param = {key: value for key, value in {"name": name}.items() if is_defined(value)}
return PaginatedList(
github.Artifact.Artifact,
self._requester,
f"{self.url}/actions/artifacts",
firstParams=param,
list_item="artifacts",
)
def get_artifact(self, artifact_id: int) -> Artifact:
"""
:calls: `GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id} <https://docs.github.com/en/rest/actions/artifacts#get-an-artifact>`_
:param artifact_id: int
:rtype: :class:`github.Artifact.Artifact`
"""
assert isinstance(artifact_id, int), artifact_id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/actions/artifacts/{artifact_id}")
return github.Artifact.Artifact(self._requester, headers, data, completed=True)
def get_codescan_alerts(self) -> PaginatedList[CodeScanAlert]:
"""
:calls: `GET https://api.github.com/repos/{owner}/{repo}/code-scanning/alerts <https://docs.github.com/en/rest/reference/code-scanning#list-code-scanning-alerts-for-a-repository>`_
:rtype: :class:`PaginatedList` of :class:`github.CodeScanAlert.CodeScanAlert`
"""
return PaginatedList(
github.CodeScanAlert.CodeScanAlert,
self._requester,
f"{self.url}/code-scanning/alerts",
None,
)
def get_environments(self) -> PaginatedList[Environment]:
"""
:calls: `GET /repositories/{self._repository.id}/environments/{self.environment_name}/environments <https://docs.github.com/en/rest/reference/deployments#get-all-environments>`_
:rtype: :class:`PaginatedList` of :class:`github.Environment.Environment`
"""
return PaginatedList(
Environment,
self._requester,
f"{self.url}/environments",
None,
attributesTransformer=PaginatedList.override_attributes(
{"environments_url": f"/repositories/{self.id}/environments"}
),
list_item="environments",
)
def get_environment(self, environment_name: str) -> Environment:
"""
:calls: `GET /repositories/{self._repository.id}/environments/{self.environment_name}/environments/{environment_name} <https://docs.github.com/en/rest/reference/deployments#get-an-environment>`_
:rtype: :class:`github.Environment.Environment`
"""
assert isinstance(environment_name, str), environment_name
environment_name = urllib.parse.quote(environment_name)
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/environments/{environment_name}")
data["environments_url"] = f"/repositories/{self.id}/environments"
return Environment(self._requester, headers, data, completed=True)
def create_environment(
self,
environment_name: str,
wait_timer: int = 0,
reviewers: list[ReviewerParams] = [],
deployment_branch_policy: EnvironmentDeploymentBranchPolicyParams | None = None,
) -> Environment:
"""
:calls: `PUT /repositories/{self._repository.id}/environments/{self.environment_name}/environments/{environment_name} <https://docs.github.com/en/rest/reference/deployments#create-or-update-an-environment>`_
:param environment_name: string
:param wait_timer: int
:param reviews: List[:class:github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicyParams]
:param deployment_branch_policy: Optional[:class:github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicyParams`]
:rtype: :class:`github.Environment.Environment`
"""
assert isinstance(environment_name, str), environment_name
assert isinstance(wait_timer, int)
assert isinstance(reviewers, list)
assert all(
[isinstance(reviewer, github.EnvironmentProtectionRuleReviewer.ReviewerParams) for reviewer in reviewers]
)
assert (
isinstance(
deployment_branch_policy,
github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicyParams,
)
or deployment_branch_policy is None
)
environment_name = urllib.parse.quote(environment_name)
put_parameters = {
"wait_timer": wait_timer,
"reviewers": [reviewer._asdict() for reviewer in reviewers],
"deployment_branch_policy": deployment_branch_policy._asdict() if deployment_branch_policy else None,
}
headers, data = self._requester.requestJsonAndCheck(
"PUT", f"{self.url}/environments/{environment_name}", input=put_parameters
)
data["environments_url"] = f"/repositories/{self.id}/environments"
return Environment(self._requester, headers, data, completed=True)
def delete_environment(self, environment_name: str) -> None:
"""
:calls: `DELETE /repositories/{self._repository.id}/environments/{self.environment_name}/environments/{environment_name} <https://docs.github.com/en/rest/reference/deployments#delete-an-environment>`_
:param environment_name: string
:rtype: None
"""
assert isinstance(environment_name, str), environment_name
environment_name = urllib.parse.quote(environment_name)
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/environments/{environment_name}")
def get_dependabot_alerts(
self,
state: Opt[str] = NotSet,
severity: Opt[str] = NotSet,
ecosystem: Opt[str] = NotSet,
package: Opt[str] = NotSet,
manifest: Opt[str] = NotSet,
scope: Opt[str] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
) -> PaginatedList[DependabotAlert]:
"""
:calls: `GET /repos/{owner}/{repo}/dependabot/alerts <https://docs.github.com/en/rest/dependabot/alerts#list-dependabot-alerts-for-a-repository>`_
:param state: Optional string
:param severity: Optional string
:param ecosystem: Optional string
:param package: Optional string
:param manifest: Optional string
:param scope: Optional string
:param sort: Optional string
:param direction: Optional string
:rtype: :class:`PaginatedList` of :class:`github.DependabotAlert.DependabotAlert`
"""
allowed_states = ["auto_dismissed", "dismissed", "fixed", "open"]
allowed_severities = ["low", "medium", "high", "critical"]
allowed_ecosystems = ["composer", "go", "maven", "npm", "nuget", "pip", "pub", "rubygems", "rust"]
allowed_scopes = ["development", "runtime"]
allowed_sorts = ["created", "updated"]
allowed_directions = ["asc", "desc"]
assert state in allowed_states + [NotSet], f"State can be one of {', '.join(allowed_states)}"
assert severity in allowed_severities + [NotSet], f"Severity can be one of {', '.join(allowed_severities)}"
assert ecosystem in allowed_ecosystems + [NotSet], f"Ecosystem can be one of {', '.join(allowed_ecosystems)}"
assert scope in allowed_scopes + [NotSet], f"Scope can be one of {', '.join(allowed_scopes)}"
assert sort in allowed_sorts + [NotSet], f"Sort can be one of {', '.join(allowed_sorts)}"
assert direction in allowed_directions + [NotSet], f"Direction can be one of {', '.join(allowed_directions)}"
url_parameters = NotSet.remove_unset_items(
{
"state": state,
"severity": severity,
"ecosystem": ecosystem,
"package": package,
"manifest": manifest,
"scope": scope,
"sort": sort,
"direction": direction,
}
)
return PaginatedList(
github.DependabotAlert.DependabotAlert,
self._requester,
f"{self.url}/dependabot/alerts",
url_parameters,
)
def get_dependabot_alert(self, number: int) -> DependabotAlert:
"""
:calls: `GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number} <https://docs.github.com/en/rest/dependabot/alerts#get-a-dependabot-alert>`_
:param number: int
:rtype: :class:`github.DependabotAlert.DependabotAlert`
"""
assert isinstance(number, int), number
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/dependabot/alerts/{number}")
return github.DependabotAlert.DependabotAlert(self._requester, headers, data, completed=True)
def update_dependabot_alert(
self, number: int, state: str, dismissed_reason: Opt[str] = NotSet, dismissed_comment: Opt[str] = NotSet
) -> DependabotAlert:
"""
:calls: `PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number} <https://docs.github.com/en/rest/dependabot/alerts#update-a-dependabot-alert>`_
:param number: int
:param state: string
:param dismissed_reason: Optional string
:param dismissed_comment: Optional string
:rtype: :class:`github.DependabotAlert.DependabotAlert`
"""
assert isinstance(number, int), number
assert isinstance(state, str), state
assert state in ["dismissed", "open"], "State can be one of ['dismissed', 'open']"
if state == "dismissed":
assert is_defined(dismissed_reason)
assert dismissed_reason in [
"fix_started",
"inaccurate",
"no_bandwidth",
"not_used",
"tolerable_risk",
], "Dismissed reason can be one of ['fix_started', 'inaccurate', 'no_bandwidth', 'not_used', 'tolerable_risk']"
assert is_optional(dismissed_comment, str), dismissed_comment
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
f"{self.url}/dependabot/alerts/{number}",
input=NotSet.remove_unset_items(
{"state": state, "dismissed_reason": dismissed_reason, "dismissed_comment": dismissed_comment}
),
)
return github.DependabotAlert.DependabotAlert(self._requester, headers, data, completed=True)
def get_custom_properties(self) -> dict[str, None | str | list]:
"""
:calls: `GET /repos/{owner}/{repo}/properties/values <https://docs.github.com/en/rest/repos/custom-properties#get-all-custom-property-values-for-a-repository>`_
:rtype: dict[str, None | str | list]
"""
url = f"{self.url}/properties/values"
_, data = self._requester.requestJsonAndCheck("GET", url)
custom_properties = {p["property_name"]: p["value"] for p in data}
self._custom_properties = self._makeDictAttribute(custom_properties)
return custom_properties
def update_custom_properties(self, properties: dict[str, None | str | list]) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/properties/values <https://docs.github.com/en/rest/repos/custom-properties#create-or-update-custom-property-values-for-a-repository>`_
:rtype: None
"""
assert all(isinstance(v, (type(None), str, list)) for v in properties.values()), properties
url = f"{self.url}/properties/values"
patch_parameters: dict[str, list] = {
"properties": [{"property_name": k, "value": v} for k, v in properties.items()]
}
self._requester.requestJsonAndCheck("PATCH", url, input=patch_parameters)
def _initAttributes(self) -> None:
self._allow_auto_merge: Attribute[bool] = NotSet
self._allow_forking: Attribute[bool] = NotSet
self._allow_merge_commit: Attribute[bool] = NotSet
self._allow_rebase_merge: Attribute[bool] = NotSet
self._allow_squash_merge: Attribute[bool] = NotSet
self._allow_update_branch: Attribute[bool] = NotSet
self._archived: Attribute[bool] = NotSet
self._archive_url: Attribute[str] = NotSet
self._assignees_url: Attribute[str] = NotSet
self._blobs_url: Attribute[str] = NotSet
self._branches_url: Attribute[str] = NotSet
self._clone_url: Attribute[str] = NotSet
self._collaborators_url: Attribute[str] = NotSet
self._comments_url: Attribute[str] = NotSet
self._commits_url: Attribute[str] = NotSet
self._compare_url: Attribute[str] = NotSet
self._contents_url: Attribute[str] = NotSet
self._contributors_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._custom_properties: Attribute[dict[str, None | str | list]] = NotSet # type: ignore
self._default_branch: Attribute[str] = NotSet
self._delete_branch_on_merge: Attribute[bool] = NotSet
self._deployments_url: Attribute[str] = NotSet
self._description: Attribute[str] = NotSet
self._downloads_url: Attribute[str] = NotSet
self._events_url: Attribute[str] = NotSet
self._fork: Attribute[bool] = NotSet
self._forks: Attribute[int] = NotSet
self._forks_count: Attribute[int] = NotSet
self._forks_url: Attribute[str] = NotSet
self._full_name: Attribute[str] = NotSet
self._git_commits_url: Attribute[str] = NotSet
self._git_refs_url: Attribute[str] = NotSet
self._git_tags_url: Attribute[str] = NotSet
self._git_url: Attribute[str] = NotSet
self._has_downloads: Attribute[bool] = NotSet
self._has_issues: Attribute[bool] = NotSet
self._has_pages: Attribute[bool] = NotSet
self._has_projects: Attribute[bool] = NotSet
self._has_wiki: Attribute[bool] = NotSet
self._has_discussions: Attribute[bool] = NotSet
self._homepage: Attribute[str] = NotSet
self._hooks_url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._is_template: Attribute[bool] = NotSet
self._issue_comment_url: Attribute[str] = NotSet
self._issue_events_url: Attribute[str] = NotSet
self._issues_url: Attribute[str] = NotSet
self._keys_url: Attribute[str] = NotSet
self._labels_url: Attribute[str] = NotSet
self._language: Attribute[str] = NotSet
self._languages_url: Attribute[str] = NotSet
self._license: Attribute[License] = NotSet
self._master_branch: Attribute[str] = NotSet
self._merge_commit_message: Attribute[str] = NotSet
self._merge_commit_title: Attribute[str] = NotSet
self._merges_url: Attribute[str] = NotSet
self._milestones_url: Attribute[str] = NotSet
self._mirror_url: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
self._network_count: Attribute[int] = NotSet
self._notifications_url: Attribute[str] = NotSet
self._open_issues: Attribute[int] = NotSet
self._open_issues_count: Attribute[int] = NotSet
self._organization: Attribute[Organization] = NotSet
self._owner: Attribute[NamedUser] = NotSet
self._parent: Attribute[Repository] = NotSet
self._permissions: Attribute[Permissions] = NotSet
self._private: Attribute[bool] = NotSet
self._pulls_url: Attribute[str] = NotSet
self._pushed_at: Attribute[datetime] = NotSet
self._releases_url: Attribute[str] = NotSet
self._security_and_analysis: Attribute[SecurityAndAnalysis] = NotSet
self._size: Attribute[int] = NotSet
self._source: Attribute[Repository] = NotSet
self._squash_merge_commit_message: Attribute[str] = NotSet
self._squash_merge_commit_title: Attribute[str] = NotSet
self._ssh_url: Attribute[str] = NotSet
self._stargazers_count: Attribute[int] = NotSet
self._stargazers_url: Attribute[str] = NotSet
self._statuses_url: Attribute[str] = NotSet
self._subscribers_url: Attribute[str] = NotSet
self._subscribers_count: Attribute[int] = NotSet
self._subscription_url: Attribute[str] = NotSet
self._svn_url: Attribute[str] = NotSet
self._tags_url: Attribute[str] = NotSet
self._teams_url: Attribute[str] = NotSet
self._topics: Attribute[list[str]] = NotSet
self._trees_url: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._use_squash_pr_title_as_default: Attribute[bool] = NotSet
self._visibility: Attribute[str] = NotSet
self._watchers: Attribute[int] = NotSet
self._watchers_count: Attribute[int] = NotSet
self._web_commit_signoff_required: Attribute[bool] = NotSet
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "allow_auto_merge" in attributes: # pragma no branch
self._allow_auto_merge = self._makeBoolAttribute(attributes["allow_auto_merge"])
if "allow_forking" in attributes: # pragma no branch
self._allow_forking = self._makeBoolAttribute(attributes["allow_forking"])
if "allow_merge_commit" in attributes: # pragma no branch
self._allow_merge_commit = self._makeBoolAttribute(attributes["allow_merge_commit"])
if "allow_rebase_merge" in attributes: # pragma no branch
self._allow_rebase_merge = self._makeBoolAttribute(attributes["allow_rebase_merge"])
if "allow_squash_merge" in attributes: # pragma no branch
self._allow_squash_merge = self._makeBoolAttribute(attributes["allow_squash_merge"])
if "allow_update_branch" in attributes: # pragma no branch
self._allow_update_branch = self._makeBoolAttribute(attributes["allow_update_branch"])
if "archived" in attributes: # pragma no branch
self._archived = self._makeBoolAttribute(attributes["archived"])
if "archive_url" in attributes: # pragma no branch
self._archive_url = self._makeStringAttribute(attributes["archive_url"])
if "assignees_url" in attributes: # pragma no branch
self._assignees_url = self._makeStringAttribute(attributes["assignees_url"])
if "blobs_url" in attributes: # pragma no branch
self._blobs_url = self._makeStringAttribute(attributes["blobs_url"])
if "branches_url" in attributes: # pragma no branch
self._branches_url = self._makeStringAttribute(attributes["branches_url"])
if "clone_url" in attributes: # pragma no branch
self._clone_url = self._makeStringAttribute(attributes["clone_url"])
if "collaborators_url" in attributes: # pragma no branch
self._collaborators_url = self._makeStringAttribute(attributes["collaborators_url"])
if "comments_url" in attributes: # pragma no branch
self._comments_url = self._makeStringAttribute(attributes["comments_url"])
if "commits_url" in attributes: # pragma no branch
self._commits_url = self._makeStringAttribute(attributes["commits_url"])
if "compare_url" in attributes: # pragma no branch
self._compare_url = self._makeStringAttribute(attributes["compare_url"])
if "contents_url" in attributes: # pragma no branch
self._contents_url = self._makeStringAttribute(attributes["contents_url"])
if "contributors_url" in attributes: # pragma no branch
self._contributors_url = self._makeStringAttribute(attributes["contributors_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "custom_properties" in attributes: # pragma no branch
self._custom_properties = self._makeDictAttribute(attributes["custom_properties"])
if "default_branch" in attributes: # pragma no branch
self._default_branch = self._makeStringAttribute(attributes["default_branch"])
if "delete_branch_on_merge" in attributes: # pragma no branch
self._delete_branch_on_merge = self._makeBoolAttribute(attributes["delete_branch_on_merge"])
if "deployments_url" in attributes: # pragma no branch
self._deployments_url = self._makeStringAttribute(attributes["deployments_url"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "downloads_url" in attributes: # pragma no branch
self._downloads_url = self._makeStringAttribute(attributes["downloads_url"])
if "events_url" in attributes: # pragma no branch
self._events_url = self._makeStringAttribute(attributes["events_url"])
if "fork" in attributes: # pragma no branch
self._fork = self._makeBoolAttribute(attributes["fork"])
if "forks" in attributes: # pragma no branch
self._forks = self._makeIntAttribute(attributes["forks"])
if "forks_count" in attributes: # pragma no branch
self._forks_count = self._makeIntAttribute(attributes["forks_count"])
if "forks_url" in attributes: # pragma no branch
self._forks_url = self._makeStringAttribute(attributes["forks_url"])
if "full_name" in attributes: # pragma no branch
self._full_name = self._makeStringAttribute(attributes["full_name"])
if "git_commits_url" in attributes: # pragma no branch
self._git_commits_url = self._makeStringAttribute(attributes["git_commits_url"])
if "git_refs_url" in attributes: # pragma no branch
self._git_refs_url = self._makeStringAttribute(attributes["git_refs_url"])
if "git_tags_url" in attributes: # pragma no branch
self._git_tags_url = self._makeStringAttribute(attributes["git_tags_url"])
if "git_url" in attributes: # pragma no branch
self._git_url = self._makeStringAttribute(attributes["git_url"])
if "has_downloads" in attributes: # pragma no branch
self._has_downloads = self._makeBoolAttribute(attributes["has_downloads"])
if "has_issues" in attributes: # pragma no branch
self._has_issues = self._makeBoolAttribute(attributes["has_issues"])
if "has_pages" in attributes: # pragma no branch
self._has_pages = self._makeBoolAttribute(attributes["has_pages"])
if "has_projects" in attributes: # pragma no branch
self._has_projects = self._makeBoolAttribute(attributes["has_projects"])
if "has_wiki" in attributes: # pragma no branch
self._has_wiki = self._makeBoolAttribute(attributes["has_wiki"])
if "has_discussions" in attributes: # pragma no branch
self._has_discussions = self._makeBoolAttribute(attributes["has_discussions"])
if "homepage" in attributes: # pragma no branch
self._homepage = self._makeStringAttribute(attributes["homepage"])
if "hooks_url" in attributes: # pragma no branch
self._hooks_url = self._makeStringAttribute(attributes["hooks_url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "is_template" in attributes: # pragma no branch
self._is_template = self._makeBoolAttribute(attributes["is_template"])
if "issue_comment_url" in attributes: # pragma no branch
self._issue_comment_url = self._makeStringAttribute(attributes["issue_comment_url"])
if "issue_events_url" in attributes: # pragma no branch
self._issue_events_url = self._makeStringAttribute(attributes["issue_events_url"])
if "issues_url" in attributes: # pragma no branch
self._issues_url = self._makeStringAttribute(attributes["issues_url"])
if "keys_url" in attributes: # pragma no branch
self._keys_url = self._makeStringAttribute(attributes["keys_url"])
if "labels_url" in attributes: # pragma no branch
self._labels_url = self._makeStringAttribute(attributes["labels_url"])
if "language" in attributes: # pragma no branch
self._language = self._makeStringAttribute(attributes["language"])
if "languages_url" in attributes: # pragma no branch
self._languages_url = self._makeStringAttribute(attributes["languages_url"])
if "license" in attributes: # pragma no branch
self._license = self._makeClassAttribute(github.License.License, attributes["license"])
if "master_branch" in attributes: # pragma no branch
self._master_branch = self._makeStringAttribute(attributes["master_branch"])
if "merges_url" in attributes: # pragma no branch
self._merges_url = self._makeStringAttribute(attributes["merges_url"])
if "merge_commit_message" in attributes: # pragma no branch
self._merge_commit_message = self._makeStringAttribute(attributes["merge_commit_message"])
if "merge_commit_title" in attributes: # pragma no branch
self._merge_commit_title = self._makeStringAttribute(attributes["merge_commit_title"])
if "milestones_url" in attributes: # pragma no branch
self._milestones_url = self._makeStringAttribute(attributes["milestones_url"])
if "mirror_url" in attributes: # pragma no branch
self._mirror_url = self._makeStringAttribute(attributes["mirror_url"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "network_count" in attributes: # pragma no branch
self._network_count = self._makeIntAttribute(attributes["network_count"])
if "notifications_url" in attributes: # pragma no branch
self._notifications_url = self._makeStringAttribute(attributes["notifications_url"])
if "open_issues" in attributes: # pragma no branch
self._open_issues = self._makeIntAttribute(attributes["open_issues"])
if "open_issues_count" in attributes: # pragma no branch
self._open_issues_count = self._makeIntAttribute(attributes["open_issues_count"])
if "organization" in attributes: # pragma no branch
self._organization = self._makeClassAttribute(github.Organization.Organization, attributes["organization"])
if "owner" in attributes: # pragma no branch
self._owner = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["owner"])
if "parent" in attributes: # pragma no branch
self._parent = self._makeClassAttribute(Repository, attributes["parent"])
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeClassAttribute(github.Permissions.Permissions, attributes["permissions"])
if "private" in attributes: # pragma no branch
self._private = self._makeBoolAttribute(attributes["private"])
if "pulls_url" in attributes: # pragma no branch
self._pulls_url = self._makeStringAttribute(attributes["pulls_url"])
if "pushed_at" in attributes: # pragma no branch
self._pushed_at = self._makeDatetimeAttribute(attributes["pushed_at"])
if "releases_url" in attributes: # pragma no branch
self._releases_url = self._makeStringAttribute(attributes["releases_url"])
if "security_and_analysis" in attributes: # pragma no branch
self._security_and_analysis = self._makeClassAttribute(
github.SecurityAndAnalysis.SecurityAndAnalysis, attributes["security_and_analysis"]
)
if "size" in attributes: # pragma no branch
self._size = self._makeIntAttribute(attributes["size"])
if "source" in attributes: # pragma no branch
self._source = self._makeClassAttribute(Repository, attributes["source"])
if "squash_merge_commit_message" in attributes: # pragma no branch
self._squash_merge_commit_message = self._makeStringAttribute(attributes["squash_merge_commit_message"])
if "squash_merge_commit_title" in attributes: # pragma no branch
self._squash_merge_commit_title = self._makeStringAttribute(attributes["squash_merge_commit_title"])
if "ssh_url" in attributes: # pragma no branch
self._ssh_url = self._makeStringAttribute(attributes["ssh_url"])
if "stargazers_count" in attributes: # pragma no branch
self._stargazers_count = self._makeIntAttribute(attributes["stargazers_count"])
if "stargazers_url" in attributes: # pragma no branch
self._stargazers_url = self._makeStringAttribute(attributes["stargazers_url"])
if "statuses_url" in attributes: # pragma no branch
self._statuses_url = self._makeStringAttribute(attributes["statuses_url"])
if "subscribers_url" in attributes: # pragma no branch
self._subscribers_url = self._makeStringAttribute(attributes["subscribers_url"])
if "subscribers_count" in attributes: # pragma no branch
self._subscribers_count = self._makeIntAttribute(attributes["subscribers_count"])
if "subscription_url" in attributes: # pragma no branch
self._subscription_url = self._makeStringAttribute(attributes["subscription_url"])
if "svn_url" in attributes: # pragma no branch
self._svn_url = self._makeStringAttribute(attributes["svn_url"])
if "tags_url" in attributes: # pragma no branch
self._tags_url = self._makeStringAttribute(attributes["tags_url"])
if "teams_url" in attributes: # pragma no branch
self._teams_url = self._makeStringAttribute(attributes["teams_url"])
if "trees_url" in attributes: # pragma no branch
self._trees_url = self._makeStringAttribute(attributes["trees_url"])
if "topics" in attributes: # pragma no branch
self._topics = self._makeListOfStringsAttribute(attributes["topics"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "use_squash_pr_title_as_default" in attributes: # pragma no branch
self._use_squash_pr_title_as_default = self._makeBoolAttribute(attributes["use_squash_pr_title_as_default"])
if "visibility" in attributes: # pragma no branch
self._visibility = self._makeStringAttribute(attributes["visibility"])
if "watchers" in attributes: # pragma no branch
self._watchers = self._makeIntAttribute(attributes["watchers"])
if "watchers_count" in attributes: # pragma no branch
self._watchers_count = self._makeIntAttribute(attributes["watchers_count"])
if "web_commit_signoff_required" in attributes: # pragma no branch
self._web_commit_signoff_required = self._makeBoolAttribute(attributes["web_commit_signoff_required"])
| 195,466
|
Python
|
.py
| 4,085
| 38.863158
| 279
| 0.627652
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,424
|
GithubException.py
|
PyGithub_PyGithub/github/GithubException.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Cameron White <cawhite@pdx.edu> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 humbug <bah> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2022 Liuyang Wan <tsfdye@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 json
from typing import Any, Dict, List, Optional, Tuple, Type, Union
class GithubException(Exception):
"""
Error handling in PyGithub is done with exceptions. This class is the base of all exceptions raised by PyGithub
(but :class:`github.GithubException.BadAttributeException`).
Some other types of exceptions might be raised by underlying libraries, for example for network-related issues.
"""
def __init__(
self,
status: int,
data: Any = None,
headers: Optional[Dict[str, str]] = None,
message: Optional[str] = None,
):
super().__init__()
self.__status = status
self.__data = data
self.__headers = headers
self.__message = message
self.args = (status, data, headers, message)
@property
def message(self) -> Optional[str]:
return self.__message
@property
def status(self) -> int:
"""
The status returned by the Github API.
"""
return self.__status
@property
def data(self) -> Any:
"""
The (decoded) data returned by the Github API.
"""
return self.__data
@property
def headers(self) -> Optional[Dict[str, str]]:
"""
The headers returned by the Github API.
"""
return self.__headers
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.__str__()})"
def __str__(self) -> str:
if self.__message:
msg = f"{self.__message}: {self.status}"
else:
msg = f"{self.status}"
if self.data is not None:
msg += " " + json.dumps(self.data)
return msg
class BadCredentialsException(GithubException):
"""
Exception raised in case of bad credentials (when Github API replies with a 401 or 403 HTML status)
"""
class UnknownObjectException(GithubException):
"""
Exception raised when a non-existing object is requested (when Github API replies with a 404 HTML status)
"""
class BadUserAgentException(GithubException):
"""
Exception raised when request is sent with a bad user agent header (when Github API replies with a 403 bad user
agent HTML status)
"""
class RateLimitExceededException(GithubException):
"""
Exception raised when the rate limit is exceeded (when Github API replies with a 403 rate limit exceeded HTML
status)
"""
class BadAttributeException(Exception):
"""
Exception raised when Github returns an attribute with the wrong type.
"""
def __init__(
self,
actualValue: Any,
expectedType: Union[
Dict[Tuple[Type[str], Type[str]], Type[dict]],
Tuple[Type[str], Type[str]],
List[Type[dict]],
List[Tuple[Type[str], Type[str]]],
],
transformationException: Optional[Exception],
):
self.__actualValue = actualValue
self.__expectedType = expectedType
self.__transformationException = transformationException
@property
def actual_value(self) -> Any:
"""
The value returned by Github.
"""
return self.__actualValue
@property
def expected_type(
self,
) -> Union[
List[Type[dict]],
Tuple[Type[str], Type[str]],
Dict[Tuple[Type[str], Type[str]], Type[dict]],
List[Tuple[Type[str], Type[str]]],
]:
"""
The type PyGithub expected.
"""
return self.__expectedType
@property
def transformation_exception(self) -> Optional[Exception]:
"""
The exception raised when PyGithub tried to parse the value.
"""
return self.__transformationException
class TwoFactorException(GithubException):
"""
Exception raised when Github requires a onetime password for two-factor authentication.
"""
class IncompletableObject(GithubException):
"""
Exception raised when we can not request an object from Github because the data returned did not include a URL.
"""
| 7,175
|
Python
|
.py
| 159
| 39.421384
| 115
| 0.543385
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,425
|
Environment.py
|
PyGithub_PyGithub/github/Environment.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 alson <git@alm.nufan.net> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.EnvironmentDeploymentBranchPolicy
import github.EnvironmentProtectionRule
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
from github.PaginatedList import PaginatedList
from github.PublicKey import PublicKey
from github.Secret import Secret
from github.Variable import Variable
if TYPE_CHECKING:
from github.EnvironmentDeploymentBranchPolicy import EnvironmentDeploymentBranchPolicy
from github.EnvironmentProtectionRule import EnvironmentProtectionRule
class Environment(CompletableGithubObject):
"""
This class represents Environment.
The reference can be found here
https://docs.github.com/en/rest/reference/deployments#environments
"""
def _initAttributes(self) -> None:
self._created_at: Attribute[datetime] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._name: Attribute[str] = NotSet
self._node_id: Attribute[str] = NotSet
self._protection_rules: Attribute[list[EnvironmentProtectionRule]] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._environments_url: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
self._deployment_branch_policy: Attribute[EnvironmentDeploymentBranchPolicy] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
@property
def protection_rules(
self,
) -> list[EnvironmentProtectionRule]:
self._completeIfNotSet(self._protection_rules)
return self._protection_rules.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def environments_url(self) -> str:
"""
:type: string
"""
return self._environments_url.value
@property
def url(self) -> str:
"""
:type: string
"""
# Construct url from environments_url and name, if self._url. is not set
if self._url is NotSet:
self._url = self._makeStringAttribute(self.environments_url + "/" + self.name)
return self._url.value
@property
def deployment_branch_policy(
self,
) -> EnvironmentDeploymentBranchPolicy:
self._completeIfNotSet(self._deployment_branch_policy)
return self._deployment_branch_policy.value
def get_public_key(self) -> PublicKey:
"""
:calls: `GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key <https://docs.github.com/en/rest/reference#get-a-repository-public-key>`_
:rtype: :class:`PublicKey`
"""
# https://stackoverflow.com/a/76474814
# https://docs.github.com/en/rest/secrets?apiVersion=2022-11-28#get-an-environment-public-key
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.url}/secrets/public-key")
return PublicKey(self._requester, headers, data, completed=True)
def create_secret(self, secret_name: str, unencrypted_value: str) -> Secret:
"""
:calls: `PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name} <https://docs.github.com/en/rest/secrets#get-a-repository-secret>`_
"""
assert isinstance(secret_name, str), secret_name
assert isinstance(unencrypted_value, str), unencrypted_value
public_key = self.get_public_key()
payload = public_key.encrypt(unencrypted_value)
put_parameters = {
"key_id": public_key.key_id,
"encrypted_value": payload,
}
self._requester.requestJsonAndCheck("PUT", f"{self.url}/secrets/{secret_name}", input=put_parameters)
return Secret(
requester=self._requester,
headers={},
attributes={
"name": secret_name,
"url": f"{self.url}/secrets/{secret_name}",
},
completed=False,
)
def get_secrets(self) -> PaginatedList[Secret]:
"""
Gets all repository secrets.
"""
return PaginatedList(
Secret,
self._requester,
f"{self.url}/secrets",
None,
attributesTransformer=PaginatedList.override_attributes({"secrets_url": f"{self.url}/secrets"}),
list_item="secrets",
)
def get_secret(self, secret_name: str) -> Secret:
"""
:calls: 'GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name} <https://docs.github.com/en/rest/secrets#get-an-organization-secret>`_
"""
assert isinstance(secret_name, str), secret_name
return Secret(
requester=self._requester,
headers={},
attributes={"url": f"{self.url}/secrets/{secret_name}"},
completed=False,
)
def create_variable(self, variable_name: str, value: str) -> Variable:
"""
:calls: `POST /repositories/{repository_id}/environments/{environment_name}/variables/{variable_name} <https://docs.github.com/en/rest/variables#create-a-repository-variable>`_
"""
assert isinstance(variable_name, str), variable_name
assert isinstance(value, str), value
post_parameters = {
"name": variable_name,
"value": value,
}
self._requester.requestJsonAndCheck("POST", f"{self.url}/variables", input=post_parameters)
return Variable(
self._requester,
headers={},
attributes={
"name": variable_name,
"value": value,
"url": f"{self.url}/variables/{variable_name}",
},
completed=False,
)
def get_variables(self) -> PaginatedList[Variable]:
"""
Gets all repository variables :rtype: :class:`PaginatedList` of :class:`Variable`
"""
return PaginatedList(
Variable,
self._requester,
f"{self.url}/variables",
None,
attributesTransformer=PaginatedList.override_attributes({"variables_url": f"{self.url}/variables"}),
list_item="variables",
)
def get_variable(self, variable_name: str) -> Variable:
"""
:calls: 'GET /orgs/{org}/variables/{variable_name} <https://docs.github.com/en/rest/variables#get-an-organization-variable>`_
:param variable_name: string
:rtype: Variable
"""
assert isinstance(variable_name, str), variable_name
return Variable(
requester=self._requester,
headers={},
attributes={"url": f"{self.url}/variables/{variable_name}"},
completed=False,
)
def delete_secret(self, secret_name: str) -> bool:
"""
:calls: `DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name} <https://docs.github.com/en/rest/reference#delete-a-repository-secret>`_
:param secret_name: string
:rtype: bool
"""
assert isinstance(secret_name, str), secret_name
status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/secrets/{secret_name}")
return status == 204
def delete_variable(self, variable_name: str) -> bool:
"""
:calls: `DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{variable_name} <https://docs.github.com/en/rest/reference#delete-a-repository-variable>`_
:param variable_name: string
:rtype: bool
"""
assert isinstance(variable_name, str), variable_name
status, headers, data = self._requester.requestJson("DELETE", f"{self.url}/variables/{variable_name}")
return status == 204
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "protection_rules" in attributes: # pragma no branch
self._protection_rules = self._makeListOfClassesAttribute(
github.EnvironmentProtectionRule.EnvironmentProtectionRule,
attributes["protection_rules"],
)
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "environments_url" in attributes:
self._environments_url = self._makeStringAttribute(attributes["environments_url"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "deployment_branch_policy" in attributes: # pragma no branch
self._deployment_branch_policy = self._makeClassAttribute(
github.EnvironmentDeploymentBranchPolicy.EnvironmentDeploymentBranchPolicy,
attributes["deployment_branch_policy"],
)
| 13,542
|
Python
|
.py
| 268
| 42.61194
| 186
| 0.594231
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,426
|
Referrer.py
|
PyGithub_PyGithub/github/Referrer.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Justin Kufro <jkufro@andrew.cmu.edu> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class Referrer(NonCompletableGithubObject):
"""
This class represents a popylar Referrer for a GitHub repository.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#traffic
"""
def _initAttributes(self) -> None:
self._referrer: Attribute[str] = NotSet
self._count: Attribute[int] = NotSet
self._uniques: Attribute[int] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"referrer": self._referrer.value,
"count": self._count.value,
"uniques": self._uniques.value,
}
)
@property
def referrer(self) -> str:
return self._referrer.value
@property
def count(self) -> int:
return self._count.value
@property
def uniques(self) -> int:
return self._uniques.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "referrer" in attributes: # pragma no branch
self._referrer = self._makeStringAttribute(attributes["referrer"])
if "count" in attributes: # pragma no branch
self._count = self._makeIntAttribute(attributes["count"])
if "uniques" in attributes: # pragma no branch
self._uniques = self._makeIntAttribute(attributes["uniques"])
| 4,537
|
Python
|
.py
| 74
| 56.743243
| 80
| 0.503258
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,427
|
RequiredPullRequestReviews.py
|
PyGithub_PyGithub/github/RequiredPullRequestReviews.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.NamedUser
import github.Team
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.NamedUser import NamedUser
from github.Team import Team
class RequiredPullRequestReviews(CompletableGithubObject):
"""
This class represents Required Pull Request Reviews.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#get-pull-request-review-protection
"""
def _initAttributes(self) -> None:
self._dismiss_stale_reviews: Attribute[bool] = NotSet
self._require_code_owner_reviews: Attribute[bool] = NotSet
self._required_approving_review_count: Attribute[int] = NotSet
self._users: Attribute[list[NamedUser]] = NotSet
self._teams: Attribute[list[Team]] = NotSet
self._require_last_push_approval: Attribute[bool] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"url": self._url.value,
"dismiss_stale_reviews": self._dismiss_stale_reviews.value,
"require_code_owner_reviews": self._require_code_owner_reviews.value,
"require_last_push_approval": self._require_last_push_approval.value,
}
)
@property
def dismiss_stale_reviews(self) -> bool:
self._completeIfNotSet(self._dismiss_stale_reviews)
return self._dismiss_stale_reviews.value
@property
def require_code_owner_reviews(self) -> bool:
self._completeIfNotSet(self._require_code_owner_reviews)
return self._require_code_owner_reviews.value
@property
def required_approving_review_count(self) -> int:
self._completeIfNotSet(self._required_approving_review_count)
return self._required_approving_review_count.value
@property
def require_last_push_approval(self) -> bool:
self._completeIfNotSet(self._require_last_push_approval)
return self._require_last_push_approval.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def dismissal_users(self) -> list[NamedUser]:
self._completeIfNotSet(self._users)
return self._users.value
@property
def dismissal_teams(self) -> list[Team]:
self._completeIfNotSet(self._teams)
return self._teams.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "dismissal_restrictions" in attributes: # pragma no branch
if "users" in attributes["dismissal_restrictions"]:
self._users = self._makeListOfClassesAttribute(
github.NamedUser.NamedUser,
attributes["dismissal_restrictions"]["users"],
)
if "teams" in attributes["dismissal_restrictions"]: # pragma no branch
self._teams = self._makeListOfClassesAttribute(
github.Team.Team, attributes["dismissal_restrictions"]["teams"]
)
if "dismiss_stale_reviews" in attributes: # pragma no branch
self._dismiss_stale_reviews = self._makeBoolAttribute(attributes["dismiss_stale_reviews"])
if "require_code_owner_reviews" in attributes: # pragma no branch
self._require_code_owner_reviews = self._makeBoolAttribute(attributes["require_code_owner_reviews"])
if "required_approving_review_count" in attributes: # pragma no branch
self._required_approving_review_count = self._makeIntAttribute(
attributes["required_approving_review_count"]
)
if "require_last_push_approval" in attributes: # pragma no branch
self._require_last_push_approval = self._makeBoolAttribute(attributes["require_last_push_approval"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 7,436
|
Python
|
.py
| 123
| 54.073171
| 112
| 0.572036
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,428
|
CommitStats.py
|
PyGithub_PyGithub/github/CommitStats.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class CommitStats(NonCompletableGithubObject):
"""
This class represents CommitStats.
"""
def _initAttributes(self) -> None:
self._total: Attribute[int] = NotSet
self._deletions: Attribute[int] = NotSet
self._additions: Attribute[int] = NotSet
@property
def additions(self) -> int:
return self._additions.value
@property
def deletions(self) -> int:
return self._deletions.value
@property
def total(self) -> int:
return self._total.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "additions" in attributes: # pragma no branch
self._additions = self._makeIntAttribute(attributes["additions"])
if "deletions" in attributes: # pragma no branch
self._deletions = self._makeIntAttribute(attributes["deletions"])
if "total" in attributes: # pragma no branch
self._total = self._makeIntAttribute(attributes["total"])
| 3,776
|
Python
|
.py
| 59
| 60.271186
| 80
| 0.495415
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,429
|
Invitation.py
|
PyGithub_PyGithub/github/Invitation.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.GithubObject
import github.NamedUser
import github.Repository
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.NamedUser import NamedUser
from github.Repository import Repository
class Invitation(CompletableGithubObject):
"""
This class represents repository invitations.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#invitations
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = NotSet
self._permissions: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._invitee: Attribute[NamedUser] = NotSet
self._inviter: Attribute[NamedUser] = NotSet
self._url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._repository: Attribute[Repository] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def permissions(self) -> str:
self._completeIfNotSet(self._permissions)
return self._permissions.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def invitee(self) -> NamedUser:
self._completeIfNotSet(self._invitee)
return self._invitee.value
@property
def inviter(self) -> NamedUser:
self._completeIfNotSet(self._inviter)
return self._inviter.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def repository(self) -> Repository:
self._completeIfNotSet(self._repository)
return self._repository.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "repository" in attributes: # pragma no branch
self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "invitee" in attributes: # pragma no branch
self._invitee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["invitee"])
if "inviter" in attributes: # pragma no branch
self._inviter = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["inviter"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeStringAttribute(attributes["permissions"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
| 6,524
|
Python
|
.py
| 115
| 51.521739
| 111
| 0.565816
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,430
|
InputFileContent.py
|
PyGithub_PyGithub/github/InputFileContent.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
from github.GithubObject import NotSet, Opt, is_defined, is_optional
class InputFileContent:
"""
This class represents InputFileContents.
"""
def __init__(self, content: str, new_name: Opt[str] = NotSet):
assert isinstance(content, str), content
assert is_optional(new_name, str), new_name
self.__newName: Opt[str] = new_name
self.__content: str = content
@property
def _identity(self) -> dict[str, str]:
identity: dict[str, Any] = {
"content": self.__content,
}
if is_defined(self.__newName):
identity["filename"] = self.__newName
return identity
| 3,480
|
Python
|
.py
| 54
| 61.222222
| 80
| 0.476302
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,431
|
__init__.py
|
PyGithub_PyGithub/github/__init__.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 sharkykh <sharkykh@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2020 Emily <github@emily.moe> #
# Copyright 2020 Liuyang Wan <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Denis Blanchette <dblanchette@coveo.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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/>. #
# #
################################################################################
"""
The primary class you will instantiate is :class:`github.MainClass.Github`. From its ``get_``, ``create_`` methods, you
will obtain instances of all Github objects like :class:`github.NamedUser.NamedUser` or
:class:`github.Repository.Repository`.
All classes inherit from :class:`github.GithubObject.GithubObject`.
"""
import logging
from . import Auth
from .AppAuthentication import AppAuthentication
from .GithubException import (
BadAttributeException,
BadCredentialsException,
BadUserAgentException,
GithubException,
IncompletableObject,
RateLimitExceededException,
TwoFactorException,
UnknownObjectException,
)
from .GithubIntegration import GithubIntegration
from .GithubRetry import GithubRetry
from .InputFileContent import InputFileContent
from .InputGitAuthor import InputGitAuthor
from .InputGitTreeElement import InputGitTreeElement
from .MainClass import Github
# set log level to INFO for github
logger = logging.getLogger("github")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
def set_log_level(level: int) -> None:
"""
Set the log level of the github logger, e.g. set_log_level(logging.WARNING) :param level: log level.
"""
logger.setLevel(level)
def enable_console_debug_logging() -> None: # pragma no cover (Function useful only outside test environment)
"""
This function sets up a very simple logging configuration (log everything on standard output) that is useful for
troubleshooting.
"""
set_log_level(logging.DEBUG)
__all__ = [
"Auth",
"AppAuthentication",
"BadAttributeException",
"BadCredentialsException",
"BadUserAgentException",
"enable_console_debug_logging",
"Github",
"GithubException",
"GithubIntegration",
"GithubRetry",
"IncompletableObject",
"InputFileContent",
"InputGitAuthor",
"InputGitTreeElement",
"RateLimitExceededException",
"TwoFactorException",
"UnknownObjectException",
]
| 5,320
|
Python
|
.py
| 100
| 50.73
| 119
| 0.5646
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,432
|
HookDescription.py
|
PyGithub_PyGithub/github/HookDescription.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class HookDescription(NonCompletableGithubObject):
"""
This class represents HookDescriptions.
"""
def _initAttributes(self) -> None:
self._events: Attribute[list[str]] = NotSet
self._name: Attribute[str] = NotSet
self._schema: Attribute[list[list[str]]] = NotSet
self._supported_events: Attribute[list[str]] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def events(self) -> list[str]:
return self._events.value
@property
def name(self) -> str:
return self._name.value
@property
def schema(self) -> list[list[str]]:
return self._schema.value
@property
def supported_events(self) -> list[str]:
return self._supported_events.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "events" in attributes: # pragma no branch
self._events = self._makeListOfStringsAttribute(attributes["events"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "schema" in attributes: # pragma no branch
self._schema = self._makeListOfListOfStringsAttribute(attributes["schema"])
if "supported_events" in attributes: # pragma no branch
self._supported_events = self._makeListOfStringsAttribute(attributes["supported_events"])
| 4,587
|
Python
|
.py
| 72
| 59.652778
| 101
| 0.522096
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,433
|
PullRequestPart.py
|
PyGithub_PyGithub/github/PullRequestPart.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.NamedUser
import github.Repository
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.NamedUser import NamedUser
from github.Repository import Repository
class PullRequestPart(NonCompletableGithubObject):
"""
This class represents PullRequestParts.
"""
def _initAttributes(self) -> None:
self._label: Attribute[str] = NotSet
self._ref: Attribute[str] = NotSet
self._repo: Attribute[Repository] = NotSet
self._sha: Attribute[str] = NotSet
self._user: Attribute[NamedUser] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"sha": self._sha.value})
@property
def label(self) -> str:
return self._label.value
@property
def ref(self) -> str:
return self._ref.value
@property
def repo(self) -> Repository:
return self._repo.value
@property
def sha(self) -> str:
return self._sha.value
@property
def user(self) -> NamedUser:
return self._user.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "label" in attributes: # pragma no branch
self._label = self._makeStringAttribute(attributes["label"])
if "ref" in attributes: # pragma no branch
self._ref = self._makeStringAttribute(attributes["ref"])
if "repo" in attributes: # pragma no branch
self._repo = self._makeClassAttribute(github.Repository.Repository, attributes["repo"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 4,903
|
Python
|
.py
| 83
| 54.771084
| 99
| 0.530795
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,434
|
AdvisoryCreditDetailed.py
|
PyGithub_PyGithub/github/AdvisoryCreditDetailed.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Nick Campbell <nicholas.j.campbell@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
import github.NamedUser
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class AdvisoryCreditDetailed(NonCompletableGithubObject):
"""
This class represents a credit that is assigned to a SecurityAdvisory.
The reference can be found here
https://docs.github.com/en/rest/security-advisories/repository-advisories
"""
@property
def state(self) -> str:
"""
:type: string
"""
return self._state.value
@property
def type(self) -> str:
"""
:type: string
"""
return self._type.value
@property
def user(self) -> github.NamedUser.NamedUser:
"""
:type: :class:`github.NamedUser.NamedUser`
"""
return self._user.value
def _initAttributes(self) -> None:
self._state: Attribute[str] = NotSet
self._type: Attribute[str] = NotSet
self._user: Attribute[github.NamedUser.NamedUser] = NotSet
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 4,749
|
Python
|
.py
| 79
| 56.025316
| 97
| 0.524259
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,435
|
GithubIntegration.py
|
PyGithub_PyGithub/github/GithubIntegration.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Denis Blanchette <dblanchette@coveo.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Hemslo Wang <hemslo.wang@gmail.com> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Mark Amery <markamery@btinternet.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 chantra <chantra@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import urllib.parse
import warnings
from typing import Any
import deprecated
import urllib3
from urllib3 import Retry
import github
from github import Consts
from github.Auth import AppAuth
from github.GithubApp import GithubApp
from github.GithubException import GithubException
from github.Installation import Installation
from github.InstallationAuthorization import InstallationAuthorization
from github.PaginatedList import PaginatedList
from github.Requester import Requester
class GithubIntegration:
"""
Main class to obtain tokens for a GitHub integration.
"""
# keep non-deprecated arguments in-sync with Requester
# v3: remove integration_id, private_key, jwt_expiry, jwt_issued_at and jwt_algorithm
# v3: move auth to the front of arguments
# v3: move * before first argument so all arguments must be named,
# allows to reorder / add new arguments / remove deprecated arguments without breaking user code
# added here to force named parameters because new parameters have been added
auth: AppAuth
base_url: str
__requester: Requester
def __init__(
self,
integration_id: int | str | None = None,
private_key: str | None = None,
base_url: str = Consts.DEFAULT_BASE_URL,
*,
timeout: int = Consts.DEFAULT_TIMEOUT,
user_agent: str = Consts.DEFAULT_USER_AGENT,
per_page: int = Consts.DEFAULT_PER_PAGE,
verify: bool | str = True,
retry: int | Retry | None = None,
pool_size: int | None = None,
seconds_between_requests: float | None = Consts.DEFAULT_SECONDS_BETWEEN_REQUESTS,
seconds_between_writes: float | None = Consts.DEFAULT_SECONDS_BETWEEN_WRITES,
jwt_expiry: int = Consts.DEFAULT_JWT_EXPIRY,
jwt_issued_at: int = Consts.DEFAULT_JWT_ISSUED_AT,
jwt_algorithm: str = Consts.DEFAULT_JWT_ALGORITHM,
auth: AppAuth | None = None,
) -> None:
"""
:param integration_id: int deprecated, use auth=github.Auth.AppAuth(...) instead
:param private_key: string deprecated, use auth=github.Auth.AppAuth(...) instead
:param base_url: string
:param timeout: integer
:param user_agent: string
:param per_page: int
:param verify: boolean or string
:param retry: int or urllib3.util.retry.Retry object
:param pool_size: int
:param seconds_between_requests: float
:param seconds_between_writes: float
:param jwt_expiry: int deprecated, use auth=github.Auth.AppAuth(...) instead
:param jwt_issued_at: int deprecated, use auth=github.Auth.AppAuth(...) instead
:param jwt_algorithm: string deprecated, use auth=github.Auth.AppAuth(...) instead
:param auth: authentication method
"""
if integration_id is not None:
assert isinstance(integration_id, (int, str)), integration_id
if private_key is not None:
assert isinstance(private_key, str), "supplied private key should be a string"
assert isinstance(base_url, str), base_url
assert isinstance(timeout, int), timeout
assert user_agent is None or isinstance(user_agent, str), user_agent
assert isinstance(per_page, int), per_page
assert isinstance(verify, (bool, str)), verify
assert retry is None or isinstance(retry, int) or isinstance(retry, urllib3.util.Retry), retry
assert pool_size is None or isinstance(pool_size, int), pool_size
assert seconds_between_requests is None or seconds_between_requests >= 0
assert seconds_between_writes is None or seconds_between_writes >= 0
assert isinstance(jwt_expiry, int), jwt_expiry
assert Consts.MIN_JWT_EXPIRY <= jwt_expiry <= Consts.MAX_JWT_EXPIRY, jwt_expiry
assert isinstance(jwt_issued_at, int)
self.base_url = base_url
if (
integration_id is not None
or private_key is not None
or jwt_expiry != Consts.DEFAULT_JWT_EXPIRY
or jwt_issued_at != Consts.DEFAULT_JWT_ISSUED_AT
or jwt_algorithm != Consts.DEFAULT_JWT_ALGORITHM
):
warnings.warn(
"Arguments integration_id, private_key, jwt_expiry, jwt_issued_at and jwt_algorithm are deprecated, "
"please use auth=github.Auth.AppAuth(...) instead",
category=DeprecationWarning,
)
auth = AppAuth(
integration_id, # type: ignore
private_key, # type: ignore
jwt_expiry=jwt_expiry,
jwt_issued_at=jwt_issued_at,
jwt_algorithm=jwt_algorithm,
)
assert isinstance(
auth, AppAuth
), f"GithubIntegration requires github.Auth.AppAuth authentication, not {type(auth)}"
self.auth = auth
self.__requester = Requester(
auth=auth,
base_url=self.base_url,
timeout=timeout,
user_agent=user_agent,
per_page=per_page,
verify=verify,
retry=retry,
pool_size=pool_size,
seconds_between_requests=seconds_between_requests,
seconds_between_writes=seconds_between_writes,
)
def close(self) -> None:
"""Close connections to the server. Alternatively, use the
GithubIntegration object as a context manager:
.. code-block:: python
with github.GithubIntegration(...) as gi:
# do something
"""
self.__requester.close()
def __enter__(self) -> GithubIntegration:
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
self.close()
def get_github_for_installation(
self, installation_id: int, token_permissions: dict[str, str] | None = None
) -> github.Github:
# The installation has to authenticate as an installation, not an app
auth = self.auth.get_installation_auth(installation_id, token_permissions, self.__requester)
return github.Github(**self.__requester.withAuth(auth).kwargs)
@property
def requester(self) -> Requester:
"""
Return my Requester object.
For example, to make requests to API endpoints not yet supported by PyGitHub.
"""
return self.__requester
def _get_headers(self) -> dict[str, str]:
"""
Get headers for the requests.
"""
return {
"Accept": Consts.mediaTypeIntegrationPreview,
}
def _get_installed_app(self, url: str) -> Installation:
"""
Get installation for the given URL.
"""
headers, response = self.__requester.requestJsonAndCheck("GET", url, headers=self._get_headers())
return Installation(
requester=self.__requester,
headers=headers,
attributes=response,
completed=True,
)
@deprecated.deprecated(
"Use github.Github(auth=github.Auth.AppAuth), github.Auth.AppAuth.token or github.Auth.AppAuth.create_jwt(expiration) instead"
)
def create_jwt(self, expiration: int | None = None) -> str:
"""
Create a signed JWT
https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
"""
return self.auth.create_jwt(expiration)
def get_access_token(
self, installation_id: int, permissions: dict[str, str] | None = None
) -> InstallationAuthorization:
"""
:calls: `POST /app/installations/{installation_id}/access_tokens <https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app>`
"""
if permissions is None:
permissions = {}
if not isinstance(permissions, dict):
raise GithubException(status=400, data={"message": "Invalid permissions"}, headers=None)
body = {"permissions": permissions}
headers, response = self.__requester.requestJsonAndCheck(
"POST",
f"/app/installations/{installation_id}/access_tokens",
headers=self._get_headers(),
input=body,
)
return InstallationAuthorization(
requester=self.__requester,
headers=headers,
attributes=response,
completed=True,
)
@deprecated.deprecated("Use get_repo_installation")
def get_installation(self, owner: str, repo: str) -> Installation:
"""
Deprecated by get_repo_installation.
:calls: `GET /repos/{owner}/{repo}/installation
<https://docs.github.com/en/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app>`
"""
owner = urllib.parse.quote(owner)
repo = urllib.parse.quote(repo)
return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation")
def get_installations(self) -> PaginatedList[Installation]:
"""
:calls: GET /app/installations <https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app>
"""
return PaginatedList(
contentClass=Installation,
requester=self.__requester,
firstUrl="/app/installations",
firstParams=None,
headers=self._get_headers(),
list_item="installations",
)
def get_org_installation(self, org: str) -> Installation:
"""
:calls: `GET /orgs/{org}/installation <https://docs.github.com/en/rest/apps/apps#get-an-organization-installation-for-the-authenticated-app>`
"""
org = urllib.parse.quote(org)
return self._get_installed_app(url=f"/orgs/{org}/installation")
def get_repo_installation(self, owner: str, repo: str) -> Installation:
"""
:calls: `GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app>`
"""
owner = urllib.parse.quote(owner)
repo = urllib.parse.quote(repo)
return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation")
def get_user_installation(self, username: str) -> Installation:
"""
:calls: `GET /users/{username}/installation <https://docs.github.com/en/rest/apps/apps#get-a-user-installation-for-the-authenticated-app>`
"""
username = urllib.parse.quote(username)
return self._get_installed_app(url=f"/users/{username}/installation")
def get_app_installation(self, installation_id: int) -> Installation:
"""
:calls: `GET /app/installations/{installation_id} <https://docs.github.com/en/rest/apps/apps#get-an-installation-for-the-authenticated-app>`
"""
return self._get_installed_app(url=f"/app/installations/{installation_id}")
def get_app(self) -> GithubApp:
"""
:calls: `GET /app <https://docs.github.com/en/rest/reference/apps#get-the-authenticated-app>`_
"""
headers, data = self.__requester.requestJsonAndCheck("GET", "/app", headers=self._get_headers())
return GithubApp(requester=self.__requester, headers=headers, attributes=data, completed=True)
| 13,714
|
Python
|
.py
| 273
| 42.076923
| 164
| 0.609358
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,436
|
EnvironmentProtectionRule.py
|
PyGithub_PyGithub/github/EnvironmentProtectionRule.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Nick Campbell <nicholas.j.campbell@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2022 Marco Köpcke <hello@parakoopa.de> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 alson <git@alm.nufan.net> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.EnvironmentProtectionRuleReviewer
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.EnvironmentProtectionRuleReviewer import EnvironmentProtectionRuleReviewer
class EnvironmentProtectionRule(NonCompletableGithubObject):
"""
This class represents a protection rule for an environment.
The reference can be found here
https://docs.github.com/en/rest/reference/deployments#environments
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = NotSet
self._node_id: Attribute[str] = NotSet
self._type: Attribute[str] = NotSet
self._reviewers: Attribute[list[EnvironmentProtectionRuleReviewer]] = NotSet
self._wait_timer: Attribute[int] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def id(self) -> int:
return self._id.value
@property
def node_id(self) -> str:
return self._node_id.value
@property
def type(self) -> str:
return self._type.value
@property
def reviewers(
self,
) -> list[EnvironmentProtectionRuleReviewer]:
return self._reviewers.value
@property
def wait_timer(self) -> int:
return self._wait_timer.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "reviewers" in attributes: # pragma no branch
self._reviewers = self._makeListOfClassesAttribute(
github.EnvironmentProtectionRuleReviewer.EnvironmentProtectionRuleReviewer,
attributes["reviewers"],
)
if "wait_timer" in attributes: # pragma no branch
self._wait_timer = self._makeIntAttribute(attributes["wait_timer"])
| 5,493
|
Python
|
.py
| 91
| 55.67033
| 91
| 0.546231
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,437
|
DependabotAlert.py
|
PyGithub_PyGithub/github/DependabotAlert.py
|
############################ Copyrights and license ############################
# #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.AdvisoryVulnerabilityPackage
import github.DependabotAlertAdvisory
import github.DependabotAlertDependency
import github.DependabotAlertVulnerability
import github.NamedUser
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.DependabotAlertAdvisory import DependabotAlertAdvisory
from github.DependabotAlertDependency import DependabotAlertDependency
from github.DependabotAlertVulnerability import DependabotAlertVulnerability
from github.NamedUser import NamedUser
class DependabotAlert(NonCompletableGithubObject):
"""
This class represents a DependabotAlert.
The reference can be found here
https://docs.github.com/en/rest/dependabot/alerts
"""
def _initAttributes(self) -> None:
self._number: Attribute[int] = NotSet
self._state: Attribute[str] = NotSet
self._dependency: Attribute[DependabotAlertDependency] = NotSet
self._security_advisory: Attribute[DependabotAlertAdvisory] = NotSet
self._security_vulnerability: Attribute[DependabotAlertVulnerability] = NotSet
self._url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._dismissed_at: Attribute[datetime | None] = NotSet
self._dismissed_by: Attribute[NamedUser | None] = NotSet
self._dismissed_reason: Attribute[str | None] = NotSet
self._dismissed_comment: Attribute[str | None] = NotSet
self._fixed_at: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"number": self.number, "ghsa_id": self.security_advisory.ghsa_id})
@property
def number(self) -> int:
return self._number.value
@property
def state(self) -> str:
return self._state.value
@property
def dependency(self) -> DependabotAlertDependency:
return self._dependency.value
@property
def security_advisory(self) -> DependabotAlertAdvisory:
return self._security_advisory.value
@property
def security_vulnerability(self) -> DependabotAlertVulnerability:
return self._security_vulnerability.value
@property
def url(self) -> str:
return self._url.value
@property
def html_url(self) -> str:
return self._html_url.value
@property
def created_at(self) -> datetime:
return self._created_at.value
@property
def updated_at(self) -> datetime:
return self._updated_at.value
@property
def dismissed_at(self) -> datetime | None:
return self._dismissed_at.value
@property
def dismissed_by(self) -> NamedUser | None:
return self._dismissed_by.value
@property
def dismissed_reason(self) -> str | None:
return self._dismissed_reason.value
@property
def dismissed_comment(self) -> str | None:
return self._dismissed_comment.value
@property
def fixed_at(self) -> str | None:
return self._fixed_at.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "number" in attributes:
self._number = self._makeIntAttribute(attributes["number"])
if "state" in attributes:
self._state = self._makeStringAttribute(attributes["state"])
if "dependency" in attributes:
self._dependency = self._makeClassAttribute(
github.DependabotAlertDependency.DependabotAlertDependency, attributes["dependency"]
)
if "security_advisory" in attributes:
self._security_advisory = self._makeClassAttribute(
github.DependabotAlertAdvisory.DependabotAlertAdvisory, attributes["security_advisory"]
)
if "security_vulnerability" in attributes:
self._security_vulnerability = self._makeClassAttribute(
github.DependabotAlertVulnerability.DependabotAlertVulnerability, attributes["security_vulnerability"]
)
if "url" in attributes:
self._url = self._makeStringAttribute(attributes["url"])
if "html_url" in attributes:
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "created_at" in attributes:
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "updated_at" in attributes:
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "dismissed_at" in attributes:
self._dismissed_at = self._makeDatetimeAttribute(attributes["dismissed_at"])
if "dismissed_by" in attributes:
self._dismissed_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["dismissed_by"])
if "dismissed_reason" in attributes:
self._dismissed_reason = self._makeStringAttribute(attributes["dismissed_reason"])
if "dismissed_comment" in attributes:
self._dismissed_comment = self._makeStringAttribute(attributes["dismissed_comment"])
if "fixed_at" in attributes:
self._fixed_at = self._makeStringAttribute(attributes["fixed_at"])
| 7,215
|
Python
|
.py
| 137
| 45.963504
| 118
| 0.616192
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,438
|
Topic.py
|
PyGithub_PyGithub/github/Topic.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class Topic(NonCompletableGithubObject):
"""
This class represents topics as used by https://github.com/topics. The object reference can be found here https://docs.github.com/en/rest/reference/search#search-topics
"""
def _initAttributes(self) -> None:
self._name: Attribute[str] = NotSet
self._display_name: Attribute[str] = NotSet
self._short_description: Attribute[str] = NotSet
self._description: Attribute[str] = NotSet
self._created_by: Attribute[str] = NotSet
self._released: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._featured: Attribute[bool] = NotSet
self._curated: Attribute[bool] = NotSet
self._score: Attribute[float] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def name(self) -> str:
return self._name.value
@property
def display_name(self) -> str:
return self._display_name.value
@property
def short_description(self) -> str:
return self._short_description.value
@property
def description(self) -> str:
return self._description.value
@property
def created_by(self) -> str:
return self._created_by.value
@property
def released(self) -> str:
return self._released.value
@property
def created_at(self) -> datetime:
return self._created_at.value
@property
def updated_at(self) -> datetime:
return self._updated_at.value
@property
def featured(self) -> bool:
return self._featured.value
@property
def curated(self) -> bool:
return self._curated.value
@property
def score(self) -> float:
return self._score.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "display_name" in attributes: # pragma no branch
self._display_name = self._makeStringAttribute(attributes["display_name"])
if "short_description" in attributes: # pragma no branch
self._short_description = self._makeStringAttribute(attributes["short_description"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "created_by" in attributes: # pragma no branch
self._created_by = self._makeStringAttribute(attributes["created_by"])
if "released" in attributes: # pragma no branch
self._released = self._makeStringAttribute(attributes["released"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "featured" in attributes: # pragma no branch
self._featured = self._makeBoolAttribute(attributes["featured"])
if "curated" in attributes: # pragma no branch
self._curated = self._makeBoolAttribute(attributes["curated"])
if "score" in attributes: # pragma no branch
self._score = self._makeFloatAttribute(attributes["score"])
| 6,715
|
Python
|
.py
| 116
| 52.275862
| 172
| 0.562158
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,439
|
SourceImport.py
|
PyGithub_PyGithub/github/SourceImport.py
|
############################ Copyrights and license ############################
# #
# Copyright 2018 Hayden Fuss <wifu1234@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
from github import Consts
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class SourceImport(CompletableGithubObject):
"""
This class represents SourceImports.
The reference can be found here
https://docs.github.com/en/rest/reference/migrations#source-imports
"""
def _initAttributes(self) -> None:
self._authors_count: Attribute[int] = NotSet
self._authors_url: Attribute[str] = NotSet
self._has_large_files: Attribute[bool] = NotSet
self._html_url: Attribute[str] = NotSet
self._large_files_count: Attribute[int] = NotSet
self._large_files_size: Attribute[int] = NotSet
self._repository_url: Attribute[str] = NotSet
self._status: Attribute[str] = NotSet
self._status_text: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
self._use_lfs: Attribute[str] = NotSet
self._vcs: Attribute[str] = NotSet
self._vcs_url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"vcs_url": self._vcs_url.value,
"repository_url": self._repository_url.value,
"status": self._status.value,
"url": self._url.value,
}
)
@property
def authors_count(self) -> int:
self._completeIfNotSet(self._authors_count)
return self._authors_count.value
@property
def authors_url(self) -> str:
self._completeIfNotSet(self._authors_url)
return self._authors_url.value
@property
def has_large_files(self) -> bool:
self._completeIfNotSet(self._has_large_files)
return self._has_large_files.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def large_files_count(self) -> int:
self._completeIfNotSet(self._large_files_count)
return self._large_files_count.value
@property
def large_files_size(self) -> int:
self._completeIfNotSet(self._large_files_size)
return self._large_files_size.value
@property
def repository_url(self) -> str:
self._completeIfNotSet(self._repository_url)
return self._repository_url.value
@property
def status(self) -> str:
self._completeIfNotSet(self._status)
return self._status.value
@property
def status_text(self) -> str:
self._completeIfNotSet(self._status_text)
return self._status_text.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def use_lfs(self) -> str:
self._completeIfNotSet(self._use_lfs)
return self._use_lfs.value
@property
def vcs(self) -> str:
self._completeIfNotSet(self._vcs)
return self._vcs.value
@property
def vcs_url(self) -> str:
self._completeIfNotSet(self._vcs_url)
return self._vcs_url.value
def update(self, additional_headers: None | dict[str, Any] = None) -> bool:
import_header = {"Accept": Consts.mediaTypeImportPreview}
return super().update(additional_headers=import_header)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "authors_count" in attributes: # pragma no branch
self._authors_count = self._makeIntAttribute(attributes["authors_count"])
if "authors_url" in attributes: # pragma no branch
self._authors_url = self._makeStringAttribute(attributes["authors_url"])
if "has_large_files" in attributes: # pragma no branch
self._has_large_files = self._makeBoolAttribute(attributes["has_large_files"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "large_files_count" in attributes: # pragma no branch
self._large_files_count = self._makeIntAttribute(attributes["large_files_count"])
if "large_files_size" in attributes: # pragma no branch
self._large_files_size = self._makeIntAttribute(attributes["large_files_size"])
if "repository_url" in attributes: # pragma no branch
self._repository_url = self._makeStringAttribute(attributes["repository_url"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
if "status_text" in attributes: # pragma no branch
self._status_text = self._makeStringAttribute(attributes["status_text"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "use_lfs" in attributes: # pragma no branch
self._use_lfs = self._makeStringAttribute(attributes["use_lfs"])
if "vcs" in attributes: # pragma no branch
self._vcs = self._makeStringAttribute(attributes["vcs"])
if "vcs_url" in attributes: # pragma no branch
self._vcs_url = self._makeStringAttribute(attributes["vcs_url"])
| 7,834
|
Python
|
.py
| 147
| 46.469388
| 93
| 0.575754
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,440
|
InstallationAuthorization.py
|
PyGithub_PyGithub/github/InstallationAuthorization.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Denis Blanchette <dblanchette@coveo.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.NamedUser
import github.PaginatedList
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.NamedUser import NamedUser
class InstallationAuthorization(NonCompletableGithubObject):
"""
This class represents InstallationAuthorizations.
"""
def _initAttributes(self) -> None:
self._token: Attribute[str] = NotSet
self._expires_at: Attribute[datetime] = NotSet
self._on_behalf_of: Attribute[NamedUser] = NotSet
self._permissions: Attribute[dict] = NotSet
self._repository_selection: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"expires_at": self._expires_at.value})
@property
def token(self) -> str:
return self._token.value
@property
def expires_at(self) -> datetime:
return self._expires_at.value
@property
def on_behalf_of(self) -> NamedUser:
return self._on_behalf_of.value
@property
def permissions(self) -> dict:
return self._permissions.value
@property
def repository_selection(self) -> str:
return self._repository_selection.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "token" in attributes: # pragma no branch
self._token = self._makeStringAttribute(attributes["token"])
if "expires_at" in attributes: # pragma no branch
self._expires_at = self._makeDatetimeAttribute(attributes["expires_at"])
if "on_behalf_of" in attributes: # pragma no branch
self._on_behalf_of = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["on_behalf_of"])
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeDictAttribute(attributes["permissions"])
if "repository_selection" in attributes: # pragma no branch
self._repository_selection = self._makeStringAttribute(attributes["repository_selection"])
| 5,290
|
Python
|
.py
| 85
| 58.058824
| 113
| 0.546138
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,441
|
ApplicationOAuth.py
|
PyGithub_PyGithub/github/ApplicationOAuth.py
|
############################ Copyrights and license ############################
# #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import urllib.parse
from typing import TYPE_CHECKING, Any
import github.AccessToken
import github.Auth
from github.Consts import DEFAULT_BASE_URL, DEFAULT_OAUTH_URL
from github.GithubException import BadCredentialsException, GithubException
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
from github.Requester import Requester
if TYPE_CHECKING:
from github.AccessToken import AccessToken
from github.Auth import AppUserAuth
class ApplicationOAuth(NonCompletableGithubObject):
"""
This class is used for identifying and authorizing users for Github Apps.
The reference can be found at
https://docs.github.com/en/developers/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps
"""
def _initAttributes(self) -> None:
self._client_id: Attribute[str] = NotSet
self._client_secret: Attribute[str] = NotSet
def __init__(
self,
requester: Requester,
headers: dict[str, Any],
attributes: Any,
completed: bool,
) -> None:
# this object requires a request without authentication
requester = requester.withAuth(auth=None)
super().__init__(requester, headers, attributes, completed)
def __repr__(self) -> str:
return self.get__repr__({"client_id": self._client_id.value})
@property
def client_id(self) -> str:
return self._client_id.value
@property
def client_secret(self) -> str:
return self._client_secret.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "client_id" in attributes: # pragma no branch
self._client_id = self._makeStringAttribute(attributes["client_id"])
if "client_secret" in attributes: # pragma no branch
self._client_secret = self._makeStringAttribute(attributes["client_secret"])
def get_oauth_url(self, path: str) -> str:
if not path.startswith("/"):
path = f"/{path}"
if self._requester.base_url == DEFAULT_BASE_URL:
base_url = DEFAULT_OAUTH_URL
else:
base_url = f"{self._requester.scheme}://{self._requester.hostname_and_port}/login/oauth"
return f"{base_url}{path}"
def get_login_url(
self,
redirect_uri: str | None = None,
state: str | None = None,
login: str | None = None,
) -> str:
"""
Return the URL you need to redirect a user to in order to authorize your App.
"""
parameters = {"client_id": self.client_id}
if redirect_uri is not None:
assert isinstance(redirect_uri, str), redirect_uri
parameters["redirect_uri"] = redirect_uri
if state is not None:
assert isinstance(state, str), state
parameters["state"] = state
if login is not None:
assert isinstance(login, str), login
parameters["login"] = login
query = urllib.parse.urlencode(parameters)
return self.get_oauth_url(f"/authorize?{query}")
def get_access_token(self, code: str, state: str | None = None) -> AccessToken:
"""
:calls: `POST /login/oauth/access_token <https://docs.github.com/en/developers/apps/identifying-and-authorizing-users-for-github-apps>`_
"""
assert isinstance(code, str), code
post_parameters = {
"code": code,
"client_id": self.client_id,
"client_secret": self.client_secret,
}
if state is not None:
post_parameters["state"] = state
headers, data = self._checkError(
*self._requester.requestJsonAndCheck(
"POST",
self.get_oauth_url("/access_token"),
headers={"Accept": "application/json"},
input=post_parameters,
)
)
return github.AccessToken.AccessToken(
requester=self._requester,
headers=headers,
attributes=data,
completed=False,
)
def get_app_user_auth(self, token: AccessToken) -> AppUserAuth:
return github.Auth.AppUserAuth(
client_id=self.client_id,
client_secret=self.client_secret,
token=token.token,
token_type=token.type,
expires_at=token.expires_at,
refresh_token=token.refresh_token,
refresh_expires_at=token.refresh_expires_at,
requester=self._requester,
)
def refresh_access_token(self, refresh_token: str) -> AccessToken:
"""
:calls: `POST /login/oauth/access_token <https://docs.github.com/en/developers/apps/identifying-and-authorizing-users-for-github-apps>`_
:param refresh_token: string
"""
assert isinstance(refresh_token, str)
post_parameters = {
"client_id": self.client_id,
"client_secret": self.client_secret,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
}
headers, data = self._checkError(
*self._requester.requestJsonAndCheck(
"POST",
self.get_oauth_url("/access_token"),
headers={"Accept": "application/json"},
input=post_parameters,
)
)
return github.AccessToken.AccessToken(
requester=self._requester,
headers=headers,
attributes=data,
completed=False,
)
@staticmethod
def _checkError(headers: dict[str, Any], data: Any) -> tuple[dict[str, Any], Any]:
if isinstance(data, dict) and "error" in data:
if data["error"] == "bad_verification_code":
raise BadCredentialsException(200, data, headers)
raise GithubException(200, data, headers)
return headers, data
| 8,213
|
Python
|
.py
| 171
| 39.865497
| 144
| 0.562211
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,442
|
AdvisoryVulnerability.py
|
PyGithub_PyGithub/github/AdvisoryVulnerability.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any, Union
from typing_extensions import TypedDict
import github.AdvisoryVulnerabilityPackage
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.AdvisoryVulnerabilityPackage import AdvisoryVulnerabilityPackage
class SimpleAdvisoryVulnerabilityPackage(TypedDict):
"""
A simple package in an advisory.
"""
ecosystem: str
name: str | None
class SimpleAdvisoryVulnerability(TypedDict):
"""
A simple vulnerability in a security advisory.
"""
package: SimpleAdvisoryVulnerabilityPackage
patched_versions: str | None
vulnerable_functions: list[str] | None
vulnerable_version_range: str | None
AdvisoryVulnerabilityInput = Union[SimpleAdvisoryVulnerability, "AdvisoryVulnerability"]
class AdvisoryVulnerability(NonCompletableGithubObject):
"""
This class represents a package that is vulnerable to a parent SecurityAdvisory.
The reference can be found here
https://docs.github.com/en/rest/security-advisories/repository-advisories
"""
@property
def package(
self,
) -> AdvisoryVulnerabilityPackage:
"""
:type: :class:`github.AdvisoryVulnerability.AdvisoryVulnerability`
"""
return self._package.value
@property
def patched_versions(self) -> str:
"""
:type: string
"""
return self._patched_versions.value
@property
def vulnerable_functions(self) -> list[str] | None:
"""
:type: list of string
"""
return self._vulnerable_functions.value
@property
def vulnerable_version_range(self) -> str | None:
"""
:type: string
"""
return self._vulnerable_version_range.value
def _initAttributes(self) -> None:
self._package: Attribute[AdvisoryVulnerabilityPackage] = NotSet
self._patched_versions: Attribute[str] = NotSet
self._vulnerable_functions: Attribute[list[str]] = NotSet
self._vulnerable_version_range: Attribute[str] = NotSet
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "package" in attributes: # pragma no branch
self._package = self._makeClassAttribute(
github.AdvisoryVulnerabilityPackage.AdvisoryVulnerabilityPackage,
attributes["package"],
)
if "patched_versions" in attributes: # pragma no branch
self._patched_versions = self._makeStringAttribute(attributes["patched_versions"])
if "vulnerable_functions" in attributes: # pragma no branch
self._vulnerable_functions = self._makeListOfStringsAttribute(attributes["vulnerable_functions"])
if "vulnerable_version_range" in attributes: # pragma no branch
self._vulnerable_version_range = self._makeStringAttribute(attributes["vulnerable_version_range"])
@classmethod
def _validate_vulnerability(cls, vulnerability: AdvisoryVulnerabilityInput) -> None:
assert isinstance(vulnerability, (dict, cls)), vulnerability
if isinstance(vulnerability, dict):
assert "package" in vulnerability, vulnerability
package: SimpleAdvisoryVulnerabilityPackage = vulnerability["package"]
assert isinstance(package, dict), package
assert "ecosystem" in package, package
assert isinstance(package["ecosystem"], str), package
assert "name" in package, package
assert isinstance(package["name"], (str, type(None))), package
assert "patched_versions" in vulnerability, vulnerability
assert isinstance(vulnerability["patched_versions"], (str, type(None))), vulnerability
assert "vulnerable_functions" in vulnerability, vulnerability
assert isinstance(vulnerability["vulnerable_functions"], (list, type(None))), vulnerability
assert "vulnerable_functions" in vulnerability, vulnerability
assert (
all(isinstance(vf, str) for vf in vulnerability["vulnerable_functions"])
if vulnerability["vulnerable_functions"] is not None
else True
), vulnerability
assert "vulnerable_version_range" in vulnerability, vulnerability
assert isinstance(vulnerability["vulnerable_version_range"], (str, type(None))), vulnerability
else:
assert (
vulnerability.package is github.AdvisoryVulnerabilityPackage.AdvisoryVulnerabilityPackage
), vulnerability
@staticmethod
def _to_github_dict(
vulnerability: AdvisoryVulnerabilityInput,
) -> SimpleAdvisoryVulnerability:
if isinstance(vulnerability, dict):
vulnerability_package: SimpleAdvisoryVulnerabilityPackage = vulnerability["package"]
return {
"package": {
"ecosystem": vulnerability_package["ecosystem"],
"name": vulnerability_package["name"],
},
"patched_versions": vulnerability["patched_versions"],
"vulnerable_functions": vulnerability["vulnerable_functions"],
"vulnerable_version_range": vulnerability["vulnerable_version_range"],
}
return {
"package": {
"ecosystem": vulnerability.package.ecosystem,
"name": vulnerability.package.name,
},
"patched_versions": vulnerability.patched_versions,
"vulnerable_functions": vulnerability.vulnerable_functions,
"vulnerable_version_range": vulnerability.vulnerable_version_range,
}
| 7,951
|
Python
|
.py
| 149
| 45.395973
| 110
| 0.604038
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,443
|
GlobalAdvisory.py
|
PyGithub_PyGithub/github/GlobalAdvisory.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
from github.AdvisoryBase import AdvisoryBase
from github.AdvisoryCreditDetailed import AdvisoryCreditDetailed
from github.AdvisoryVulnerability import AdvisoryVulnerability
from github.GithubObject import Attribute, NotSet
class GlobalAdvisory(AdvisoryBase):
"""
This class represents a GlobalAdvisory.
https://docs.github.com/en/rest/security-advisories/global-advisories
"""
def _initAttributes(self) -> None:
self._credits: Attribute[list[AdvisoryCreditDetailed]] = NotSet
self._github_reviewed_at: Attribute[datetime] = NotSet
self._nvd_published_at: Attribute[datetime] = NotSet
self._references: Attribute[list[str]] = NotSet
self._repository_advisory_url: Attribute[str] = NotSet
self._source_code_location: Attribute[str] = NotSet
self._type: Attribute[str] = NotSet
self._vulnerabilities: Attribute[list[AdvisoryVulnerability]] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"ghsa_id": self.ghsa_id, "summary": self.summary})
@property
def credits(
self,
) -> list[AdvisoryCreditDetailed]:
return self._credits.value
@property
def github_reviewed_at(self) -> datetime:
return self._github_reviewed_at.value
@property
def nvd_published_at(self) -> datetime:
return self._nvd_published_at.value
@property
def references(self) -> list[str]:
return self._references.value
@property
def repository_advisory_url(self) -> str:
return self._repository_advisory_url.value
@property
def source_code_location(self) -> str:
return self._source_code_location.value
@property
def type(self) -> str:
return self._type.value
@property
def vulnerabilities(self) -> list[AdvisoryVulnerability]:
return self._vulnerabilities.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "credits" in attributes: # pragma no branch
self._credits = self._makeListOfClassesAttribute(
AdvisoryCreditDetailed,
attributes["credits"],
)
if "github_reviewed_at" in attributes: # pragma no branch
assert attributes["github_reviewed_at"] is None or isinstance(
attributes["github_reviewed_at"], str
), attributes["github_reviewed_at"]
self._github_reviewed_at = self._makeDatetimeAttribute(attributes["github_reviewed_at"])
if "nvd_published_at" in attributes: # pragma no branch
assert attributes["nvd_published_at"] is None or isinstance(
attributes["nvd_published_at"], str
), attributes["nvd_published_at"]
self._nvd_published_at = self._makeDatetimeAttribute(attributes["nvd_published_at"])
if "references" in attributes: # pragma no branch
self._references = self._makeListOfStringsAttribute(attributes["references"])
if "repository_advisory_url" in attributes: # pragma no branch
self._repository_advisory_url = self._makeStringAttribute(attributes["repository_advisory_url"])
if "source_code_location" in attributes: # pragma no branch
self._source_code_location = self._makeStringAttribute(attributes["source_code_location"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "vulnerabilities" in attributes:
self._vulnerabilities = self._makeListOfClassesAttribute(
AdvisoryVulnerability,
attributes["vulnerabilities"],
)
super()._useAttributes(attributes)
| 5,840
|
Python
|
.py
| 104
| 49.442308
| 108
| 0.582022
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,444
|
GitBlob.py
|
PyGithub_PyGithub/github/GitBlob.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class GitBlob(CompletableGithubObject):
"""
This class represents GitBlobs.
The reference can be found here
https://docs.github.com/en/rest/reference/git#blobs
"""
def _initAttributes(self) -> None:
self._content: Attribute[str] = NotSet
self._encoding: Attribute[str] = NotSet
self._sha: Attribute[str] = NotSet
self._size: Attribute[int] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"sha": self._sha.value})
@property
def content(self) -> str:
self._completeIfNotSet(self._content)
return self._content.value
@property
def encoding(self) -> str:
self._completeIfNotSet(self._encoding)
return self._encoding.value
@property
def sha(self) -> str:
self._completeIfNotSet(self._sha)
return self._sha.value
@property
def size(self) -> int:
self._completeIfNotSet(self._size)
return self._size.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "content" in attributes: # pragma no branch
self._content = self._makeStringAttribute(attributes["content"])
if "encoding" in attributes: # pragma no branch
self._encoding = self._makeStringAttribute(attributes["encoding"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "size" in attributes: # pragma no branch
self._size = self._makeIntAttribute(attributes["size"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 4,945
|
Python
|
.py
| 84
| 54.130952
| 80
| 0.520941
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,445
|
RepositoryKey.py
|
PyGithub_PyGithub/github/RepositoryKey.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Srijan Choudhary <srijan4@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Jimmy Zelinskie <jimmy.zelinskie+git@gmail.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Laurent Raufaste <analogue@glop.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Floyd Hightower <floyd.hightower27@gmail.com> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Ramiro Morales <ramiro@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class RepositoryKey(CompletableGithubObject):
"""
This class represents RepositoryKeys.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#deploy-keys
"""
def _initAttributes(self) -> None:
self._added_by: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._id: Attribute[int] = NotSet
self._key: Attribute[str] = NotSet
self._last_used: Attribute[datetime] = NotSet
self._title: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
self._verified: Attribute[bool] = NotSet
self._read_only: Attribute[bool] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "title": self._title.value})
@property
def added_by(self) -> str:
self._completeIfNotSet(self._added_by)
return self._added_by.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def key(self) -> str:
self._completeIfNotSet(self._key)
return self._key.value
@property
def last_used(self) -> datetime:
self._completeIfNotSet(self._last_used)
return self._last_used.value
@property
def title(self) -> str:
self._completeIfNotSet(self._title)
return self._title.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def verified(self) -> bool:
self._completeIfNotSet(self._verified)
return self._verified.value
@property
def read_only(self) -> bool:
self._completeIfNotSet(self._read_only)
return self._read_only.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/keys/{id} <https://docs.github.com/en/rest/reference/repos#deploy-keys>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "added_by" in attributes: # pragma no branch
self._added_by = self._makeStringAttribute(attributes["added_by"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "key" in attributes: # pragma no branch
self._key = self._makeStringAttribute(attributes["key"])
if "last_used" in attributes: # pragma no branch
assert attributes["last_used"] is None or isinstance(attributes["last_used"], str), attributes["last_used"]
self._last_used = self._makeDatetimeAttribute(attributes["last_used"])
if "title" in attributes: # pragma no branch
self._title = self._makeStringAttribute(attributes["title"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "verified" in attributes: # pragma no branch
self._verified = self._makeBoolAttribute(attributes["verified"])
if "read_only" in attributes: # pragma no branch
self._read_only = self._makeBoolAttribute(attributes["read_only"])
| 7,320
|
Python
|
.py
| 127
| 52.110236
| 119
| 0.55283
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,446
|
GitRef.py
|
PyGithub_PyGithub/github/GitRef.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.GithubObject
import github.GitObject
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional
if TYPE_CHECKING:
from github.GitObject import GitObject
class GitRef(CompletableGithubObject):
"""
This class represents GitRefs.
The reference can be found here
https://docs.github.com/en/rest/reference/git#references
"""
def _initAttributes(self) -> None:
self._object: Attribute[GitObject] = NotSet
self._ref: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"ref": self._ref.value})
@property
def object(self) -> GitObject:
self._completeIfNotSet(self._object)
return self._object.value
@property
def ref(self) -> str:
self._completeIfNotSet(self._ref)
return self._ref.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/git/refs/{ref} <https://docs.github.com/en/rest/reference/git#references>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(self, sha: str, force: Opt[bool] = NotSet) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/git/refs/{ref} <https://docs.github.com/en/rest/reference/git#references>`_
"""
assert isinstance(sha, str), sha
assert is_optional(force, bool), force
post_parameters = NotSet.remove_unset_items({"sha": sha, "force": force})
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "object" in attributes: # pragma no branch
self._object = self._makeClassAttribute(github.GitObject.GitObject, attributes["object"])
if "ref" in attributes: # pragma no branch
self._ref = self._makeStringAttribute(attributes["ref"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 5,497
|
Python
|
.py
| 91
| 55.89011
| 121
| 0.538961
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,447
|
ContentFile.py
|
PyGithub_PyGithub/github/ContentFile.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Thialfihar <thi@thialfihar.org> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 h.shi <10385628+AnYeMoWang@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import base64
from typing import TYPE_CHECKING, Any
import github.GithubObject
import github.Repository
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, _ValuedAttribute
if TYPE_CHECKING:
from github.License import License
from github.Repository import Repository
class ContentFile(CompletableGithubObject):
"""
This class represents ContentFiles.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#contents
"""
def _initAttributes(self) -> None:
self._content: Attribute[str] = NotSet
self._download_url: Attribute[str] = NotSet
self._encoding: Attribute[str] = NotSet
self._git_url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._license: Attribute[License] = NotSet
self._name: Attribute[str] = NotSet
self._path: Attribute[str] = NotSet
self._repository: Attribute[Repository] = NotSet
self._sha: Attribute[str] = NotSet
self._size: Attribute[int] = NotSet
self._type: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
self._text_matches: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"path": self._path.value})
@property
def content(self) -> str:
self._completeIfNotSet(self._content)
return self._content.value
@property
def decoded_content(self) -> bytes:
assert self.encoding == "base64", f"unsupported encoding: {self.encoding}"
return base64.b64decode(bytearray(self.content, "utf-8"))
@property
def download_url(self) -> str:
self._completeIfNotSet(self._download_url)
return self._download_url.value
@property
def encoding(self) -> str:
self._completeIfNotSet(self._encoding)
return self._encoding.value
@property
def git_url(self) -> str:
self._completeIfNotSet(self._git_url)
return self._git_url.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def license(self) -> License:
self._completeIfNotSet(self._license)
return self._license.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def path(self) -> str:
self._completeIfNotSet(self._path)
return self._path.value
@property
def repository(self) -> Repository:
if self._repository is NotSet:
# The repository was not set automatically, so it must be looked up by url.
repo_url = "/".join(self.url.split("/")[:6]) # pragma no cover (Should be covered)
self._repository = _ValuedAttribute(
github.Repository.Repository(self._requester, self._headers, {"url": repo_url}, completed=False)
) # pragma no cover (Should be covered)
return self._repository.value
@property
def sha(self) -> str:
self._completeIfNotSet(self._sha)
return self._sha.value
@property
def size(self) -> int:
self._completeIfNotSet(self._size)
return self._size.value
@property
def type(self) -> str:
self._completeIfNotSet(self._type)
return self._type.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def text_matches(self) -> str:
self._completeIfNotSet(self._text_matches)
return self._text_matches.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "content" in attributes: # pragma no branch
self._content = self._makeStringAttribute(attributes["content"])
if "download_url" in attributes: # pragma no branch
self._download_url = self._makeStringAttribute(attributes["download_url"])
if "encoding" in attributes: # pragma no branch
self._encoding = self._makeStringAttribute(attributes["encoding"])
if "git_url" in attributes: # pragma no branch
self._git_url = self._makeStringAttribute(attributes["git_url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "license" in attributes: # pragma no branch
self._license = self._makeClassAttribute(github.License.License, attributes["license"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(attributes["path"])
if "repository" in attributes: # pragma no branch
self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "size" in attributes: # pragma no branch
self._size = self._makeIntAttribute(attributes["size"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "text_matches" in attributes: # pragma no branch
self._text_matches = self._makeListOfDictsAttribute(attributes["text_matches"])
| 9,058
|
Python
|
.py
| 168
| 47.619048
| 112
| 0.580212
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,448
|
Hook.py
|
PyGithub_PyGithub/github/Hook.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.GithubObject
import github.HookResponse
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional, is_optional_list
class Hook(CompletableGithubObject):
"""
This class represents Hooks.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#webhooks
"""
def _initAttributes(self) -> None:
self._active: Attribute[bool] = NotSet
self._config: Attribute[dict] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._events: Attribute[list[str]] = NotSet
self._id: Attribute[int] = NotSet
self._last_response: Attribute[github.HookResponse.HookResponse] = NotSet
self._name: Attribute[str] = NotSet
self._test_url: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._ping_url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "url": self._url.value})
@property
def active(self) -> bool:
self._completeIfNotSet(self._active)
return self._active.value
@property
def config(self) -> dict:
self._completeIfNotSet(self._config)
return self._config.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def events(self) -> list[str]:
self._completeIfNotSet(self._events)
return self._events.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def last_response(self) -> github.HookResponse.HookResponse:
self._completeIfNotSet(self._last_response)
return self._last_response.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def test_url(self) -> str:
self._completeIfNotSet(self._test_url)
return self._test_url.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def ping_url(self) -> str:
self._completeIfNotSet(self._ping_url)
return self._ping_url.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/hooks/{id} <https://docs.github.com/en/rest/reference/repos#webhooks>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(
self,
name: str,
config: dict,
events: Opt[list[str]] = NotSet,
add_events: Opt[list[str]] = NotSet,
remove_events: Opt[list[str]] = NotSet,
active: Opt[bool] = NotSet,
) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/hooks/{id} <https://docs.github.com/en/rest/reference/repos#webhooks>`_
"""
assert isinstance(name, str), name
assert isinstance(config, dict), config
assert is_optional_list(events, str), events
assert is_optional_list(add_events, str), add_events
assert is_optional_list(remove_events, str), remove_events
assert is_optional(active, bool), active
post_parameters = NotSet.remove_unset_items(
{
"name": name,
"config": config,
"events": events,
"add_events": add_events,
"remove_events": remove_events,
"active": active,
}
)
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def test(self) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/hooks/{id}/tests <https://docs.github.com/en/rest/reference/repos#webhooks>`_
"""
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/tests")
def ping(self) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/hooks/{id}/pings <https://docs.github.com/en/rest/reference/repos#webhooks>`_
"""
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/pings")
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "active" in attributes: # pragma no branch
self._active = self._makeBoolAttribute(attributes["active"])
if "config" in attributes: # pragma no branch
self._config = self._makeDictAttribute(attributes["config"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "events" in attributes: # pragma no branch
self._events = self._makeListOfStringsAttribute(attributes["events"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "last_response" in attributes: # pragma no branch
self._last_response = self._makeClassAttribute(
github.HookResponse.HookResponse, attributes["last_response"]
)
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "test_url" in attributes: # pragma no branch
self._test_url = self._makeStringAttribute(attributes["test_url"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "ping_url" in attributes: # pragma no branch
self._ping_url = self._makeStringAttribute(attributes["ping_url"])
| 9,370
|
Python
|
.py
| 180
| 45.155556
| 121
| 0.567983
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,449
|
TeamDiscussion.py
|
PyGithub_PyGithub/github/TeamDiscussion.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Chris McBride <thehighlander@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Benoit Latinier <benoit@latinier.fr> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 Yossarian King <yggy@blackbirdinteractive.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.GithubObject
import github.NamedUser
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class TeamDiscussion(CompletableGithubObject):
"""
This class represents TeamDiscussions.
The reference can be found here
https://docs.github.com/en/rest/reference/teams#discussions
"""
def _initAttributes(self) -> None:
self._author: Attribute[github.NamedUser.NamedUser] = NotSet
self._body: Attribute[str] = NotSet
self._body_html: Attribute[str] = NotSet
self._body_version: Attribute[str] = NotSet
self._comments_count: Attribute[int] = NotSet
self._comments_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._html_url: Attribute[str] = NotSet
self._last_edited_at: Attribute[datetime] = NotSet
self._node_id: Attribute[str] = NotSet
self._number: Attribute[int] = NotSet
self._pinned: Attribute[bool] = NotSet
self._private: Attribute[bool] = NotSet
self._team_url: Attribute[str] = NotSet
self._title: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"number": self._number.value, "title": self._title.value})
@property
def author(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._author)
return self._author.value
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def body_html(self) -> str:
self._completeIfNotSet(self._body_html)
return self._body_html.value
@property
def body_version(self) -> str:
self._completeIfNotSet(self._body_version)
return self._body_version.value
@property
def comments_count(self) -> int:
self._completeIfNotSet(self._comments_count)
return self._comments_count.value
@property
def comments_url(self) -> str:
self._completeIfNotSet(self._comments_url)
return self._comments_url.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def last_edited_at(self) -> datetime:
self._completeIfNotSet(self._last_edited_at)
return self._last_edited_at.value
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
@property
def number(self) -> int:
self._completeIfNotSet(self._number)
return self._number.value
@property
def pinned(self) -> bool:
self._completeIfNotSet(self._pinned)
return self._pinned.value
@property
def private(self) -> bool:
self._completeIfNotSet(self._private)
return self._private.value
@property
def team_url(self) -> str:
self._completeIfNotSet(self._team_url)
return self._team_url.value
@property
def title(self) -> str:
self._completeIfNotSet(self._title)
return self._title.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "author" in attributes: # pragma no branch
self._author = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["author"])
if "body" in attributes: # pragma no branch
self._body = self._makeStringAttribute(attributes["body"])
if "body_html" in attributes: # pragma no branch
self._body_html = self._makeStringAttribute(attributes["body_html"])
if "body_version" in attributes: # pragma no branch
self._body_version = self._makeStringAttribute(attributes["body_version"])
if "comments_count" in attributes: # pragma no branch
self._comments_count = self._makeIntAttribute(attributes["comments_count"])
if "comments_url" in attributes: # pragma no branch
self._comments_url = self._makeStringAttribute(attributes["comments_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "last_edited_at" in attributes: # pragma no branch
self._last_edited_at = self._makeDatetimeAttribute(attributes["last_edited_at"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "number" in attributes: # pragma no branch
self._number = self._makeIntAttribute(attributes["number"])
if "pinned" in attributes: # pragma no branch
self._pinned = self._makeBoolAttribute(attributes["pinned"])
if "private" in attributes: # pragma no branch
self._private = self._makeBoolAttribute(attributes["private"])
if "team_url" in attributes: # pragma no branch
self._team_url = self._makeStringAttribute(attributes["team_url"])
if "title" in attributes:
self._title = self._makeStringAttribute(attributes["title"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 9,580
|
Python
|
.py
| 178
| 47.477528
| 101
| 0.58624
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,450
|
CommitCombinedStatus.py
|
PyGithub_PyGithub/github/CommitCombinedStatus.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 John Eskew <jeskew@edx.org> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
import github.CommitStatus
import github.Repository
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class CommitCombinedStatus(NonCompletableGithubObject):
"""
This class represents CommitCombinedStatuses.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#statuses
"""
def _initAttributes(self) -> None:
self._state: Attribute[str] = NotSet
self._sha: Attribute[str] = NotSet
self._total_count: Attribute[int] = NotSet
self._commit_url: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
self._repository: Attribute[github.Repository.Repository] = NotSet
self._statuses: Attribute[list[github.CommitStatus.CommitStatus]] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"sha": self._sha.value, "state": self._state.value})
@property
def state(self) -> str:
return self._state.value
@property
def sha(self) -> str:
return self._sha.value
@property
def total_count(self) -> int:
return self._total_count.value
@property
def commit_url(self) -> str:
return self._commit_url.value
@property
def url(self) -> str:
return self._url.value
@property
def repository(self) -> github.Repository.Repository:
return self._repository.value
@property
def statuses(self) -> list[github.CommitStatus.CommitStatus]:
return self._statuses.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
if "total_count" in attributes: # pragma no branch
self._total_count = self._makeIntAttribute(attributes["total_count"])
if "commit_url" in attributes: # pragma no branch
self._commit_url = self._makeStringAttribute(attributes["commit_url"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "repository" in attributes: # pragma no branch
self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"])
if "statuses" in attributes: # pragma no branch
self._statuses = self._makeListOfClassesAttribute(github.CommitStatus.CommitStatus, attributes["statuses"])
| 5,811
|
Python
|
.py
| 96
| 55.729167
| 119
| 0.552124
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,451
|
CodeScanAlert.py
|
PyGithub_PyGithub/github/CodeScanAlert.py
|
############################ Copyrights and license ############################
# #
# Copyright 2022 Eric Nieuwland <eric.nieuwland@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.CodeScanAlertInstance
import github.CodeScanRule
import github.CodeScanTool
import github.GithubObject
import github.NamedUser
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
from github.PaginatedList import PaginatedList
class CodeScanAlert(NonCompletableGithubObject):
"""
This class represents alerts from code scanning.
The reference can be found here
https://docs.github.com/en/rest/reference/code-scanning.
"""
def _initAttributes(self) -> None:
self._number: Attribute[int] = NotSet
self._rule: Attribute[github.CodeScanRule.CodeScanRule] = NotSet
self._tool: Attribute[github.CodeScanTool.CodeScanTool] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._dismissed_at: Attribute[datetime | None] = NotSet
self._dismissed_by: Attribute[github.NamedUser.NamedUser | None] = NotSet
self._dismissed_reason: Attribute[str | None] = NotSet
self._url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._instances_url: Attribute[str] = NotSet
self._most_recent_instance: Attribute[github.CodeScanAlertInstance.CodeScanAlertInstance] = NotSet
self._state: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"number": self.number})
@property
def number(self) -> int:
return self._number.value
@property
def rule(self) -> github.CodeScanRule.CodeScanRule:
return self._rule.value
@property
def tool(self) -> github.CodeScanTool.CodeScanTool:
return self._tool.value
@property
def created_at(self) -> datetime:
return self._created_at.value
@property
def dismissed_at(self) -> datetime | None:
return self._dismissed_at.value
@property
def dismissed_by(self) -> github.NamedUser.NamedUser | None:
return self._dismissed_by.value
@property
def dismissed_reason(self) -> str | None:
return self._dismissed_reason.value
@property
def url(self) -> str:
return self._url.value
@property
def html_url(self) -> str:
return self._html_url.value
@property
def instances_url(self) -> str:
return self._instances_url.value
@property
def most_recent_instance(self) -> github.CodeScanAlertInstance.CodeScanAlertInstance:
return self._most_recent_instance.value
@property
def state(self) -> str:
return self._state.value
def get_instances(self) -> PaginatedList[github.CodeScanAlertInstance.CodeScanAlertInstance]:
"""
Get instances.
:calls: `GET` on the URL for instances as provided by Github.
"""
return PaginatedList(
github.CodeScanAlertInstance.CodeScanAlertInstance,
self._requester,
self.instances_url,
None,
)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "number" in attributes: # pragma no branch
self._number = self._makeIntAttribute(attributes["number"])
if "rule" in attributes: # pragma no branch
self._rule = self._makeClassAttribute(github.CodeScanRule.CodeScanRule, attributes["rule"])
if "tool" in attributes: # pragma no branch
self._tool = self._makeClassAttribute(github.CodeScanTool.CodeScanTool, attributes["tool"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "dismissed_at" in attributes: # pragma no branch
self._dismissed_at = self._makeDatetimeAttribute(attributes["dismissed_at"])
if "dismissed_by" in attributes: # pragma no branch
self._dismissed_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["dismissed_by"])
if "dismissed_reason" in attributes: # pragma no branch
self._dismissed_reason = self._makeStringAttribute(attributes["dismissed_reason"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "instances_url" in attributes: # pragma no branch
self._instances_url = self._makeStringAttribute(attributes["instances_url"])
if "most_recent_instance" in attributes: # pragma no branch
self._most_recent_instance = self._makeClassAttribute(
github.CodeScanAlertInstance.CodeScanAlertInstance,
attributes["most_recent_instance"],
)
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
| 7,086
|
Python
|
.py
| 132
| 47.075758
| 113
| 0.600058
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,452
|
PullRequestMergeStatus.py
|
PyGithub_PyGithub/github/PullRequestMergeStatus.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class PullRequestMergeStatus(NonCompletableGithubObject):
"""
This class represents PullRequestMergeStatuses.
The reference can be found here
https://docs.github.com/en/rest/reference/pulls#check-if-a-pull-request-has-been-merged
"""
def _initAttributes(self) -> None:
self._merged: Attribute[bool] = NotSet
self._message: Attribute[str] = NotSet
self._sha: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"sha": self._sha.value, "merged": self._merged.value})
@property
def merged(self) -> bool:
return self._merged.value
@property
def message(self) -> str:
return self._message.value
@property
def sha(self) -> str:
return self._sha.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "merged" in attributes: # pragma no branch
self._merged = self._makeBoolAttribute(attributes["merged"])
if "message" in attributes: # pragma no branch
self._message = self._makeStringAttribute(attributes["message"])
if "sha" in attributes: # pragma no branch
self._sha = self._makeStringAttribute(attributes["sha"])
| 4,503
|
Python
|
.py
| 69
| 61.594203
| 91
| 0.50995
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,453
|
OrganizationVariable.py
|
PyGithub_PyGithub/github/OrganizationVariable.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Mauricio Alejandro Martínez Pacheco <mauricio.martinez@premise.com>#
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict
from github.GithubObject import Attribute, NotSet
from github.PaginatedList import PaginatedList
from github.Repository import Repository
from github.Variable import Variable
class OrganizationVariable(Variable):
"""
This class represents a org level GitHub variable.
The reference can be found here
https://docs.github.com/en/rest/actions/variables
"""
def _initAttributes(self) -> None:
self._name: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._visibility: Attribute[str] = NotSet
self._selected_repositories: Attribute[PaginatedList[Repository]] = NotSet
self._selected_repositories_url: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
@property
def visibility(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._visibility)
return self._visibility.value
@property
def selected_repositories(self) -> PaginatedList[Repository]:
return PaginatedList(
Repository,
self._requester,
self._selected_repositories_url.value,
None,
list_item="repositories",
)
def edit(
self,
value: str,
visibility: str = "all",
) -> bool:
"""
:calls: `PATCH /orgs/{org}/actions/variables/{variable_name} <https://docs.github.com/en/rest/reference/actions/variables#update-an-organization-variable>`_
:param variable_name: string
:param value: string
:param visibility: string
:rtype: bool
"""
assert isinstance(value, str), value
assert isinstance(visibility, str), visibility
patch_parameters: Dict[str, Any] = {
"name": self.name,
"value": value,
"visibility": visibility,
}
status, _, _ = self._requester.requestJson(
"PATCH",
f"{self.url}/actions/variables/{self.name}",
input=patch_parameters,
)
return status == 204
def add_repo(self, repo: Repository) -> bool:
"""
:calls: 'PUT {org_url}/actions/variables/{variable_name} <https://docs.github.com/en/rest/actions/variables#add-selected-repository-to-an-organization-secret>`_
:param repo: github.Repository.Repository
:rtype: bool
"""
if self.visibility != "selected":
return False
self._requester.requestJsonAndCheck("PUT", f"{self._selected_repositories_url.value}/{repo.id}")
return True
def remove_repo(self, repo: Repository) -> bool:
"""
:calls: 'DELETE {org_url}/actions/variables/{variable_name} <https://docs.github.com/en/rest/actions/variables#add-selected-repository-to-an-organization-secret>`_
:param repo: github.Repository.Repository
:rtype: bool
"""
if self.visibility != "selected":
return False
self._requester.requestJsonAndCheck("DELETE", f"{self._selected_repositories_url.value}/{repo.id}")
return True
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "name" in attributes:
self._name = self._makeStringAttribute(attributes["name"])
if "created_at" in attributes:
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "updated_at" in attributes:
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "visibility" in attributes:
self._visibility = self._makeStringAttribute(attributes["visibility"])
if "selected_repositories_url" in attributes:
self._selected_repositories_url = self._makeStringAttribute(attributes["selected_repositories_url"])
if "url" in attributes:
self._url = self._makeStringAttribute(attributes["url"])
| 5,984
|
Python
|
.py
| 118
| 43.550847
| 171
| 0.565886
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,454
|
RepositoryAdvisory.py
|
PyGithub_PyGithub/github/RepositoryAdvisory.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any, Iterable
import github.AdvisoryVulnerability
import github.NamedUser
from github.AdvisoryBase import AdvisoryBase
from github.AdvisoryCredit import AdvisoryCredit, Credit
from github.AdvisoryCreditDetailed import AdvisoryCreditDetailed
from github.GithubObject import Attribute, NotSet, Opt
if TYPE_CHECKING:
from github.AdvisoryVulnerability import AdvisoryVulnerability, AdvisoryVulnerabilityInput
from github.NamedUser import NamedUser
class RepositoryAdvisory(AdvisoryBase):
"""
This class represents a RepositoryAdvisory.
The reference can be found here
https://docs.github.com/en/rest/security-advisories/repository-advisories
"""
def _initAttributes(self) -> None:
self._author: Attribute[NamedUser] = NotSet
self._closed_at: Attribute[datetime] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._credits: Attribute[list[AdvisoryCredit]] = NotSet
self._credits_detailed: Attribute[list[AdvisoryCreditDetailed]] = NotSet
self._cwe_ids: Attribute[list[str]] = NotSet
self._state: Attribute[str] = NotSet
self._vulnerabilities: Attribute[list[AdvisoryVulnerability]] = NotSet
super()._initAttributes()
@property
def author(self) -> NamedUser:
return self._author.value
@property
def closed_at(self) -> datetime:
return self._closed_at.value
@property
def created_at(self) -> datetime:
return self._created_at.value
@property
def credits(
self,
) -> list[AdvisoryCredit]:
return self._credits.value
@property
def credits_detailed(
self,
) -> list[AdvisoryCreditDetailed]:
return self._credits_detailed.value
@property
def cwe_ids(self) -> list[str]:
return self._cwe_ids.value
@property
def state(self) -> str:
return self._state.value
@property
def vulnerabilities(self) -> list[AdvisoryVulnerability]:
return self._vulnerabilities.value
def add_vulnerability(
self,
ecosystem: str,
package_name: str | None = None,
vulnerable_version_range: str | None = None,
patched_versions: str | None = None,
vulnerable_functions: list[str] | None = None,
) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`\
"""
return self.add_vulnerabilities(
[
{
"package": {
"ecosystem": ecosystem,
"name": package_name,
},
"vulnerable_version_range": vulnerable_version_range,
"patched_versions": patched_versions,
"vulnerable_functions": vulnerable_functions,
}
]
)
def add_vulnerabilities(self, vulnerabilities: Iterable[AdvisoryVulnerabilityInput]) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`
"""
assert isinstance(vulnerabilities, Iterable), vulnerabilities
for vulnerability in vulnerabilities:
github.AdvisoryVulnerability.AdvisoryVulnerability._validate_vulnerability(vulnerability)
post_parameters = {
"vulnerabilities": [
github.AdvisoryVulnerability.AdvisoryVulnerability._to_github_dict(vulnerability)
for vulnerability in (self.vulnerabilities + list(vulnerabilities))
]
}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=post_parameters,
)
self._useAttributes(data)
def offer_credit(
self,
login_or_user: str | github.NamedUser.NamedUser,
credit_type: str,
) -> None:
"""
Offers credit to a user for a vulnerability in a repository.
Unless you are giving credit to yourself, the user having credit offered will need to explicitly accept the credit.
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`
"""
self.offer_credits([{"login": login_or_user, "type": credit_type}])
def offer_credits(
self,
credited: Iterable[Credit],
) -> None:
"""
Offers credit to a list of users for a vulnerability in a repository.
Unless you are giving credit to yourself, the user having credit offered will need to explicitly accept the credit.
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`
:param credited: iterable of dict with keys "login" and "type"
"""
assert isinstance(credited, Iterable), credited
for credit in credited:
AdvisoryCredit._validate_credit(credit)
patch_parameters = {
"credits": [AdvisoryCredit._to_github_dict(credit) for credit in (self.credits + list(credited))]
}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
def revoke_credit(self, login_or_user: str | github.NamedUser.NamedUser) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`_
"""
assert isinstance(login_or_user, (str, github.NamedUser.NamedUser)), login_or_user
if isinstance(login_or_user, github.NamedUser.NamedUser):
login_or_user = login_or_user.login
patch_parameters = {
"credits": [
dict(login=credit.login, type=credit.type) for credit in self.credits if credit.login != login_or_user
]
}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
def clear_credits(self) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`_
"""
patch_parameters: dict[str, Any] = {"credits": []}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
def edit(
self,
summary: Opt[str] = NotSet,
description: Opt[str] = NotSet,
severity_or_cvss_vector_string: Opt[str] = NotSet,
cve_id: Opt[str] = NotSet,
vulnerabilities: Opt[Iterable[AdvisoryVulnerabilityInput]] = NotSet,
cwe_ids: Opt[Iterable[str]] = NotSet,
credits: Opt[Iterable[Credit]] = NotSet,
state: Opt[str] = NotSet,
) -> RepositoryAdvisory:
"""
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`_
"""
assert summary is NotSet or isinstance(summary, str), summary
assert description is NotSet or isinstance(description, str), description
assert severity_or_cvss_vector_string is NotSet or isinstance(
severity_or_cvss_vector_string, str
), severity_or_cvss_vector_string
assert cve_id is NotSet or isinstance(cve_id, str), cve_id
assert vulnerabilities is NotSet or isinstance(vulnerabilities, Iterable), vulnerabilities
if isinstance(vulnerabilities, Iterable):
for vulnerability in vulnerabilities:
github.AdvisoryVulnerability.AdvisoryVulnerability._validate_vulnerability(vulnerability)
assert cwe_ids is NotSet or (
isinstance(cwe_ids, Iterable) and all(isinstance(element, str) for element in cwe_ids)
), cwe_ids
if isinstance(credits, Iterable):
for credit in credits:
github.AdvisoryCredit.AdvisoryCredit._validate_credit(credit)
assert state is NotSet or isinstance(state, str), state
patch_parameters: dict[str, Any] = {}
if summary is not NotSet:
patch_parameters["summary"] = summary
if description is not NotSet:
patch_parameters["description"] = description
if isinstance(severity_or_cvss_vector_string, str):
if severity_or_cvss_vector_string.startswith("CVSS:"):
patch_parameters["cvss_vector_string"] = severity_or_cvss_vector_string
else:
patch_parameters["severity"] = severity_or_cvss_vector_string
if cve_id is not NotSet:
patch_parameters["cve_id"] = cve_id
if isinstance(vulnerabilities, Iterable):
patch_parameters["vulnerabilities"] = [
github.AdvisoryVulnerability.AdvisoryVulnerability._to_github_dict(vulnerability)
for vulnerability in vulnerabilities
]
if isinstance(cwe_ids, Iterable):
patch_parameters["cwe_ids"] = list(cwe_ids)
if isinstance(credits, Iterable):
patch_parameters["credits"] = [
github.AdvisoryCredit.AdvisoryCredit._to_github_dict(credit) for credit in credits
]
if state is not NotSet:
patch_parameters["state"] = state
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
return self
def accept_report(self) -> None:
"""
Accepts the advisory reported from an external reporter via private vulnerability reporting.
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`
"""
patch_parameters = {"state": "draft"}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
def publish(self) -> None:
"""
Publishes the advisory.
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`
"""
patch_parameters = {"state": "published"}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
def request_cve(self) -> None:
"""
Requests a CVE for the advisory.
:calls: `POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve <https://docs.github.com/en/rest/security-advisories/repository-advisories#request-a-cve-for-a-repository-security-advisory>`_
"""
self._requester.requestJsonAndCheck(
"POST",
self.url + "/cve",
)
def close(self) -> None:
"""
Closes the advisory.
:calls: `PATCH /repos/{owner}/{repo}/security-advisories/:advisory_id <https://docs.github.com/en/rest/security-advisories/repository-advisories>`
"""
patch_parameters = {"state": "closed"}
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
)
self._useAttributes(data)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "author" in attributes: # pragma no branch
self._author = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["author"])
if "closed_at" in attributes: # pragma no branch
assert attributes["closed_at"] is None or isinstance(attributes["closed_at"], str), attributes["closed_at"]
self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"])
if "created_at" in attributes: # pragma no branch
assert attributes["created_at"] is None or isinstance(attributes["created_at"], str), attributes[
"created_at"
]
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "credits" in attributes: # pragma no branch
self._credits = self._makeListOfClassesAttribute(
AdvisoryCredit,
attributes["credits"],
)
if "credits_detailed" in attributes: # pragma no branch
self._credits_detailed = self._makeListOfClassesAttribute(
AdvisoryCreditDetailed,
attributes["credits_detailed"],
)
if "cwe_ids" in attributes: # pragma no branch
self._cwe_ids = self._makeListOfStringsAttribute(attributes["cwe_ids"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "vulnerabilities" in attributes:
self._vulnerabilities = self._makeListOfClassesAttribute(
github.AdvisoryVulnerability.AdvisoryVulnerability,
attributes["vulnerabilities"],
)
super()._useAttributes(attributes)
| 16,007
|
Python
|
.py
| 328
| 39.597561
| 204
| 0.606805
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,455
|
OrganizationDependabotAlert.py
|
PyGithub_PyGithub/github/OrganizationDependabotAlert.py
|
############################ Copyrights and license ############################
# #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# #
# 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 __future__ import annotations
from typing import Any
from github.DependabotAlert import DependabotAlert
from github.GithubObject import Attribute, NotSet
from github.Repository import Repository
class OrganizationDependabotAlert(DependabotAlert):
"""
This class represents a Dependabot alert on an organization.
The reference can be found here
https://docs.github.com/en/rest/dependabot/alerts#list-dependabot-alerts-for-an-organization
"""
def _initAttributes(self) -> None:
super()._initAttributes()
self._repository: Attribute[Repository] = NotSet
@property
def repository(self) -> Repository:
return self._repository.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
super()._useAttributes(attributes)
if "repository" in attributes:
self._repository = self._makeClassAttribute(Repository, attributes["repository"])
| 2,803
|
Python
|
.py
| 44
| 60.477273
| 96
| 0.505275
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,456
|
PullRequestComment.py
|
PyGithub_PyGithub/github/PullRequestComment.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Michael Stead <michael.stead@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Nicolas Agustín Torres <nicolastrres@gmail.com> #
# Copyright 2018 Jess Morgan <979404+JessMorgan@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 per1234 <accounts@perglass.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Huan-Cheng Chang <changhc84@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Den Stroebel <stroebs@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.GithubObject
import github.NamedUser
import github.Reaction
from github import Consts
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
from github.PaginatedList import PaginatedList
class PullRequestComment(CompletableGithubObject):
"""
This class represents PullRequestComments.
The reference can be found here
https://docs.github.com/en/rest/reference/pulls#review-comments
"""
def _initAttributes(self) -> None:
self._body: Attribute[str] = NotSet
self._commit_id: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._diff_hunk: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._in_reply_to_id: Attribute[int] = NotSet
self._original_commit_id: Attribute[str] = NotSet
self._original_position: Attribute[int] = NotSet
self._path: Attribute[str] = NotSet
self._position: Attribute[int] = NotSet
self._pull_request_url: Attribute[str] = NotSet
self._pull_request_review_id: Attribute[int] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._user: Attribute[github.NamedUser.NamedUser] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "user": self._user.value})
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def commit_id(self) -> str:
self._completeIfNotSet(self._commit_id)
return self._commit_id.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def diff_hunk(self) -> str:
self._completeIfNotSet(self._diff_hunk)
return self._diff_hunk.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def in_reply_to_id(self) -> int:
self._completeIfNotSet(self._in_reply_to_id)
return self._in_reply_to_id.value
@property
def original_commit_id(self) -> str:
self._completeIfNotSet(self._original_commit_id)
return self._original_commit_id.value
@property
def original_position(self) -> int:
self._completeIfNotSet(self._original_position)
return self._original_position.value
@property
def path(self) -> str:
self._completeIfNotSet(self._path)
return self._path.value
@property
def position(self) -> int:
self._completeIfNotSet(self._position)
return self._position.value
@property
def pull_request_review_id(self) -> int:
self._completeIfNotSet(self._pull_request_review_id)
return self._pull_request_review_id.value
@property
def pull_request_url(self) -> str:
self._completeIfNotSet(self._pull_request_url)
return self._pull_request_url.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def user(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/pulls/comments/{number} <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
:rtype: None
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(self, body: str) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/pulls/comments/{number} <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
:param body: string
:rtype: None
"""
assert isinstance(body, str), body
post_parameters = {
"body": body,
}
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def get_reactions(self) -> PaginatedList[github.Reaction.Reaction]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/comments/{number}/reactions
<https://docs.github.com/en/rest/reference/reactions#list-reactions-for-a-pull-request-review-comment>`_
:return: :class: :class:`github.PaginatedList.PaginatedList` of :class:`github.Reaction.Reaction`
"""
return PaginatedList(
github.Reaction.Reaction,
self._requester,
f"{self.url}/reactions",
None,
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
def create_reaction(self, reaction_type: str) -> github.Reaction.Reaction:
"""
:calls: `POST /repos/{owner}/{repo}/pulls/comments/{number}/reactions
<https://docs.github.com/en/rest/reference/reactions#create-reaction-for-a-pull-request-review-comment>`_
:param reaction_type: string
:rtype: :class:`github.Reaction.Reaction`
"""
assert isinstance(reaction_type, str), reaction_type
post_parameters = {
"content": reaction_type,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/reactions",
input=post_parameters,
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)
def delete_reaction(self, reaction_id: int) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}
<https://docs.github.com/en/rest/reference/reactions#delete-a-pull-request-comment-reaction>`_
:param reaction_id: integer
:rtype: bool
"""
assert isinstance(reaction_id, int), reaction_id
status, _, _ = self._requester.requestJson(
"DELETE",
f"{self.url}/reactions/{reaction_id}",
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
return status == 204
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "body" in attributes: # pragma no branch
self._body = self._makeStringAttribute(attributes["body"])
if "commit_id" in attributes: # pragma no branch
self._commit_id = self._makeStringAttribute(attributes["commit_id"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "diff_hunk" in attributes: # pragma no branch
self._diff_hunk = self._makeStringAttribute(attributes["diff_hunk"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "in_reply_to_id" in attributes: # pragma no branch
self._in_reply_to_id = self._makeIntAttribute(attributes["in_reply_to_id"])
if "original_commit_id" in attributes: # pragma no branch
self._original_commit_id = self._makeStringAttribute(attributes["original_commit_id"])
if "original_position" in attributes: # pragma no branch
self._original_position = self._makeIntAttribute(attributes["original_position"])
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(attributes["path"])
if "position" in attributes: # pragma no branch
self._position = self._makeIntAttribute(attributes["position"])
if "pull_request_review_id" in attributes: # pragma no branch
self._pull_request_review_id = self._makeIntAttribute(attributes["pull_request_review_id"])
if "pull_request_url" in attributes: # pragma no branch
self._pull_request_url = self._makeStringAttribute(attributes["pull_request_url"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 12,679
|
Python
|
.py
| 240
| 45.716667
| 137
| 0.595825
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,457
|
Rate.py
|
PyGithub_PyGithub/github/Rate.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Nikolay Yurin <yurinnick93@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class Rate(NonCompletableGithubObject):
"""
This class represents Rates.
The reference can be found here
https://docs.github.com/en/rest/reference/rate-limit
"""
def _initAttributes(self) -> None:
self._limit: Attribute[int] = NotSet
self._remaining: Attribute[int] = NotSet
self._reset: Attribute[datetime] = NotSet
self._used: Attribute[int] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"limit": self._limit.value,
"remaining": self._remaining.value,
"reset": self._reset.value,
}
)
@property
def limit(self) -> int:
return self._limit.value
@property
def remaining(self) -> int:
return self._remaining.value
@property
def reset(self) -> datetime:
return self._reset.value
@property
def used(self) -> int:
return self._used.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "limit" in attributes: # pragma no branch
self._limit = self._makeIntAttribute(attributes["limit"])
if "remaining" in attributes: # pragma no branch
self._remaining = self._makeIntAttribute(attributes["remaining"])
if "reset" in attributes: # pragma no branch
self._reset = self._makeTimestampAttribute(attributes["reset"])
if "used" in attributes: # pragma no branch
self._used = self._makeIntAttribute(attributes["used"])
| 4,848
|
Python
|
.py
| 82
| 54.353659
| 80
| 0.509152
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,458
|
EnterpriseConsumedLicenses.py
|
PyGithub_PyGithub/github/EnterpriseConsumedLicenses.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 YugoHino <henom06@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
from github.NamedEnterpriseUser import NamedEnterpriseUser
from github.PaginatedList import PaginatedList
class EnterpriseConsumedLicenses(CompletableGithubObject):
"""
This class represents license consumed by enterprises.
The reference can be found here
https://docs.github.com/en/enterprise-cloud@latest/rest/enterprise-admin/license#list-enterprise-consumed-licenses
"""
def _initAttributes(self) -> None:
self._total_seats_consumed: Attribute[int] = NotSet
self._total_seats_purchased: Attribute[int] = NotSet
self._enterprise: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"enterprise": self._enterprise.value})
@property
def total_seats_consumed(self) -> int:
return self._total_seats_consumed.value
@property
def total_seats_purchased(self) -> int:
return self._total_seats_purchased.value
@property
def enterprise(self) -> str:
self._completeIfNotSet(self._enterprise)
return self._enterprise.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def get_users(self) -> PaginatedList[NamedEnterpriseUser]:
"""
:calls: `GET /enterprises/{enterprise}/consumed-licenses <https://docs.github.com/en/enterprise-cloud@latest/rest/enterprise-admin/license#list-enterprise-consumed-licenses>`_
"""
url_parameters: Dict[str, Any] = {}
return PaginatedList(
NamedEnterpriseUser,
self._requester,
self.url,
url_parameters,
None,
"users",
firstData=self.raw_data,
firstHeaders=self.raw_headers,
)
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "total_seats_consumed" in attributes: # pragma no branch
self._total_seats_consumed = self._makeIntAttribute(attributes["total_seats_consumed"])
if "total_seats_purchased" in attributes: # pragma no branch
self._total_seats_purchased = self._makeIntAttribute(attributes["total_seats_purchased"])
if "enterprise" in attributes: # pragma no branch
self._enterprise = self._makeStringAttribute(attributes["enterprise"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 5,663
|
Python
|
.py
| 93
| 55.645161
| 183
| 0.548515
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,459
|
Autolink.py
|
PyGithub_PyGithub/github/Autolink.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Nick Campbell <nicholas.j.campbell@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2022 Marco Köpcke <hello@parakoopa.de> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com>#
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class Autolink(NonCompletableGithubObject):
"""
This class represents Repository autolinks.
The reference can be found here
https://docs.github.com/en/rest/repos/autolinks?apiVersion=2022-11-28
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = NotSet
self._key_prefix: Attribute[str] = NotSet
self._url_template: Attribute[str] = NotSet
self._is_alphanumeric: Attribute[bool] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def id(self) -> int:
return self._id.value
@property
def key_prefix(self) -> str:
return self._key_prefix.value
@property
def url_template(self) -> str:
return self._url_template.value
@property
def is_alphanumeric(self) -> bool:
return self._is_alphanumeric.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
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"])
if "is_alphanumeric" in attributes: # pragma no branch
self._is_alphanumeric = self._makeBoolAttribute(attributes["is_alphanumeric"])
| 4,789
|
Python
|
.py
| 75
| 59.8
| 90
| 0.528611
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,460
|
Download.py
|
PyGithub_PyGithub/github/Download.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class Download(CompletableGithubObject):
"""
This class represents Downloads.
The reference can be found here
https://docs.github.com/en/rest/reference/repos
"""
def _initAttributes(self) -> None:
self._accesskeyid: Attribute[str] = NotSet
self._acl: Attribute[str] = NotSet
self._bucket: Attribute[str] = NotSet
self._content_type: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._description: Attribute[str] = NotSet
self._download_count: Attribute[int] = NotSet
self._expirationdate: Attribute[datetime] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._mime_type: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
self._path: Attribute[str] = NotSet
self._policy: Attribute[str] = NotSet
self._prefix: Attribute[str] = NotSet
self._redirect: Attribute[bool] = NotSet
self._s3_url: Attribute[str] = NotSet
self._signature: Attribute[str] = NotSet
self._size: Attribute[int] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def accesskeyid(self) -> str:
self._completeIfNotSet(self._accesskeyid)
return self._accesskeyid.value
@property
def acl(self) -> str:
self._completeIfNotSet(self._acl)
return self._acl.value
@property
def bucket(self) -> str:
self._completeIfNotSet(self._bucket)
return self._bucket.value
@property
def content_type(self) -> str:
self._completeIfNotSet(self._content_type)
return self._content_type.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def description(self) -> str:
self._completeIfNotSet(self._description)
return self._description.value
@property
def download_count(self) -> int:
self._completeIfNotSet(self._download_count)
return self._download_count.value
@property
def expirationdate(self) -> datetime:
self._completeIfNotSet(self._expirationdate)
return self._expirationdate.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def mime_type(self) -> str:
self._completeIfNotSet(self._mime_type)
return self._mime_type.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def path(self) -> str:
self._completeIfNotSet(self._path)
return self._path.value
@property
def policy(self) -> str:
self._completeIfNotSet(self._policy)
return self._policy.value
@property
def prefix(self) -> str:
self._completeIfNotSet(self._prefix)
return self._prefix.value
@property
def redirect(self) -> bool:
self._completeIfNotSet(self._redirect)
return self._redirect.value
@property
def s3_url(self) -> str:
self._completeIfNotSet(self._s3_url)
return self._s3_url.value
@property
def signature(self) -> str:
self._completeIfNotSet(self._signature)
return self._signature.value
@property
def size(self) -> int:
self._completeIfNotSet(self._size)
return self._size.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/downloads/{id} <https://docs.github.com/en/rest/reference/repos>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "accesskeyid" in attributes: # pragma no branch
self._accesskeyid = self._makeStringAttribute(
attributes["accesskeyid"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "acl" in attributes: # pragma no branch
self._acl = self._makeStringAttribute(
attributes["acl"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "bucket" in attributes: # pragma no branch
self._bucket = self._makeStringAttribute(
attributes["bucket"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "content_type" in attributes: # pragma no branch
self._content_type = self._makeStringAttribute(attributes["content_type"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "download_count" in attributes: # pragma no branch
self._download_count = self._makeIntAttribute(attributes["download_count"])
if "expirationdate" in attributes: # pragma no branch
self._expirationdate = self._makeDatetimeAttribute(
attributes["expirationdate"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "mime_type" in attributes: # pragma no branch
self._mime_type = self._makeStringAttribute(
attributes["mime_type"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "path" in attributes: # pragma no branch
self._path = self._makeStringAttribute(
attributes["path"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "policy" in attributes: # pragma no branch
self._policy = self._makeStringAttribute(
attributes["policy"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "prefix" in attributes: # pragma no branch
self._prefix = self._makeStringAttribute(
attributes["prefix"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "redirect" in attributes: # pragma no branch
self._redirect = self._makeBoolAttribute(
attributes["redirect"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "s3_url" in attributes: # pragma no branch
self._s3_url = self._makeStringAttribute(
attributes["s3_url"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "signature" in attributes: # pragma no branch
self._signature = self._makeStringAttribute(
attributes["signature"]
) # pragma no cover (was covered only by create_download, which has been removed)
if "size" in attributes: # pragma no branch
self._size = self._makeIntAttribute(attributes["size"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 11,218
|
Python
|
.py
| 218
| 43.784404
| 112
| 0.584465
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,461
|
AuthorizationApplication.py
|
PyGithub_PyGithub/github/AuthorizationApplication.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class AuthorizationApplication(CompletableGithubObject):
"""
This class represents AuthorizationApplications.
"""
def _initAttributes(self) -> None:
self._name: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 3,912
|
Python
|
.py
| 60
| 61.783333
| 80
| 0.492844
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,462
|
PaginatedList.py
|
PyGithub_PyGithub/github/PaginatedList.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Bill Mill <bill.mill@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 davidbrai <davidbrai@gmail.com> #
# Copyright 2014 Thialfihar <thi@thialfihar.org> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Dan Vanderkam <danvdk@gmail.com> #
# Copyright 2015 Eliot Walker <eliot@lyft.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2018 Gilad Shefer <gshefer@redhat.com> #
# Copyright 2018 Joel Koglin <JoelKoglin@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 netsgnut <284779+netsgnut@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Emir Hodzic <emir.hodzich@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 YugoHino <henom06@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# #
# 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 typing import Any, Callable, Dict, Generic, Iterator, List, Optional, Type, TypeVar, Union
from urllib.parse import parse_qs
from github.GithubObject import GithubObject
from github.Requester import Requester
T = TypeVar("T", bound=GithubObject)
class PaginatedListBase(Generic[T]):
__elements: List[T]
def _couldGrow(self) -> bool:
raise NotImplementedError
def _fetchNextPage(self) -> List[T]:
raise NotImplementedError
def __init__(self, elements: Optional[List[T]] = None) -> None:
self.__elements = [] if elements is None else elements
def __getitem__(self, index: Union[int, slice]) -> Any:
assert isinstance(index, (int, slice))
if isinstance(index, int):
self.__fetchToIndex(index)
return self.__elements[index]
else:
return self._Slice(self, index)
def __iter__(self) -> Iterator[T]:
yield from self.__elements
while self._couldGrow():
newElements = self._grow()
yield from newElements
def _isBiggerThan(self, index: int) -> bool:
return len(self.__elements) > index or self._couldGrow()
def __fetchToIndex(self, index: int) -> None:
while len(self.__elements) <= index and self._couldGrow():
self._grow()
def _grow(self) -> List[T]:
newElements = self._fetchNextPage()
self.__elements += newElements
return newElements
class _Slice:
def __init__(self, theList: "PaginatedListBase[T]", theSlice: slice):
self.__list = theList
self.__start = theSlice.start or 0
self.__stop = theSlice.stop
self.__step = theSlice.step or 1
def __iter__(self) -> Iterator[T]:
index = self.__start
while not self.__finished(index):
if self.__list._isBiggerThan(index):
yield self.__list[index]
index += self.__step
else:
return
def __finished(self, index: int) -> bool:
return self.__stop is not None and index >= self.__stop
class PaginatedList(PaginatedListBase[T]):
"""
This class abstracts the `pagination of the API <https://docs.github.com/en/rest/guides/traversing-with-pagination>`_.
You can simply enumerate through instances of this class::
for repo in user.get_repos():
print(repo.name)
If you want to know the total number of items in the list::
print(user.get_repos().totalCount)
You can also index them or take slices::
second_repo = user.get_repos()[1]
first_repos = user.get_repos()[:10]
If you want to iterate in reversed order, just do::
for repo in user.get_repos().reversed:
print(repo.name)
And if you really need it, you can explicitly access a specific page::
some_repos = user.get_repos().get_page(0)
some_other_repos = user.get_repos().get_page(3)
"""
def __init__(
self,
contentClass: Type[T],
requester: Requester,
firstUrl: str,
firstParams: Any,
headers: Optional[Dict[str, str]] = None,
list_item: str = "items",
total_count_item: str = "total_count",
firstData: Optional[Any] = None,
firstHeaders: Optional[Dict[str, Union[str, int]]] = None,
attributesTransformer: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
):
self.__requester = requester
self.__contentClass = contentClass
self.__firstUrl = firstUrl
self.__firstParams = firstParams or ()
self.__nextUrl = firstUrl
self.__nextParams = firstParams or {}
self.__headers = headers
self.__list_item = list_item
self.__total_count_item = total_count_item
if self.__requester.per_page != 30:
self.__nextParams["per_page"] = self.__requester.per_page
self._reversed = False
self.__totalCount: Optional[int] = None
self._attributesTransformer = attributesTransformer
first_page = []
if firstData is not None and firstHeaders is not None:
first_page = self._getPage(firstData, firstHeaders)
super().__init__(first_page)
def _transformAttributes(self, element: Dict[str, Any]) -> Dict[str, Any]:
if self._attributesTransformer is None:
return element
return self._attributesTransformer(element)
@property
def totalCount(self) -> int:
if not self.__totalCount:
params = {} if self.__nextParams is None else self.__nextParams.copy()
# set per_page = 1 so the totalCount is just the number of pages
params.update({"per_page": 1})
headers, data = self.__requester.requestJsonAndCheck(
"GET", self.__firstUrl, parameters=params, headers=self.__headers
)
if "link" not in headers:
if data and "total_count" in data:
self.__totalCount = data["total_count"]
elif data:
if isinstance(data, dict):
data = data[self.__list_item]
self.__totalCount = len(data)
else:
self.__totalCount = 0
else:
links = self.__parseLinkHeader(headers)
lastUrl = links.get("last")
if lastUrl:
self.__totalCount = int(parse_qs(lastUrl)["page"][0])
else:
self.__totalCount = 0
return self.__totalCount # type: ignore
def _getLastPageUrl(self) -> Optional[str]:
headers, data = self.__requester.requestJsonAndCheck(
"GET", self.__firstUrl, parameters=self.__nextParams, headers=self.__headers
)
links = self.__parseLinkHeader(headers)
return links.get("last")
@property
def reversed(self) -> "PaginatedList[T]":
r = PaginatedList(
self.__contentClass,
self.__requester,
self.__firstUrl,
self.__firstParams,
self.__headers,
self.__list_item,
attributesTransformer=self._attributesTransformer,
)
r.__reverse()
return r
def __reverse(self) -> None:
self._reversed = True
lastUrl = self._getLastPageUrl()
if lastUrl:
self.__nextUrl = lastUrl
def _couldGrow(self) -> bool:
return self.__nextUrl is not None
def _fetchNextPage(self) -> List[T]:
headers, data = self.__requester.requestJsonAndCheck(
"GET", self.__nextUrl, parameters=self.__nextParams, headers=self.__headers
)
data = data if data else []
return self._getPage(data, headers)
def _getPage(self, data: Any, headers: Dict[str, Any]) -> List[T]:
self.__nextUrl = None # type: ignore
if len(data) > 0:
links = self.__parseLinkHeader(headers)
if self._reversed:
if "prev" in links:
self.__nextUrl = links["prev"]
elif "next" in links:
self.__nextUrl = links["next"]
self.__nextParams = None
if self.__list_item in data:
self.__totalCount = data.get(self.__total_count_item)
data = data[self.__list_item]
content = [
self.__contentClass(self.__requester, headers, self._transformAttributes(element), completed=False)
for element in data
if element is not None
]
if self._reversed:
return content[::-1]
return content
def __parseLinkHeader(self, headers: Dict[str, str]) -> Dict[str, str]:
links = {}
if "link" in headers:
linkHeaders = headers["link"].split(", ")
for linkHeader in linkHeaders:
url, rel, *rest = linkHeader.split("; ")
url = url[1:-1]
rel = rel[5:-1]
links[rel] = url
return links
def get_page(self, page: int) -> List[T]:
params = dict(self.__firstParams)
if page != 0:
params["page"] = page + 1
if self.__requester.per_page != 30:
params["per_page"] = self.__requester.per_page
headers, data = self.__requester.requestJsonAndCheck(
"GET", self.__firstUrl, parameters=params, headers=self.__headers
)
if self.__list_item in data:
self.__totalCount = data.get("total_count")
data = data[self.__list_item]
return [
self.__contentClass(self.__requester, headers, self._transformAttributes(element), completed=False)
for element in data
]
@classmethod
def override_attributes(cls, overrides: Dict[str, Any]) -> Callable[[Dict[str, Any]], Dict[str, Any]]:
def attributes_transformer(element: Dict[str, Any]) -> Dict[str, Any]:
# Recursively merge overrides with attributes, overriding attributes with overrides
element = cls.merge_dicts(element, overrides)
return element
return attributes_transformer
@classmethod
def merge_dicts(cls, d1: Dict[str, Any], d2: Dict[str, Any]) -> Dict[str, Any]:
# clone d1
d1 = d1.copy()
for k, v in d2.items():
if isinstance(v, dict):
d1[k] = cls.merge_dicts(d1.get(k, {}), v)
else:
d1[k] = v
return d1
| 13,663
|
Python
|
.py
| 275
| 40.843636
| 122
| 0.543091
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,463
|
UserKey.py
|
PyGithub_PyGithub/github/UserKey.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
import github.GithubObject
from github.GithubObject import Attribute
class UserKey(github.GithubObject.CompletableGithubObject):
"""
This class represents UserKeys.
The reference can be found here
https://docs.github.com/en/rest/reference/users#keys
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = github.GithubObject.NotSet
self._key: Attribute[str] = github.GithubObject.NotSet
self._title: Attribute[str] = github.GithubObject.NotSet
self._url: Attribute[str] = github.GithubObject.NotSet
self._verified: Attribute[bool] = github.GithubObject.NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "title": self._title.value})
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def key(self) -> str:
self._completeIfNotSet(self._key)
return self._key.value
@property
def title(self) -> str:
self._completeIfNotSet(self._title)
return self._title.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def verified(self) -> bool:
self._completeIfNotSet(self._verified)
return self._verified.value
def delete(self) -> None:
"""
:calls: `DELETE /user/keys/{id} <https://docs.github.com/en/rest/reference/users#get-a-public-ssh-key-for-the-authenticated-user>`_
:rtype: None
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "key" in attributes: # pragma no branch
self._key = self._makeStringAttribute(attributes["key"])
if "title" in attributes: # pragma no branch
self._title = self._makeStringAttribute(attributes["title"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "verified" in attributes: # pragma no branch
self._verified = self._makeBoolAttribute(attributes["verified"])
| 5,516
|
Python
|
.py
| 93
| 54.451613
| 139
| 0.53199
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,464
|
SecurityAndAnalysisFeature.py
|
PyGithub_PyGithub/github/SecurityAndAnalysisFeature.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Caleb McCombs <caleb@mccombalot.net> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class SecurityAndAnalysisFeature(NonCompletableGithubObject):
"""
This class represents a Security and Analysis feature status.
"""
def _initAttributes(self) -> None:
self._status: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"status": self._status.value})
@property
def status(self) -> str:
return self._status.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
| 3,709
|
Python
|
.py
| 53
| 67.396226
| 80
| 0.486842
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,465
|
Issue.py
|
PyGithub_PyGithub/github/Issue.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Andrew Bettison <andrewb@zip.com.au> #
# Copyright 2012 Philip Kimmey <philip@rover.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 David Farr <david.farr@sap.com> #
# Copyright 2013 Stuart Glaser <stuglaser@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Raja Reddy Karri <klnrajareddy@gmail.com> #
# Copyright 2016 @tmshn <tmshn@r.recruit.co.jp> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Matt Babineau <babineaum@users.noreply.github.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Nicolas Agustín Torres <nicolastrres@gmail.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Aaron L. Levine <allevin@sandia.gov> #
# Copyright 2018 Shinichi TAMURA <shnch.tmr@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 per1234 <accounts@perglass.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Filipe Laíns <filipe.lains@gmail.com> #
# Copyright 2019 Nick Campbell <nicholas.j.campbell@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Huan-Cheng Chang <changhc84@gmail.com> #
# Copyright 2020 Huw Jones <huwcbjones@outlook.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Nicolas Schweitzer <nicolas.schweitzer@datadoghq.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Malik Shahzad Muzaffar <shahzad.malik.muzaffar@cern.ch> #
# #
# 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 __future__ import annotations
import urllib.parse
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.GithubObject
import github.IssueComment
import github.IssueEvent
import github.IssuePullRequest
import github.Label
import github.Milestone
import github.NamedUser
import github.PullRequest
import github.Reaction
import github.Repository
import github.TimelineEvent
from github import Consts
from github.GithubObject import (
Attribute,
CompletableGithubObject,
NotSet,
Opt,
is_defined,
is_optional,
is_optional_list,
is_undefined,
)
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.IssueComment import IssueComment
from github.IssueEvent import IssueEvent
from github.IssuePullRequest import IssuePullRequest
from github.Label import Label
from github.Milestone import Milestone
from github.NamedUser import NamedUser
from github.PullRequest import PullRequest
from github.Reaction import Reaction
from github.Repository import Repository
from github.TimelineEvent import TimelineEvent
class Issue(CompletableGithubObject):
"""
This class represents Issues.
The reference can be found here
https://docs.github.com/en/rest/reference/issues
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = NotSet
self._active_lock_reason: Attribute[str | None] = NotSet
self._assignee: Attribute[NamedUser | None] = NotSet
self._assignees: Attribute[list[NamedUser]] = NotSet
self._body: Attribute[str] = NotSet
self._closed_at: Attribute[datetime] = NotSet
self._closed_by: Attribute[NamedUser] = NotSet
self._comments: Attribute[int] = NotSet
self._comments_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._events_url: Attribute[str] = NotSet
self._html_url: Attribute[str] = NotSet
self._labels: Attribute[list[Label]] = NotSet
self._labels_url: Attribute[str] = NotSet
self._locked: Attribute[bool] = NotSet
self._milestone: Attribute[Milestone] = NotSet
self._number: Attribute[int] = NotSet
self._pull_request: Attribute[IssuePullRequest] = NotSet
self._repository: Attribute[Repository] = NotSet
self._state: Attribute[str] = NotSet
self._state_reason: Attribute[str | None] = NotSet
self._title: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._user: Attribute[NamedUser] = NotSet
self._reactions: Attribute[dict] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"number": self._number.value, "title": self._title.value})
@property
def assignee(self) -> NamedUser | None:
self._completeIfNotSet(self._assignee)
return self._assignee.value
@property
def assignees(self) -> list[NamedUser]:
self._completeIfNotSet(self._assignees)
return self._assignees.value
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def closed_at(self) -> datetime:
self._completeIfNotSet(self._closed_at)
return self._closed_at.value
@property
def closed_by(self) -> NamedUser | None:
self._completeIfNotSet(self._closed_by)
return self._closed_by.value
@property
def comments(self) -> int:
self._completeIfNotSet(self._comments)
return self._comments.value
@property
def comments_url(self) -> str:
self._completeIfNotSet(self._comments_url)
return self._comments_url.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def events_url(self) -> str:
self._completeIfNotSet(self._events_url)
return self._events_url.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def labels(self) -> list[Label]:
self._completeIfNotSet(self._labels)
return self._labels.value
@property
def labels_url(self) -> str:
self._completeIfNotSet(self._labels_url)
return self._labels_url.value
@property
def milestone(self) -> Milestone:
self._completeIfNotSet(self._milestone)
return self._milestone.value
@property
def number(self) -> int:
self._completeIfNotSet(self._number)
return self._number.value
@property
def pull_request(self) -> IssuePullRequest | None:
self._completeIfNotSet(self._pull_request)
return self._pull_request.value
@property
def repository(self) -> Repository:
self._completeIfNotSet(self._repository)
if is_undefined(self._repository):
# The repository was not set automatically, so it must be looked up by url.
repo_url = "/".join(self.url.split("/")[:-2])
self._repository = github.GithubObject._ValuedAttribute(
github.Repository.Repository(self._requester, self._headers, {"url": repo_url}, completed=False)
)
return self._repository.value
@property
def state(self) -> str:
self._completeIfNotSet(self._state)
return self._state.value
@property
def state_reason(self) -> str | None:
self._completeIfNotSet(self._state_reason)
return self._state_reason.value
@property
def title(self) -> str:
self._completeIfNotSet(self._title)
return self._title.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def user(self) -> NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
@property
def locked(self) -> bool:
self._completeIfNotSet(self._locked)
return self._locked.value
@property
def active_lock_reason(self) -> str | None:
self._completeIfNotSet(self._active_lock_reason)
return self._active_lock_reason.value
@property
def reactions(self) -> dict:
self._completeIfNotSet(self._reactions)
return self._reactions.value
def as_pull_request(self) -> PullRequest:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number} <https://docs.github.com/en/rest/reference/pulls>`_
"""
headers, data = self._requester.requestJsonAndCheck("GET", "/pulls/".join(self.url.rsplit("/issues/", 1)))
return github.PullRequest.PullRequest(self._requester, headers, data, completed=True)
def add_to_assignees(self, *assignees: NamedUser | str) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/assignees <https://docs.github.com/en/rest/reference/issues#assignees>`_
"""
assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees
post_parameters = {
"assignees": [
assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee
for assignee in assignees
]
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/assignees", input=post_parameters)
self._useAttributes(data)
def add_to_labels(self, *labels: Label | str) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels
post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels]
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/labels", input=post_parameters)
def create_comment(self, body: str) -> IssueComment:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/comments <https://docs.github.com/en/rest/reference/issues#comments>`_
"""
assert isinstance(body, str), body
post_parameters = {
"body": body,
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/comments", input=post_parameters)
return github.IssueComment.IssueComment(self._requester, headers, data, completed=True)
def delete_labels(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/labels")
def edit(
self,
title: Opt[str] = NotSet,
body: Opt[str] = NotSet,
assignee: Opt[str | NamedUser | None] = NotSet,
state: Opt[str] = NotSet,
milestone: Opt[Milestone | None] = NotSet,
labels: Opt[list[str]] = NotSet,
assignees: Opt[list[NamedUser | str]] = NotSet,
state_reason: Opt[str] = NotSet,
) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/issues/{number} <https://docs.github.com/en/rest/reference/issues>`_
:param assignee: deprecated, use `assignees` instead. `assignee=None` means to remove current assignee.
:param milestone: `milestone=None` means to remove current milestone.
"""
assert is_optional(title, str), title
assert is_optional(body, str), body
assert assignee is None or is_optional(assignee, (github.NamedUser.NamedUser, str)), assignee
assert is_optional_list(assignees, (github.NamedUser.NamedUser, str)), assignees
assert is_optional(state, str), state
assert milestone is None or is_optional(milestone, github.Milestone.Milestone), milestone
assert is_optional_list(labels, str), labels
post_parameters = NotSet.remove_unset_items(
{
"title": title,
"body": body,
"state": state,
"state_reason": state_reason,
"labels": labels,
"assignee": assignee._identity
if isinstance(assignee, github.NamedUser.NamedUser)
else (assignee or ""),
"milestone": milestone._identity
if isinstance(milestone, github.Milestone.Milestone)
else (milestone or ""),
}
)
if is_defined(assignees):
post_parameters["assignees"] = [
element._identity if isinstance(element, github.NamedUser.NamedUser) else element
for element in assignees
]
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def lock(self, lock_reason: str) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/issues/{issue_number}/lock <https://docs.github.com/en/rest/reference/issues>`_
"""
assert isinstance(lock_reason, str), lock_reason
put_parameters = {"lock_reason": lock_reason}
headers, data = self._requester.requestJsonAndCheck(
"PUT",
f"{self.url}/lock",
input=put_parameters,
headers={"Accept": Consts.mediaTypeLockReasonPreview},
)
def unlock(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock <https://docs.github.com/en/rest/reference/issues>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/lock")
def get_comment(self, id: int) -> IssueComment:
"""
:calls: `GET /repos/{owner}/{repo}/issues/comments/{id} <https://docs.github.com/en/rest/reference/issues#comments>`_
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self._parentUrl(self.url)}/comments/{id}")
return github.IssueComment.IssueComment(self._requester, headers, data, completed=True)
def get_comments(self, since: Opt[datetime] = NotSet) -> PaginatedList[IssueComment]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number}/comments <https://docs.github.com/en/rest/reference/issues#comments>`_
"""
url_parameters = {}
if is_defined(since):
assert isinstance(since, datetime), since
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(
github.IssueComment.IssueComment,
self._requester,
f"{self.url}/comments",
url_parameters,
)
def get_events(self) -> PaginatedList[IssueEvent]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{issue_number}/events <https://docs.github.com/en/rest/reference/issues#events>`_
"""
return PaginatedList(
github.IssueEvent.IssueEvent,
self._requester,
f"{self.url}/events",
None,
headers={"Accept": Consts.mediaTypeLockReasonPreview},
)
def get_labels(self) -> PaginatedList[Label]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
return PaginatedList(github.Label.Label, self._requester, f"{self.url}/labels", None)
def remove_from_assignees(self, *assignees: NamedUser | str) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{number}/assignees <https://docs.github.com/en/rest/reference/issues#assignees>`_
"""
assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees
post_parameters = {
"assignees": [
assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee
for assignee in assignees
]
}
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/assignees", input=post_parameters)
self._useAttributes(data)
def remove_from_labels(self, label: Label | str) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name} <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert isinstance(label, (github.Label.Label, str)), label
if isinstance(label, github.Label.Label):
label = label._identity
else:
label = urllib.parse.quote(label)
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.url}/labels/{label}")
def set_labels(self, *labels: Label | str) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels
post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels]
headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/labels", input=post_parameters)
def get_reactions(self) -> PaginatedList[Reaction]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number}/reactions <https://docs.github.com/en/rest/reference/reactions#list-reactions-for-an-issue>`_
"""
return PaginatedList(
github.Reaction.Reaction,
self._requester,
f"{self.url}/reactions",
None,
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
def create_reaction(self, reaction_type: str) -> Reaction:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/reactions <https://docs.github.com/en/rest/reference/reactions>`_
"""
assert isinstance(reaction_type, str), reaction_type
post_parameters = {
"content": reaction_type,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/reactions",
input=post_parameters,
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)
def delete_reaction(self, reaction_id: int) -> bool:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id} <https://docs.github.com/en/rest/reference/reactions#delete-an-issue-reaction>`_
"""
assert isinstance(reaction_id, int), reaction_id
status, _, _ = self._requester.requestJson(
"DELETE",
f"{self.url}/reactions/{reaction_id}",
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
return status == 204
def get_timeline(self) -> PaginatedList[TimelineEvent]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number}/timeline <https://docs.github.com/en/rest/reference/issues#list-timeline-events-for-an-issue>`_
"""
return PaginatedList(
github.TimelineEvent.TimelineEvent,
self._requester,
f"{self.url}/timeline",
None,
headers={"Accept": Consts.issueTimelineEventsPreview},
)
@property
def _identity(self) -> int:
return self.number
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "active_lock_reason" in attributes: # pragma no branch
self._active_lock_reason = self._makeStringAttribute(attributes["active_lock_reason"])
if "assignee" in attributes: # pragma no branch
self._assignee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["assignee"])
if "assignees" in attributes: # pragma no branch
self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, attributes["assignees"])
elif "assignee" in attributes:
if attributes["assignee"] is not None:
self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, [attributes["assignee"]])
else:
self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, [])
if "body" in attributes: # pragma no branch
self._body = self._makeStringAttribute(attributes["body"])
if "closed_at" in attributes: # pragma no branch
self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"])
if "closed_by" in attributes: # pragma no branch
self._closed_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["closed_by"])
if "comments" in attributes: # pragma no branch
self._comments = self._makeIntAttribute(attributes["comments"])
if "comments_url" in attributes: # pragma no branch
self._comments_url = self._makeStringAttribute(attributes["comments_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "events_url" in attributes: # pragma no branch
self._events_url = self._makeStringAttribute(attributes["events_url"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "labels" in attributes: # pragma no branch
self._labels = self._makeListOfClassesAttribute(github.Label.Label, attributes["labels"])
if "labels_url" in attributes: # pragma no branch
self._labels_url = self._makeStringAttribute(attributes["labels_url"])
if "locked" in attributes: # pragma no branch
self._locked = self._makeBoolAttribute(attributes["locked"])
if "milestone" in attributes: # pragma no branch
self._milestone = self._makeClassAttribute(github.Milestone.Milestone, attributes["milestone"])
if "number" in attributes: # pragma no branch
self._number = self._makeIntAttribute(attributes["number"])
if "pull_request" in attributes: # pragma no branch
self._pull_request = self._makeClassAttribute(
github.IssuePullRequest.IssuePullRequest, attributes["pull_request"]
)
if "repository" in attributes: # pragma no branch
self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "state_reason" in attributes: # pragma no branch
self._state_reason = self._makeStringAttribute(attributes["state_reason"])
if "title" in attributes: # pragma no branch
self._title = self._makeStringAttribute(attributes["title"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
if "reactions" in attributes:
self._reactions = self._makeDictAttribute(attributes["reactions"])
| 26,781
|
Python
|
.py
| 522
| 43.249042
| 172
| 0.616621
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,466
|
Project.py
|
PyGithub_PyGithub/github/Project.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Chris McBride <thehighlander@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Benoit Latinier <benoit@latinier.fr> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 Yossarian King <yggy@blackbirdinteractive.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Anuj Bansal <bansalanuj1996@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Lars Kellogg-Stedman <lars@oddbit.com> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import Any
import github.GithubObject
import github.NamedUser
import github.ProjectColumn
from github import Consts
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt
from github.PaginatedList import PaginatedList
class Project(CompletableGithubObject):
"""
This class represents Projects.
The reference can be found here
https://docs.github.com/en/rest/reference/projects
"""
def _initAttributes(self) -> None:
self._body: Attribute[str] = NotSet
self._columns_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._creator: Attribute[github.NamedUser.NamedUser] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._name: Attribute[str] = NotSet
self._node_id: Attribute[str] = NotSet
self._number: Attribute[int] = NotSet
self._owner_url: Attribute[str] = NotSet
self._state: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def columns_url(self) -> str:
self._completeIfNotSet(self._columns_url)
return self._columns_url.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def creator(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._creator)
return self._creator.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
@property
def number(self) -> int:
self._completeIfNotSet(self._number)
return self._number.value
@property
def owner_url(self) -> str:
self._completeIfNotSet(self._owner_url)
return self._owner_url.value
@property
def state(self) -> str:
self._completeIfNotSet(self._state)
return self._state.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def delete(self) -> None:
"""
:calls: `DELETE /projects/{project_id} <https://docs.github.com/en/rest/reference/projects#delete-a-project>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"DELETE", self.url, headers={"Accept": Consts.mediaTypeProjectsPreview}
)
def edit(
self,
name: Opt[str] = NotSet,
body: Opt[str] = NotSet,
state: Opt[str] = NotSet,
organization_permission: Opt[str] = NotSet,
private: Opt[bool] = NotSet,
) -> None:
"""
:calls: `PATCH /projects/{project_id} <https://docs.github.com/en/rest/reference/projects#update-a-project>`_
"""
assert name is NotSet or isinstance(name, str), name
assert body is NotSet or isinstance(body, str), body
assert state is NotSet or isinstance(state, str), state
assert organization_permission is NotSet or isinstance(organization_permission, str), organization_permission
assert private is NotSet or isinstance(private, bool), private
patch_parameters = NotSet.remove_unset_items(
{
"name": name,
"body": body,
"state": state,
"organization_permission": organization_permission,
"private": private,
}
)
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=patch_parameters,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
self._useAttributes(data)
def get_columns(self) -> PaginatedList[github.ProjectColumn.ProjectColumn]:
"""
:calls: `GET /projects/{project_id}/columns <https://docs.github.com/en/rest/reference/projects#list-project-columns>`_
"""
return PaginatedList(
github.ProjectColumn.ProjectColumn,
self._requester,
self.columns_url,
None,
{"Accept": Consts.mediaTypeProjectsPreview},
)
def create_column(self, name: str) -> github.ProjectColumn.ProjectColumn:
"""
calls: `POST /projects/{project_id}/columns <https://docs.github.com/en/rest/reference/projects#create-a-project-column>`_
"""
assert isinstance(name, str), name
post_parameters = {"name": name}
import_header = {"Accept": Consts.mediaTypeProjectsPreview}
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.url}/columns", headers=import_header, input=post_parameters
)
return github.ProjectColumn.ProjectColumn(self._requester, headers, data, completed=True)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "body" in attributes: # pragma no branch
self._body = self._makeStringAttribute(attributes["body"])
if "columns_url" in attributes: # pragma no branch
self._columns_url = self._makeStringAttribute(attributes["columns_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "creator" in attributes: # pragma no branch
self._creator = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["creator"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "number" in attributes: # pragma no branch
self._number = self._makeIntAttribute(attributes["number"])
if "owner_url" in attributes: # pragma no branch
self._owner_url = self._makeStringAttribute(attributes["owner_url"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 11,104
|
Python
|
.py
| 216
| 44.365741
| 130
| 0.583571
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,467
|
WorkflowStep.py
|
PyGithub_PyGithub/github/WorkflowStep.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Victor Zeng <zacker150@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jeppe Fihl-Pearson <tenzer@tenzer.dk> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class WorkflowStep(CompletableGithubObject):
"""
This class represents steps in a Workflow Job.
The reference can be found here
https://docs.github.com/en/rest/reference/actions#workflow-jobs
"""
def _initAttributes(self) -> None:
self._completed_at: Attribute[datetime] = NotSet
self._conclusion: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
self._number: Attribute[int] = NotSet
self._started_at: Attribute[datetime] = NotSet
self._status: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"number": self._number.value, "name": self._name.value})
@property
def completed_at(self) -> datetime:
self._completeIfNotSet(self._completed_at)
return self._completed_at.value
@property
def conclusion(self) -> str:
self._completeIfNotSet(self._conclusion)
return self._conclusion.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def number(self) -> int:
self._completeIfNotSet(self._number)
return self._number.value
@property
def started_at(self) -> datetime:
self._completeIfNotSet(self._started_at)
return self._started_at.value
@property
def status(self) -> str:
self._completeIfNotSet(self._status)
return self._status.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "completed_at" in attributes: # pragma no branch
self._completed_at = self._makeDatetimeAttribute(attributes["completed_at"])
if "conclusion" in attributes: # pragma no branch
self._conclusion = self._makeStringAttribute(attributes["conclusion"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "number" in attributes: # pragma no branch
self._number = self._makeIntAttribute(attributes["number"])
if "started_at" in attributes: # pragma no branch
self._started_at = self._makeDatetimeAttribute(attributes["started_at"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
| 5,643
|
Python
|
.py
| 94
| 55.12766
| 89
| 0.546621
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,468
|
Branch.py
|
PyGithub_PyGithub/github/Branch.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Kyle Hornberg <khornberg@users.noreply.github.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Juan Manuel "Kang" Pérez <kangcoding@gmail.com> #
# Copyright 2023 Kevin Grandjean <Muscaw@users.noreply.github.com> #
# Copyright 2023 Paul Luna <paulluna0215@gmail.com> #
# Copyright 2023 Thomas Devoogdt <thomas@devoogdt.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 terenho <33275803+terenho@users.noreply.github.com> #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.BranchProtection
import github.Commit
import github.RequiredPullRequestReviews
import github.RequiredStatusChecks
from github import Consts
from github.GithubObject import (
Attribute,
NonCompletableGithubObject,
NotSet,
Opt,
is_defined,
is_optional,
is_optional_list,
is_undefined,
)
if TYPE_CHECKING:
from github.BranchProtection import BranchProtection
from github.Commit import Commit
from github.NamedUser import NamedUser
from github.PaginatedList import PaginatedList
from github.RequiredPullRequestReviews import RequiredPullRequestReviews
from github.RequiredStatusChecks import RequiredStatusChecks
from github.Team import Team
class Branch(NonCompletableGithubObject):
"""
This class represents Branches.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#branches
"""
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def commit(self) -> Commit:
return self._commit.value
@property
def name(self) -> str:
return self._name.value
@property
def protected(self) -> bool:
return self._protected.value
@property
def protection_url(self) -> str:
return self._protection_url.value
def _initAttributes(self) -> None:
self._commit: Attribute[Commit] = github.GithubObject.NotSet
self._name: Attribute[str] = github.GithubObject.NotSet
self._protection_url: Attribute[str] = github.GithubObject.NotSet
self._protected: Attribute[bool] = github.GithubObject.NotSet
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "commit" in attributes: # pragma no branch
self._commit = self._makeClassAttribute(github.Commit.Commit, attributes["commit"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "protection_url" in attributes: # pragma no branch
self._protection_url = self._makeStringAttribute(attributes["protection_url"])
if "protected" in attributes: # pragma no branch
self._protected = self._makeBoolAttribute(attributes["protected"])
def get_protection(self) -> BranchProtection:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.protection_url,
headers={"Accept": Consts.mediaTypeRequireMultipleApprovingReviews},
)
return github.BranchProtection.BranchProtection(self._requester, headers, data, completed=True)
def edit_protection(
self,
strict: Opt[bool] = NotSet,
contexts: Opt[list[str]] = NotSet,
enforce_admins: Opt[bool] = NotSet,
dismissal_users: Opt[list[str]] = NotSet,
dismissal_teams: Opt[list[str]] = NotSet,
dismissal_apps: Opt[list[str]] = NotSet,
dismiss_stale_reviews: Opt[bool] = NotSet,
require_code_owner_reviews: Opt[bool] = NotSet,
required_approving_review_count: Opt[int] = NotSet,
user_push_restrictions: Opt[list[str]] = NotSet,
team_push_restrictions: Opt[list[str]] = NotSet,
app_push_restrictions: Opt[list[str]] = NotSet,
required_linear_history: Opt[bool] = NotSet,
allow_force_pushes: Opt[bool] = NotSet,
required_conversation_resolution: Opt[bool] = NotSet,
lock_branch: Opt[bool] = NotSet,
allow_fork_syncing: Opt[bool] = NotSet,
users_bypass_pull_request_allowances: Opt[list[str]] = NotSet,
teams_bypass_pull_request_allowances: Opt[list[str]] = NotSet,
apps_bypass_pull_request_allowances: Opt[list[str]] = NotSet,
block_creations: Opt[bool] = NotSet,
require_last_push_approval: Opt[bool] = NotSet,
allow_deletions: Opt[bool] = NotSet,
) -> BranchProtection:
"""
:calls: `PUT /repos/{owner}/{repo}/branches/{branch}/protection <https://docs.github.com/en/rest/reference/repos#get-branch-protection>`_
NOTE: The GitHub API groups strict and contexts together, both must
be submitted. Take care to pass both as arguments even if only one is
changing. Use edit_required_status_checks() to avoid this.
"""
assert is_optional(strict, bool), strict
assert is_optional_list(contexts, str), contexts
assert is_optional(enforce_admins, bool), enforce_admins
assert is_optional_list(dismissal_users, str), dismissal_users
assert is_optional_list(dismissal_teams, str), dismissal_teams
assert is_optional_list(dismissal_apps, str), dismissal_apps
assert is_optional(dismiss_stale_reviews, bool), dismiss_stale_reviews
assert is_optional(require_code_owner_reviews, bool), require_code_owner_reviews
assert is_optional(required_approving_review_count, int), required_approving_review_count
assert is_optional(required_linear_history, bool), required_linear_history
assert is_optional(allow_force_pushes, bool), allow_force_pushes
assert is_optional(required_conversation_resolution, bool), required_conversation_resolution
assert is_optional(lock_branch, bool), lock_branch
assert is_optional(allow_fork_syncing, bool), allow_fork_syncing
assert is_optional_list(users_bypass_pull_request_allowances, str), users_bypass_pull_request_allowances
assert is_optional_list(teams_bypass_pull_request_allowances, str), teams_bypass_pull_request_allowances
assert is_optional_list(apps_bypass_pull_request_allowances, str), apps_bypass_pull_request_allowances
assert is_optional(require_last_push_approval, bool), require_last_push_approval
assert is_optional(allow_deletions, bool), allow_deletions
post_parameters: dict[str, Any] = {}
if is_defined(strict) or is_defined(contexts):
if is_undefined(strict):
strict = False
if is_undefined(contexts):
contexts = []
post_parameters["required_status_checks"] = {
"strict": strict,
"contexts": contexts,
}
else:
post_parameters["required_status_checks"] = None
if is_defined(enforce_admins):
post_parameters["enforce_admins"] = enforce_admins
else:
post_parameters["enforce_admins"] = None
if (
is_defined(dismissal_users)
or is_defined(dismissal_teams)
or is_defined(dismissal_apps)
or is_defined(dismiss_stale_reviews)
or is_defined(require_code_owner_reviews)
or is_defined(required_approving_review_count)
or is_defined(users_bypass_pull_request_allowances)
or is_defined(teams_bypass_pull_request_allowances)
or is_defined(apps_bypass_pull_request_allowances)
or is_defined(require_last_push_approval)
):
post_parameters["required_pull_request_reviews"] = {}
if is_defined(dismiss_stale_reviews):
post_parameters["required_pull_request_reviews"]["dismiss_stale_reviews"] = dismiss_stale_reviews
if is_defined(require_code_owner_reviews):
post_parameters["required_pull_request_reviews"][
"require_code_owner_reviews"
] = require_code_owner_reviews
if is_defined(required_approving_review_count):
post_parameters["required_pull_request_reviews"][
"required_approving_review_count"
] = required_approving_review_count
if is_defined(require_last_push_approval):
post_parameters["required_pull_request_reviews"][
"require_last_push_approval"
] = require_last_push_approval
dismissal_restrictions = {}
if is_defined(dismissal_users):
dismissal_restrictions["users"] = dismissal_users
if is_defined(dismissal_teams):
dismissal_restrictions["teams"] = dismissal_teams
if is_defined(dismissal_apps):
dismissal_restrictions["apps"] = dismissal_apps
if dismissal_restrictions:
post_parameters["required_pull_request_reviews"]["dismissal_restrictions"] = dismissal_restrictions
bypass_pull_request_allowances = {}
if is_defined(users_bypass_pull_request_allowances):
bypass_pull_request_allowances["users"] = users_bypass_pull_request_allowances
if is_defined(teams_bypass_pull_request_allowances):
bypass_pull_request_allowances["teams"] = teams_bypass_pull_request_allowances
if is_defined(apps_bypass_pull_request_allowances):
bypass_pull_request_allowances["apps"] = apps_bypass_pull_request_allowances
if bypass_pull_request_allowances:
post_parameters["required_pull_request_reviews"][
"bypass_pull_request_allowances"
] = bypass_pull_request_allowances
else:
post_parameters["required_pull_request_reviews"] = None
if (
is_defined(user_push_restrictions)
or is_defined(team_push_restrictions)
or is_defined(app_push_restrictions)
):
if is_undefined(user_push_restrictions):
user_push_restrictions = []
if is_undefined(team_push_restrictions):
team_push_restrictions = []
if is_undefined(app_push_restrictions):
app_push_restrictions = []
post_parameters["restrictions"] = {
"users": user_push_restrictions,
"teams": team_push_restrictions,
"apps": app_push_restrictions,
}
else:
post_parameters["restrictions"] = None
if is_defined(required_linear_history):
post_parameters["required_linear_history"] = required_linear_history
else:
post_parameters["required_linear_history"] = None
if is_defined(allow_force_pushes):
post_parameters["allow_force_pushes"] = allow_force_pushes
else:
post_parameters["allow_force_pushes"] = None
if is_defined(required_conversation_resolution):
post_parameters["required_conversation_resolution"] = required_conversation_resolution
else:
post_parameters["required_conversation_resolution"] = None
if is_defined(lock_branch):
post_parameters["lock_branch"] = lock_branch
else:
post_parameters["lock_branch"] = None
if is_defined(allow_fork_syncing):
post_parameters["allow_fork_syncing"] = allow_fork_syncing
else:
post_parameters["allow_fork_syncing"] = None
if is_defined(block_creations):
post_parameters["block_creations"] = block_creations
else:
post_parameters["block_creations"] = None
if is_defined(allow_deletions):
post_parameters["allow_deletions"] = allow_deletions
else:
post_parameters["allow_deletions"] = None
headers, data = self._requester.requestJsonAndCheck(
"PUT",
self.protection_url,
headers={"Accept": Consts.mediaTypeRequireMultipleApprovingReviews},
input=post_parameters,
)
return github.BranchProtection.BranchProtection(self._requester, headers, data, completed=True)
def remove_protection(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
self.protection_url,
)
def get_required_status_checks(self) -> RequiredStatusChecks:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks <https://docs.github.com/en/rest/reference/repos#branches>`_
:rtype: :class:`github.RequiredStatusChecks.RequiredStatusChecks`
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.protection_url}/required_status_checks")
return github.RequiredStatusChecks.RequiredStatusChecks(self._requester, headers, data, completed=True)
def edit_required_status_checks(
self,
strict: Opt[bool] = NotSet,
contexts: Opt[list[str]] = NotSet,
) -> RequiredStatusChecks:
"""
:calls: `PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
assert is_optional(strict, bool), strict
assert is_optional_list(contexts, str), contexts
post_parameters: dict[str, Any] = NotSet.remove_unset_items({"strict": strict, "contexts": contexts})
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
f"{self.protection_url}/required_status_checks",
input=post_parameters,
)
return github.RequiredStatusChecks.RequiredStatusChecks(self._requester, headers, data, completed=True)
def remove_required_status_checks(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
f"{self.protection_url}/required_status_checks",
)
def get_required_pull_request_reviews(self) -> RequiredPullRequestReviews:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.protection_url}/required_pull_request_reviews",
headers={"Accept": Consts.mediaTypeRequireMultipleApprovingReviews},
)
return github.RequiredPullRequestReviews.RequiredPullRequestReviews(
self._requester, headers, data, completed=True
)
def edit_required_pull_request_reviews(
self,
dismissal_users: Opt[list[str]] = NotSet,
dismissal_teams: Opt[list[str]] = NotSet,
dismissal_apps: Opt[list[str]] = NotSet,
dismiss_stale_reviews: Opt[bool] = NotSet,
require_code_owner_reviews: Opt[bool] = NotSet,
required_approving_review_count: Opt[int] = NotSet,
require_last_push_approval: Opt[bool] = NotSet,
) -> RequiredStatusChecks:
"""
:calls: `PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
assert is_optional_list(dismissal_users, str), dismissal_users
assert is_optional_list(dismissal_teams, str), dismissal_teams
assert is_optional(dismiss_stale_reviews, bool), dismiss_stale_reviews
assert is_optional(require_code_owner_reviews, bool), require_code_owner_reviews
assert is_optional(required_approving_review_count, int), required_approving_review_count
assert is_optional(require_last_push_approval, bool), require_last_push_approval
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"dismiss_stale_reviews": dismiss_stale_reviews,
"require_code_owner_reviews": require_code_owner_reviews,
"required_approving_review_count": required_approving_review_count,
"require_last_push_approval": require_last_push_approval,
}
)
dismissal_restrictions: dict[str, Any] = NotSet.remove_unset_items(
{"users": dismissal_users, "teams": dismissal_teams, "apps": dismissal_apps}
)
if dismissal_restrictions:
post_parameters["dismissal_restrictions"] = dismissal_restrictions
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
f"{self.protection_url}/required_pull_request_reviews",
headers={"Accept": Consts.mediaTypeRequireMultipleApprovingReviews},
input=post_parameters,
)
return github.RequiredStatusChecks.RequiredStatusChecks(self._requester, headers, data, completed=True)
def remove_required_pull_request_reviews(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
f"{self.protection_url}/required_pull_request_reviews",
)
def get_admin_enforcement(self) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.protection_url}/enforce_admins")
return data["enabled"]
def set_admin_enforcement(self) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.protection_url}/enforce_admins")
def remove_admin_enforcement(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.protection_url}/enforce_admins")
def get_user_push_restrictions(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
return github.PaginatedList.PaginatedList(
github.NamedUser.NamedUser,
self._requester,
f"{self.protection_url}/restrictions/users",
None,
)
def get_team_push_restrictions(self) -> PaginatedList[Team]:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
return github.PaginatedList.PaginatedList(
github.Team.Team,
self._requester,
f"{self.protection_url}/restrictions/teams",
None,
)
def add_user_push_restrictions(self, *users: str) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users <https://docs.github.com/en/rest/reference/repos#branches>`_
:users: list of strings (user names)
"""
assert all(isinstance(element, str) for element in users), users
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.protection_url}/restrictions/users", input=users
)
def replace_user_push_restrictions(self, *users: str) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users <https://docs.github.com/en/rest/reference/repos#branches>`_
:users: list of strings (user names)
"""
assert all(isinstance(element, str) for element in users), users
headers, data = self._requester.requestJsonAndCheck(
"PUT", f"{self.protection_url}/restrictions/users", input=users
)
def remove_user_push_restrictions(self, *users: str) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users <https://docs.github.com/en/rest/reference/repos#branches>`_
:users: list of strings (user names)
"""
assert all(isinstance(element, str) for element in users), users
headers, data = self._requester.requestJsonAndCheck(
"DELETE", f"{self.protection_url}/restrictions/users", input=users
)
def add_team_push_restrictions(self, *teams: str) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams <https://docs.github.com/en/rest/reference/repos#branches>`_
:teams: list of strings (team slugs)
"""
assert all(isinstance(element, str) for element in teams), teams
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.protection_url}/restrictions/teams", input=teams
)
def replace_team_push_restrictions(self, *teams: str) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams <https://docs.github.com/en/rest/reference/repos#branches>`_
:teams: list of strings (team slugs)
"""
assert all(isinstance(element, str) for element in teams), teams
headers, data = self._requester.requestJsonAndCheck(
"PUT", f"{self.protection_url}/restrictions/teams", input=teams
)
def remove_team_push_restrictions(self, *teams: str) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams <https://docs.github.com/en/rest/reference/repos#branches>`_
:teams: list of strings (team slugs)
"""
assert all(isinstance(element, str) for element in teams), teams
headers, data = self._requester.requestJsonAndCheck(
"DELETE", f"{self.protection_url}/restrictions/teams", input=teams
)
def remove_push_restrictions(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.protection_url}/restrictions")
def get_required_signatures(self) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.protection_url}/required_signatures",
headers={"Accept": Consts.signaturesProtectedBranchesPreview},
)
return data["enabled"]
def add_required_signatures(self) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.protection_url}/required_signatures",
headers={"Accept": Consts.signaturesProtectedBranchesPreview},
)
def remove_required_signatures(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck(
"DELETE",
f"{self.protection_url}/required_signatures",
headers={"Accept": Consts.signaturesProtectedBranchesPreview},
)
def get_allow_deletions(self) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/branches/{branch}/protection/allow_deletions <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("GET", f"{self.protection_url}/allow_deletions")
return data["enabled"]
def set_allow_deletions(self) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/branches/{branch}/protection/allow_deletions <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.protection_url}/allow_deletions")
def remove_allow_deletions(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/branches/{branch}/protection/allow_deletions <https://docs.github.com/en/rest/reference/repos#branches>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.protection_url}/allow_deletions")
| 29,018
|
Python
|
.py
| 525
| 46.133333
| 165
| 0.628852
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,469
|
GithubObject.py
|
PyGithub_PyGithub/github/GithubObject.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Andrew Scheller <github@loowis.durge.org> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jakub Wilk <jwilk@jwilk.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 Sam Corbett <sam.corbett@cloudsoftcorp.com> #
# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> #
# Copyright 2018 h.shi <10385628+AnYeMoWang@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Christoph Reiter <reiter.christoph@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Nicolas Schweitzer <nicolas.schweitzer@datadoghq.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 email.utils
import typing
from datetime import datetime, timezone
from decimal import Decimal
from operator import itemgetter
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Type, Union
from typing_extensions import Protocol, TypeGuard
from . import Consts
from .GithubException import BadAttributeException, IncompletableObject
if TYPE_CHECKING:
from .Requester import Requester
T = typing.TypeVar("T")
K = typing.TypeVar("K")
T_co = typing.TypeVar("T_co", covariant=True)
T_gh = typing.TypeVar("T_gh", bound="GithubObject")
class Attribute(Protocol[T_co]):
@property
def value(self) -> T_co:
raise NotImplementedError
def _datetime_from_http_date(value: str) -> datetime:
"""
Convert an HTTP date to a datetime object.
Raises ValueError for invalid dates.
"""
dt = email.utils.parsedate_to_datetime(value)
if dt.tzinfo is None:
# RFC7231 states that UTC is assumed if no timezone info is present
return dt.replace(tzinfo=timezone.utc)
return dt
def _datetime_from_github_isoformat(value: str) -> datetime:
"""
Convert an GitHub API timestamps to a datetime object.
Raises ValueError for invalid timestamps.
"""
# Github always returns YYYY-MM-DDTHH:MM:SSZ, so we can use the stdlib parser
# with some minor adjustments for Python < 3.11 which doesn't support "Z"
# https://docs.github.com/en/rest/overview/resources-in-the-rest-api#schema
if value.endswith("Z"):
value = value[:-1] + "+00:00"
return datetime.fromisoformat(value)
class _NotSetType:
def __repr__(self) -> str:
return "NotSet"
@property
def value(self) -> Any:
return None
@staticmethod
def remove_unset_items(data: Dict[str, Any]) -> Dict[str, Any]:
return {key: value for key, value in data.items() if not isinstance(value, _NotSetType)}
NotSet = _NotSetType()
Opt = Union[T, _NotSetType]
def is_defined(v: Union[T, _NotSetType]) -> TypeGuard[T]:
return not isinstance(v, _NotSetType)
def is_undefined(v: Union[T, _NotSetType]) -> TypeGuard[_NotSetType]:
return isinstance(v, _NotSetType)
def is_optional(v: Any, type: Union[Type, Tuple[Type, ...]]) -> bool:
return isinstance(v, _NotSetType) or isinstance(v, type)
def is_optional_list(v: Any, type: Union[Type, Tuple[Type, ...]]) -> bool:
return isinstance(v, _NotSetType) or isinstance(v, list) and all(isinstance(element, type) for element in v)
class _ValuedAttribute(Attribute[T]):
def __init__(self, value: T):
self._value = value
@property
def value(self) -> T:
return self._value
class _BadAttribute(Attribute):
def __init__(self, value: Any, expectedType: Any, exception: Optional[Exception] = None):
self.__value = value
self.__expectedType = expectedType
self.__exception = exception
@property
def value(self) -> Any:
raise BadAttributeException(self.__value, self.__expectedType, self.__exception)
# v3: add * to edit function of all GithubObject implementations,
# this allows to rename attributes and maintain the order of attributes
class GithubObject:
"""
Base class for all classes representing objects returned by the API.
"""
"""
A global debug flag to enable header validation by requester for all objects
"""
CHECK_AFTER_INIT_FLAG = False
_url: Attribute[str]
@classmethod
def setCheckAfterInitFlag(cls, flag: bool) -> None:
cls.CHECK_AFTER_INIT_FLAG = flag
def __init__(
self,
requester: "Requester",
headers: Dict[str, Union[str, int]],
attributes: Any,
completed: bool,
):
self._requester = requester
self._initAttributes()
self._storeAndUseAttributes(headers, attributes)
# Ask requester to do some checking, for debug and test purpose
# Since it's most handy to access and kinda all-knowing
if self.CHECK_AFTER_INIT_FLAG: # pragma no branch (Flag always set in tests)
requester.check_me(self)
def _storeAndUseAttributes(self, headers: Dict[str, Union[str, int]], attributes: Any) -> None:
# Make sure headers are assigned before calling _useAttributes
# (Some derived classes will use headers in _useAttributes)
self._headers = headers
self._rawData = attributes
self._useAttributes(attributes)
@property
def requester(self) -> "Requester":
"""
Return my Requester object.
For example, to make requests to API endpoints not yet supported by PyGitHub.
"""
return self._requester
@property
def raw_data(self) -> Dict[str, Any]:
"""
:type: dict
"""
self._completeIfNeeded()
return self._rawData
@property
def raw_headers(self) -> Dict[str, Union[str, int]]:
"""
:type: dict
"""
self._completeIfNeeded()
return self._headers
@staticmethod
def _parentUrl(url: str) -> str:
return "/".join(url.split("/")[:-1])
@staticmethod
def __makeSimpleAttribute(value: Any, type: Type[T]) -> Attribute[T]:
if value is None or isinstance(value, type):
return _ValuedAttribute(value) # type: ignore
else:
return _BadAttribute(value, type) # type: ignore
@staticmethod
def __makeSimpleListAttribute(value: list, type: Type[T]) -> Attribute[T]:
if isinstance(value, list) and all(isinstance(element, type) for element in value):
return _ValuedAttribute(value) # type: ignore
else:
return _BadAttribute(value, [type]) # type: ignore
@staticmethod
def __makeTransformedAttribute(value: T, type: Type[T], transform: Callable[[T], K]) -> Attribute[K]:
if value is None:
return _ValuedAttribute(None) # type: ignore
elif isinstance(value, type):
try:
return _ValuedAttribute(transform(value))
except Exception as e:
return _BadAttribute(value, type, e) # type: ignore
else:
return _BadAttribute(value, type) # type: ignore
@staticmethod
def _makeStringAttribute(value: Optional[Union[int, str]]) -> Attribute[str]:
return GithubObject.__makeSimpleAttribute(value, str)
@staticmethod
def _makeIntAttribute(value: Optional[Union[int, str]]) -> Attribute[int]:
return GithubObject.__makeSimpleAttribute(value, int)
@staticmethod
def _makeDecimalAttribute(value: Optional[Decimal]) -> Attribute[Decimal]:
return GithubObject.__makeSimpleAttribute(value, Decimal)
@staticmethod
def _makeFloatAttribute(value: Optional[float]) -> Attribute[float]:
return GithubObject.__makeSimpleAttribute(value, float)
@staticmethod
def _makeBoolAttribute(value: Optional[bool]) -> Attribute[bool]:
return GithubObject.__makeSimpleAttribute(value, bool)
@staticmethod
def _makeDictAttribute(value: Dict[str, Any]) -> Attribute[Dict[str, Any]]:
return GithubObject.__makeSimpleAttribute(value, dict)
@staticmethod
def _makeTimestampAttribute(value: int) -> Attribute[datetime]:
return GithubObject.__makeTransformedAttribute(
value,
int,
lambda t: datetime.fromtimestamp(t, tz=timezone.utc),
)
@staticmethod
def _makeDatetimeAttribute(value: Optional[str]) -> Attribute[datetime]:
return GithubObject.__makeTransformedAttribute(value, str, _datetime_from_github_isoformat) # type: ignore
@staticmethod
def _makeHttpDatetimeAttribute(value: Optional[str]) -> Attribute[datetime]:
return GithubObject.__makeTransformedAttribute(value, str, _datetime_from_http_date) # type: ignore
def _makeClassAttribute(self, klass: Type[T_gh], value: Any) -> Attribute[T_gh]:
return GithubObject.__makeTransformedAttribute(
value,
dict,
lambda value: klass(self._requester, self._headers, value, completed=False),
)
@staticmethod
def _makeListOfStringsAttribute(value: Union[List[List[str]], List[str], List[Union[str, int]]]) -> Attribute:
return GithubObject.__makeSimpleListAttribute(value, str)
@staticmethod
def _makeListOfIntsAttribute(value: List[int]) -> Attribute:
return GithubObject.__makeSimpleListAttribute(value, int)
@staticmethod
def _makeListOfDictsAttribute(
value: List[Dict[str, Union[str, List[Dict[str, Union[str, List[int]]]]]]]
) -> Attribute:
return GithubObject.__makeSimpleListAttribute(value, dict)
@staticmethod
def _makeListOfListOfStringsAttribute(
value: List[List[str]],
) -> Attribute:
return GithubObject.__makeSimpleListAttribute(value, list)
def _makeListOfClassesAttribute(self, klass: Type[T_gh], value: Any) -> Attribute[List[T_gh]]:
if isinstance(value, list) and all(isinstance(element, dict) for element in value):
return _ValuedAttribute(
[klass(self._requester, self._headers, element, completed=False) for element in value]
)
else:
return _BadAttribute(value, [dict])
def _makeDictOfStringsToClassesAttribute(
self,
klass: Type[T_gh],
value: Dict[
str,
Union[int, Dict[str, Union[str, int, None]], Dict[str, Union[str, int]]],
],
) -> Attribute[Dict[str, T_gh]]:
if isinstance(value, dict) and all(
isinstance(key, str) and isinstance(element, dict) for key, element in value.items()
):
return _ValuedAttribute(
{key: klass(self._requester, self._headers, element, completed=False) for key, element in value.items()}
)
else:
return _BadAttribute(value, {str: dict})
@property
def etag(self) -> Optional[str]:
"""
:type: str
"""
return self._headers.get(Consts.RES_ETAG) # type: ignore
@property
def last_modified(self) -> Optional[str]:
"""
:type: str
"""
return self._headers.get(Consts.RES_LAST_MODIFIED) # type: ignore
@property
def last_modified_datetime(self) -> Optional[datetime]:
"""
:type: datetime
"""
return self._makeHttpDatetimeAttribute(self.last_modified).value # type: ignore
def get__repr__(self, params: Dict[str, Any]) -> str:
"""
Converts the object to a nicely printable string.
"""
def format_params(params: Dict[str, Any]) -> typing.Generator[str, None, None]:
items = list(params.items())
for k, v in sorted(items, key=itemgetter(0), reverse=True):
if isinstance(v, bytes):
v = v.decode("utf-8")
if isinstance(v, str):
v = f'"{v}"'
yield f"{k}={v}"
return "{class_name}({params})".format(
class_name=self.__class__.__name__,
params=", ".join(list(format_params(params))),
)
def _initAttributes(self) -> None:
raise NotImplementedError("BUG: Not Implemented _initAttributes")
def _useAttributes(self, attributes: Any) -> None:
raise NotImplementedError("BUG: Not Implemented _useAttributes")
def _completeIfNeeded(self) -> None:
raise NotImplementedError("BUG: Not Implemented _completeIfNeeded")
class NonCompletableGithubObject(GithubObject):
def _completeIfNeeded(self) -> None:
pass
class CompletableGithubObject(GithubObject):
def __init__(
self,
requester: "Requester",
headers: Dict[str, Union[str, int]],
attributes: Dict[str, Any],
completed: bool,
):
super().__init__(requester, headers, attributes, completed)
self.__completed = completed
def __eq__(self, other: Any) -> bool:
return other.__class__ is self.__class__ and other._url.value == self._url.value
def __hash__(self) -> int:
return hash(self._url.value)
def __ne__(self, other: Any) -> bool:
return not self == other
def _completeIfNotSet(self, value: Attribute) -> None:
if isinstance(value, _NotSetType):
self._completeIfNeeded()
def _completeIfNeeded(self) -> None:
if not self.__completed:
self.__complete()
def __complete(self) -> None:
if self._url.value is None:
raise IncompletableObject(400, message="Returned object contains no URL")
headers, data = self._requester.requestJsonAndCheck("GET", self._url.value)
self._storeAndUseAttributes(headers, data)
self.__completed = True
def update(self, additional_headers: Optional[Dict[str, Any]] = None) -> bool:
"""
Check and update the object with conditional request :rtype: Boolean value indicating whether the object is
changed.
"""
conditionalRequestHeader = dict()
if self.etag is not None:
conditionalRequestHeader[Consts.REQ_IF_NONE_MATCH] = self.etag
if self.last_modified is not None:
conditionalRequestHeader[Consts.REQ_IF_MODIFIED_SINCE] = self.last_modified
if additional_headers is not None:
conditionalRequestHeader.update(additional_headers)
status, responseHeaders, output = self._requester.requestJson(
"GET", self._url.value, headers=conditionalRequestHeader
)
if status == 304:
return False
else:
headers, data = self._requester._Requester__check(status, responseHeaders, output) # type: ignore
self._storeAndUseAttributes(headers, data)
self.__completed = True
return True
| 17,828
|
Python
|
.py
| 371
| 41.083558
| 120
| 0.615398
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,470
|
NamedUser.py
|
PyGithub_PyGithub/github/NamedUser.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Bruce Richardson <itsbruce@workshy.org> #
# Copyright 2018 Iraquitan Cordeiro Filho <iraquitanfilho@gmail.com> #
# Copyright 2018 Riccardo Pittau <elfosardo@users.noreply.github.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Victor Granic <vmg@boreal321.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 namc <namratachaudhary@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Pavan Kunisetty <nagapavan@users.noreply.github.com> #
# Copyright 2019 Shibasis Patel <smartshibasish@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Surya Teja <94suryateja@gmail.com> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Anuj Bansal <bansalanuj1996@gmail.com> #
# Copyright 2020 Daniel Haas <thisisdhaas@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Mark Amery <markamery@btinternet.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import urllib.parse
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.Event
import github.Gist
import github.GithubObject
import github.Organization
import github.PaginatedList
import github.Permissions
import github.Plan
import github.Repository
from github import Consts
from github.GithubObject import Attribute, NotSet, Opt, is_defined
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.Event import Event
from github.Gist import Gist
from github.Membership import Membership
from github.Organization import Organization
from github.Permissions import Permissions
from github.Plan import Plan
from github.Project import Project
from github.Repository import Repository
from github.UserKey import UserKey
class NamedUser(github.GithubObject.CompletableGithubObject):
"""
This class represents NamedUsers.
The reference can be found here
https://docs.github.com/en/rest/reference/users#get-a-user
"""
def _initAttributes(self) -> None:
self._avatar_url: Attribute[str] = NotSet
self._bio: Attribute[str | None] = NotSet
self._blog: Attribute[str | None] = NotSet
self._collaborators: Attribute[int] = NotSet
self._company: Attribute[str | None] = NotSet
self._contributions: Attribute[int] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._disk_usage: Attribute[int] = NotSet
self._email: Attribute[str | None] = NotSet
self._events_url: Attribute[str] = NotSet
self._followers: Attribute[int] = NotSet
self._followers_url: Attribute[str] = NotSet
self._following: Attribute[int] = NotSet
self._following_url: Attribute[str] = NotSet
self._gists_url: Attribute[str] = NotSet
self._gravatar_id: Attribute[str | None] = NotSet
self._hireable: Attribute[bool | None] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._invitation_teams_url: Attribute[str] = NotSet
self._inviter: Attribute[NamedUser] = NotSet
self._location: Attribute[str | None] = NotSet
self._login: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
self._node_id: Attribute[str] = NotSet
self._organizations_url: Attribute[str] = NotSet
self._owned_private_repos: Attribute[int] = NotSet
self._permissions: Attribute[Permissions] = NotSet
self._plan: Attribute[Plan] = NotSet
self._private_gists: Attribute[int] = NotSet
self._public_gists: Attribute[int] = NotSet
self._public_repos: Attribute[int] = NotSet
self._received_events_url: Attribute[str] = NotSet
self._repos_url: Attribute[str] = NotSet
self._role: Attribute[str] = NotSet
self._site_admin: Attribute[bool] = NotSet
self._starred_url: Attribute[str] = NotSet
self._subscriptions_url: Attribute[str] = NotSet
self._suspended_at: Attribute[datetime | None] = NotSet
self._team_count: Attribute[int] = NotSet
self._total_private_repos: Attribute[int] = NotSet
self._twitter_username: Attribute[str | None] = NotSet
self._type: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"login": self._login.value})
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
@property
def twitter_username(self) -> str | None:
self._completeIfNotSet(self._twitter_username)
return self._twitter_username.value
def __hash__(self) -> int:
return hash((self.id, self.login))
def __eq__(self, other: Any) -> bool:
return isinstance(other, type(self)) and self.login == other.login and self.id == other.id
@property
def avatar_url(self) -> str:
self._completeIfNotSet(self._avatar_url)
return self._avatar_url.value
@property
def bio(self) -> str | None:
self._completeIfNotSet(self._bio)
return self._bio.value
@property
def blog(self) -> str | None:
self._completeIfNotSet(self._blog)
return self._blog.value
@property
def collaborators(self) -> int | None:
self._completeIfNotSet(self._collaborators)
return self._collaborators.value
@property
def company(self) -> str | None:
self._completeIfNotSet(self._company)
return self._company.value
@property
def contributions(self) -> int:
self._completeIfNotSet(self._contributions)
return self._contributions.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def disk_usage(self) -> int:
self._completeIfNotSet(self._disk_usage)
return self._disk_usage.value
@property
def email(self) -> str | None:
self._completeIfNotSet(self._email)
return self._email.value
@property
def events_url(self) -> str:
self._completeIfNotSet(self._events_url)
return self._events_url.value
@property
def followers(self) -> int:
self._completeIfNotSet(self._followers)
return self._followers.value
@property
def followers_url(self) -> str:
self._completeIfNotSet(self._followers_url)
return self._followers_url.value
@property
def following(self) -> int:
self._completeIfNotSet(self._following)
return self._following.value
@property
def following_url(self) -> str:
self._completeIfNotSet(self._following_url)
return self._following_url.value
@property
def gists_url(self) -> str:
self._completeIfNotSet(self._gists_url)
return self._gists_url.value
@property
def gravatar_id(self) -> str | None:
self._completeIfNotSet(self._gravatar_id)
return self._gravatar_id.value
@property
def hireable(self) -> bool | None:
self._completeIfNotSet(self._hireable)
return self._hireable.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def invitation_teams_url(self) -> str:
self._completeIfNotSet(self._invitation_teams_url)
return self._invitation_teams_url.value
@property
def inviter(self) -> NamedUser:
self._completeIfNotSet(self._inviter)
return self._inviter.value
@property
def location(self) -> str | None:
self._completeIfNotSet(self._location)
return self._location.value
@property
def login(self) -> str:
self._completeIfNotSet(self._login)
return self._login.value
@property
def name(self) -> str | None:
self._completeIfNotSet(self._name)
return self._name.value
@property
def organizations_url(self) -> str:
self._completeIfNotSet(self._organizations_url)
return self._organizations_url.value
@property
def owned_private_repos(self) -> int | None:
self._completeIfNotSet(self._owned_private_repos)
return self._owned_private_repos.value
@property
def permissions(self) -> Permissions:
self._completeIfNotSet(self._permissions)
return self._permissions.value
@property
def plan(self) -> Plan | None:
self._completeIfNotSet(self._plan)
return self._plan.value
@property
def private_gists(self) -> int | None:
self._completeIfNotSet(self._private_gists)
return self._private_gists.value
@property
def public_gists(self) -> int:
self._completeIfNotSet(self._public_gists)
return self._public_gists.value
@property
def public_repos(self) -> int:
self._completeIfNotSet(self._public_repos)
return self._public_repos.value
@property
def received_events_url(self) -> str:
self._completeIfNotSet(self._received_events_url)
return self._received_events_url.value
@property
def repos_url(self) -> str:
self._completeIfNotSet(self._repos_url)
return self._repos_url.value
@property
def role(self) -> str:
self._completeIfNotSet(self._role)
return self._role.value
@property
def site_admin(self) -> bool:
self._completeIfNotSet(self._site_admin)
return self._site_admin.value
@property
def starred_url(self) -> str:
self._completeIfNotSet(self._starred_url)
return self._starred_url.value
@property
def subscriptions_url(self) -> str:
self._completeIfNotSet(self._subscriptions_url)
return self._subscriptions_url.value
@property
def suspended_at(self) -> datetime | None:
self._completeIfNotSet(self._suspended_at)
return self._suspended_at.value
@property
def team_count(self) -> int:
self._completeIfNotSet(self._team_count)
return self._team_count.value
@property
def total_private_repos(self) -> int | None:
self._completeIfNotSet(self._total_private_repos)
return self._total_private_repos.value
@property
def type(self) -> str:
self._completeIfNotSet(self._type)
return self._type.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def get_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /users/{user}/events <https://docs.github.com/en/rest/reference/activity#events>`_
"""
return github.PaginatedList.PaginatedList(github.Event.Event, self._requester, f"{self.url}/events", None)
def get_followers(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /users/{user}/followers <https://docs.github.com/en/rest/reference/users#followers>`_
"""
return github.PaginatedList.PaginatedList(NamedUser, self._requester, f"{self.url}/followers", None)
def get_following(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /users/{user}/following <https://docs.github.com/en/rest/reference/users#followers>`_
"""
return github.PaginatedList.PaginatedList(NamedUser, self._requester, f"{self.url}/following", None)
def get_gists(self, since: Opt[datetime] = NotSet) -> PaginatedList[Gist]:
"""
:calls: `GET /users/{user}/gists <https://docs.github.com/en/rest/reference/gists>`_
"""
assert since is NotSet or isinstance(since, datetime), since
url_parameters = dict()
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return github.PaginatedList.PaginatedList(
github.Gist.Gist, self._requester, f"{self.url}/gists", url_parameters
)
def get_keys(self) -> PaginatedList[UserKey]:
"""
:calls: `GET /users/{user}/keys <https://docs.github.com/en/rest/reference/users#create-a-public-ssh-key-for-the-authenticated-user>`_
"""
return github.PaginatedList.PaginatedList(github.UserKey.UserKey, self._requester, f"{self.url}/keys", None)
def get_orgs(self) -> PaginatedList[Organization]:
"""
:calls: `GET /users/{user}/orgs <https://docs.github.com/en/rest/reference/orgs>`_
"""
return github.PaginatedList.PaginatedList(
github.Organization.Organization, self._requester, f"{self.url}/orgs", None
)
def get_projects(self, state: str = "open") -> PaginatedList[Project]:
"""
:calls: `GET /users/{user}/projects <https://docs.github.com/en/rest/reference/projects#list-user-projects>`_
"""
assert isinstance(state, str), state
url_parameters = {"state": state}
return github.PaginatedList.PaginatedList(
github.Project.Project,
self._requester,
f"{self.url}/projects",
url_parameters,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
def get_public_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /users/{user}/events/public <https://docs.github.com/en/rest/reference/activity#events>`_
"""
return github.PaginatedList.PaginatedList(
github.Event.Event, self._requester, f"{self.url}/events/public", None
)
def get_public_received_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /users/{user}/received_events/public <https://docs.github.com/en/rest/reference/activity#events>`_
"""
return github.PaginatedList.PaginatedList(
github.Event.Event,
self._requester,
f"{self.url}/received_events/public",
None,
)
def get_received_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /users/{user}/received_events <https://docs.github.com/en/rest/reference/activity#events>`_
"""
return github.PaginatedList.PaginatedList(
github.Event.Event, self._requester, f"{self.url}/received_events", None
)
def get_repo(self, name: str) -> Repository:
"""
:calls: `GET /repos/{owner}/{repo} <https://docs.github.com/en/rest/reference/repos>`_
"""
assert isinstance(name, str), name
headers, data = self._requester.requestJsonAndCheck("GET", f"/repos/{self.login}/{name}")
return github.Repository.Repository(self._requester, headers, data, completed=True)
def get_repos(
self,
type: Opt[str] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
) -> PaginatedList[Repository]:
"""
:calls: `GET /users/{user}/repos <https://docs.github.com/en/rest/reference/repos>`_
"""
assert type is NotSet or isinstance(type, str), type
assert sort is NotSet or isinstance(sort, str), sort
assert direction is NotSet or isinstance(direction, str), direction
url_parameters = dict()
if type is not NotSet:
url_parameters["type"] = type
if sort is not NotSet:
url_parameters["sort"] = sort
if direction is not NotSet:
url_parameters["direction"] = direction
return github.PaginatedList.PaginatedList(
github.Repository.Repository,
self._requester,
f"{self.url}/repos",
url_parameters,
)
def get_starred(self) -> PaginatedList[Repository]:
"""
:calls: `GET /users/{user}/starred <https://docs.github.com/en/rest/reference/activity#starring>`_
"""
return github.PaginatedList.PaginatedList(
github.Repository.Repository, self._requester, f"{self.url}/starred", None
)
def get_subscriptions(self) -> PaginatedList[Repository]:
"""
:calls: `GET /users/{user}/subscriptions <https://docs.github.com/en/rest/reference/activity#watching>`_
"""
return github.PaginatedList.PaginatedList(
github.Repository.Repository,
self._requester,
f"{self.url}/subscriptions",
None,
)
def get_watched(self) -> PaginatedList[Repository]:
"""
:calls: `GET /users/{user}/watched <https://docs.github.com/en/rest/reference/activity#starring>`_
"""
return github.PaginatedList.PaginatedList(
github.Repository.Repository, self._requester, f"{self.url}/watched", None
)
def has_in_following(self, following: NamedUser) -> bool:
"""
:calls: `GET /users/{user}/following/{target_user} <https://docs.github.com/en/rest/reference/users#check-if-a-user-follows-another-user>`_
"""
assert isinstance(following, github.NamedUser.NamedUser), following
status, headers, data = self._requester.requestJson("GET", f"{self.url}/following/{following._identity}")
return status == 204
@property
def _identity(self) -> str:
return self.login
def get_organization_membership(self, org: str | Organization) -> Membership:
"""
:calls: `GET /orgs/{org}/memberships/{username} <https://docs.github.com/en/rest/reference/orgs#check-organization-membership-for-a-user>`_
"""
assert isinstance(org, str) or isinstance(org, github.Organization.Organization), org
if isinstance(org, github.Organization.Organization):
org = org.login # type: ignore
org = urllib.parse.quote(org)
headers, data = self._requester.requestJsonAndCheck("GET", f"/orgs/{org}/memberships/{self.login}")
return github.Membership.Membership(self._requester, headers, data, completed=True)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "avatar_url" in attributes: # pragma no branch
self._avatar_url = self._makeStringAttribute(attributes["avatar_url"])
if "bio" in attributes: # pragma no branch
self._bio = self._makeStringAttribute(attributes["bio"])
if "blog" in attributes: # pragma no branch
self._blog = self._makeStringAttribute(attributes["blog"])
if "collaborators" in attributes: # pragma no branch
self._collaborators = self._makeIntAttribute(attributes["collaborators"])
if "company" in attributes: # pragma no branch
self._company = self._makeStringAttribute(attributes["company"])
if "contributions" in attributes: # pragma no branch
self._contributions = self._makeIntAttribute(attributes["contributions"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "disk_usage" in attributes: # pragma no branch
self._disk_usage = self._makeIntAttribute(attributes["disk_usage"])
if "email" in attributes: # pragma no branch
self._email = self._makeStringAttribute(attributes["email"])
if "events_url" in attributes: # pragma no branch
self._events_url = self._makeStringAttribute(attributes["events_url"])
if "followers" in attributes: # pragma no branch
self._followers = self._makeIntAttribute(attributes["followers"])
if "followers_url" in attributes: # pragma no branch
self._followers_url = self._makeStringAttribute(attributes["followers_url"])
if "following" in attributes: # pragma no branch
self._following = self._makeIntAttribute(attributes["following"])
if "following_url" in attributes: # pragma no branch
self._following_url = self._makeStringAttribute(attributes["following_url"])
if "gists_url" in attributes: # pragma no branch
self._gists_url = self._makeStringAttribute(attributes["gists_url"])
if "gravatar_id" in attributes: # pragma no branch
self._gravatar_id = self._makeStringAttribute(attributes["gravatar_id"])
if "hireable" in attributes: # pragma no branch
self._hireable = self._makeBoolAttribute(attributes["hireable"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "invitation_teams_url" in attributes: # pragma no branch
self._invitation_teams_url = self._makeStringAttribute(attributes["invitation_teams_url"])
if "inviter" in attributes: # pragma no branch
self._inviter = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["inviter"])
if "location" in attributes: # pragma no branch
self._location = self._makeStringAttribute(attributes["location"])
if "login" in attributes: # pragma no branch
self._login = self._makeStringAttribute(attributes["login"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "organizations_url" in attributes: # pragma no branch
self._organizations_url = self._makeStringAttribute(attributes["organizations_url"])
if "owned_private_repos" in attributes: # pragma no branch
self._owned_private_repos = self._makeIntAttribute(attributes["owned_private_repos"])
if "permissions" in attributes: # pragma no branch
self._permissions = self._makeClassAttribute(github.Permissions.Permissions, attributes["permissions"])
if "plan" in attributes: # pragma no branch
self._plan = self._makeClassAttribute(github.Plan.Plan, attributes["plan"])
if "private_gists" in attributes: # pragma no branch
self._private_gists = self._makeIntAttribute(attributes["private_gists"])
if "public_gists" in attributes: # pragma no branch
self._public_gists = self._makeIntAttribute(attributes["public_gists"])
if "public_repos" in attributes: # pragma no branch
self._public_repos = self._makeIntAttribute(attributes["public_repos"])
if "received_events_url" in attributes: # pragma no branch
self._received_events_url = self._makeStringAttribute(attributes["received_events_url"])
if "repos_url" in attributes: # pragma no branch
self._repos_url = self._makeStringAttribute(attributes["repos_url"])
if "role" in attributes: # pragma no branch
self._role = self._makeStringAttribute(attributes["role"])
if "site_admin" in attributes: # pragma no branch
self._site_admin = self._makeBoolAttribute(attributes["site_admin"])
if "starred_url" in attributes: # pragma no branch
self._starred_url = self._makeStringAttribute(attributes["starred_url"])
if "subscriptions_url" in attributes: # pragma no branch
self._subscriptions_url = self._makeStringAttribute(attributes["subscriptions_url"])
if "suspended_at" in attributes: # pragma no branch
self._suspended_at = self._makeDatetimeAttribute(attributes["suspended_at"])
if "team_count" in attributes:
self._team_count = self._makeIntAttribute(attributes["team_count"])
if "total_private_repos" in attributes: # pragma no branch
self._total_private_repos = self._makeIntAttribute(attributes["total_private_repos"])
if "twitter_username" in attributes: # pragma no branch
self._twitter_username = self._makeStringAttribute(attributes["twitter_username"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 28,105
|
Python
|
.py
| 558
| 42.636201
| 147
| 0.628881
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,471
|
Reaction.py
|
PyGithub_PyGithub/github/Reaction.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Nicolas Agustín Torres <nicolastrres@gmail.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.NamedUser
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
from . import Consts
if TYPE_CHECKING:
from github.NamedUser import NamedUser
class Reaction(CompletableGithubObject):
"""
This class represents Reactions.
The reference can be found here
https://docs.github.com/en/rest/reference/reactions
"""
def _initAttributes(self) -> None:
self._content: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._id: Attribute[int] = NotSet
self._user: Attribute[NamedUser] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "user": self._user.value})
@property
def content(self) -> str:
self._completeIfNotSet(self._content)
return self._content.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def user(self) -> NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
def delete(self) -> None:
"""
:calls: `DELETE /reactions/{id} <https://docs.github.com/en/rest/reference/reactions#delete-a-reaction-legacy>`_
:rtype: None
"""
self._requester.requestJsonAndCheck(
"DELETE",
f"{self._parentUrl('')}/reactions/{self.id}",
headers={"Accept": Consts.mediaTypeReactionsPreview},
)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "content" in attributes: # pragma no branch
self._content = self._makeStringAttribute(attributes["content"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 5,576
|
Python
|
.py
| 96
| 53.364583
| 120
| 0.539447
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,472
|
NamedEnterpriseUser.py
|
PyGithub_PyGithub/github/NamedEnterpriseUser.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 YugoHino <henom06@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
class NamedEnterpriseUser(CompletableGithubObject):
"""
This class represents NamedEnterpriseUsers.
The reference can be found here
https://docs.github.com/en/enterprise-cloud@latest/rest/enterprise-admin/license#list-enterprise-consumed-licenses
"""
def _initAttributes(self) -> None:
self._github_com_login: Attribute[str] = NotSet
self._github_com_name: Attribute[str] = NotSet
self._enterprise_server_user_ids: Attribute[list] = NotSet
self._github_com_user: Attribute[bool] = NotSet
self._enterprise_server_user: Attribute[bool] = NotSet
self._visual_studio_subscription_user: Attribute[bool] = NotSet
self._license_type: Attribute[str] = NotSet
self._github_com_profile: Attribute[str] = NotSet
self._github_com_member_roles: Attribute[list] = NotSet
self._github_com_enterprise_roles: Attribute[list] = NotSet
self._github_com_verified_domain_emails: Attribute[list] = NotSet
self._github_com_saml_name_id: Attribute[str] = NotSet
self._github_com_orgs_with_pending_invites: Attribute[list] = NotSet
self._github_com_two_factor_auth: Attribute[bool] = NotSet
self._enterprise_server_primary_emails: Attribute[list] = NotSet
self._visual_studio_license_status: Attribute[str] = NotSet
self._visual_studio_subscription_email: Attribute[str] = NotSet
self._total_user_accounts: Attribute[int] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"login": self._github_com_login.value})
@property
def github_com_login(self) -> str:
self._completeIfNotSet(self._github_com_login)
return self._github_com_login.value
@property
def github_com_name(self) -> str:
self._completeIfNotSet(self._github_com_name)
return self._github_com_name.value
@property
def enterprise_server_user_ids(self) -> list:
self._completeIfNotSet(self._enterprise_server_user_ids)
return self._enterprise_server_user_ids.value
@property
def github_com_user(self) -> bool:
self._completeIfNotSet(self._github_com_user)
return self._github_com_user.value
@property
def enterprise_server_user(self) -> bool:
self._completeIfNotSet(self._enterprise_server_user)
return self._enterprise_server_user.value
@property
def visual_studio_subscription_user(self) -> bool:
self._completeIfNotSet(self._visual_studio_subscription_user)
return self._visual_studio_subscription_user.value
@property
def license_type(self) -> str:
self._completeIfNotSet(self._license_type)
return self._license_type.value
@property
def github_com_profile(self) -> str:
self._completeIfNotSet(self._github_com_profile)
return self._github_com_profile.value
@property
def github_com_member_roles(self) -> list:
self._completeIfNotSet(self._github_com_member_roles)
return self._github_com_member_roles.value
@property
def github_com_enterprise_roles(self) -> list:
self._completeIfNotSet(self._github_com_enterprise_roles)
return self._github_com_enterprise_roles.value
@property
def github_com_verified_domain_emails(self) -> list:
self._completeIfNotSet(self._github_com_verified_domain_emails)
return self._github_com_verified_domain_emails.value
@property
def github_com_saml_name_id(self) -> str:
self._completeIfNotSet(self._github_com_saml_name_id)
return self._github_com_saml_name_id.value
@property
def github_com_orgs_with_pending_invites(self) -> list:
self._completeIfNotSet(self._github_com_orgs_with_pending_invites)
return self._github_com_orgs_with_pending_invites.value
@property
def github_com_two_factor_auth(self) -> bool:
self._completeIfNotSet(self._github_com_two_factor_auth)
return self._github_com_two_factor_auth.value
@property
def enterprise_server_primary_emails(self) -> list:
self._completeIfNotSet(self._enterprise_server_primary_emails)
return self._enterprise_server_primary_emails.value
@property
def visual_studio_license_status(self) -> str:
self._completeIfNotSet(self._visual_studio_license_status)
return self._visual_studio_license_status.value
@property
def visual_studio_subscription_email(self) -> str:
self._completeIfNotSet(self._visual_studio_subscription_email)
return self._visual_studio_subscription_email.value
@property
def total_user_accounts(self) -> int:
self._completeIfNotSet(self._total_user_accounts)
return self._total_user_accounts.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "github_com_login" in attributes: # pragma no branch
self._github_com_login = self._makeStringAttribute(attributes["github_com_login"])
if "github_com_name" in attributes: # pragma no branch
self._github_com_name = self._makeStringAttribute(attributes["github_com_name"])
if "enterprise_server_user_ids" in attributes: # pragma no branch
self._enterprise_server_user_ids = self._makeListOfStringsAttribute(
attributes["enterprise_server_user_ids"]
)
if "github_com_user" in attributes: # pragma no branch
self._github_com_user = self._makeBoolAttribute(attributes["github_com_user"])
if "enterprise_server_user" in attributes: # pragma no branch
self._enterprise_server_user = self._makeBoolAttribute(attributes["enterprise_server_user"])
if "visual_studio_subscription_user" in attributes: # pragma no branch
self._visual_studio_subscription_user = self._makeBoolAttribute(
attributes["visual_studio_subscription_user"]
)
if "license_type" in attributes: # pragma no branch
self._license_type = self._makeStringAttribute(attributes["license_type"])
if "github_com_profile" in attributes: # pragma no branch
self._github_com_profile = self._makeStringAttribute(attributes["github_com_profile"])
if "github_com_member_roles" in attributes: # pragma no branch
self._github_com_member_roles = self._makeListOfStringsAttribute(attributes["github_com_member_roles"])
if "github_com_enterprise_roles" in attributes: # pragma no branch
self._github_com_enterprise_roles = self._makeListOfStringsAttribute(
attributes["github_com_enterprise_roles"]
)
if "github_com_verified_domain_emails" in attributes: # pragma no branch
self._github_com_verified_domain_emails = self._makeListOfStringsAttribute(
attributes["github_com_verified_domain_emails"]
)
if "github_com_saml_name_id" in attributes: # pragma no branch
self._github_com_saml_name_id = self._makeStringAttribute(attributes["github_com_saml_name_id"])
if "github_com_orgs_with_pending_invites" in attributes: # pragma no branch
self._github_com_orgs_with_pending_invites = self._makeListOfStringsAttribute(
attributes["github_com_orgs_with_pending_invites"]
)
if "github_com_two_factor_auth" in attributes: # pragma no branch
self._github_com_two_factor_auth = self._makeBoolAttribute(attributes["github_com_two_factor_auth"])
if "enterprise_server_primary_emails" in attributes: # pragma no branch
self._enterprise_server_primary_emails = self._makeListOfStringsAttribute(
attributes["enterprise_server_primary_emails"]
)
if "visual_studio_license_status" in attributes: # pragma no branch
self._visual_studio_license_status = self._makeStringAttribute(attributes["visual_studio_license_status"])
if "visual_studio_subscription_email" in attributes: # pragma no branch
self._visual_studio_subscription_email = self._makeStringAttribute(
attributes["visual_studio_subscription_email"]
)
if "total_user_accounts" in attributes: # pragma no branch
self._total_user_accounts = self._makeIntAttribute(attributes["total_user_accounts"])
| 10,462
|
Python
|
.py
| 176
| 51.630682
| 118
| 0.63359
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,473
|
HookDelivery.py
|
PyGithub_PyGithub/github/HookDelivery.py
|
############################ Copyrights and license ############################
# #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict, Optional
import github.GithubObject
from github.GithubObject import Attribute, NotSet
class HookDeliverySummary(github.GithubObject.NonCompletableGithubObject):
"""
This class represents a Summary of HookDeliveries.
"""
def _initAttributes(self) -> None:
self._id: Attribute[int] = NotSet
self._guid: Attribute[str] = NotSet
self._delivered_at: Attribute[datetime] = NotSet
self._redelivery: Attribute[bool] = NotSet
self._duration: Attribute[float] = NotSet
self._status: Attribute[str] = NotSet
self._status_code: Attribute[int] = NotSet
self._event: Attribute[str] = NotSet
self._action: Attribute[str] = NotSet
self._installation_id: Attribute[int] = NotSet
self._repository_id: Attribute[int] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def id(self) -> Optional[int]:
return self._id.value
@property
def guid(self) -> Optional[str]:
return self._guid.value
@property
def delivered_at(self) -> Optional[datetime]:
return self._delivered_at.value
@property
def redelivery(self) -> Optional[bool]:
return self._redelivery.value
@property
def duration(self) -> Optional[float]:
return self._duration.value
@property
def status(self) -> Optional[str]:
return self._status.value
@property
def status_code(self) -> Optional[int]:
return self._status_code.value
@property
def event(self) -> Optional[str]:
return self._event.value
@property
def action(self) -> Optional[str]:
return self._action.value
@property
def installation_id(self) -> Optional[int]:
return self._installation_id.value
@property
def repository_id(self) -> Optional[int]:
return self._repository_id.value
@property
def url(self) -> Optional[str]:
return self._url.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "guid" in attributes: # pragma no branch
self._guid = self._makeStringAttribute(attributes["guid"])
if "delivered_at" in attributes: # pragma no branch
self._delivered_at = self._makeDatetimeAttribute(attributes["delivered_at"])
if "redelivery" in attributes: # pragma no branch
self._redelivery = self._makeBoolAttribute(attributes["redelivery"])
if "duration" in attributes: # pragma no branch
self._duration = self._makeFloatAttribute(attributes["duration"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
if "status_code" in attributes: # pragma no branch
self._status_code = self._makeIntAttribute(attributes["status_code"])
if "event" in attributes: # pragma no branch
self._event = self._makeStringAttribute(attributes["event"])
if "action" in attributes: # pragma no branch
self._action = self._makeStringAttribute(attributes["action"])
if "installation_id" in attributes: # pragma no branch
self._installation_id = self._makeIntAttribute(attributes["installation_id"])
if "repository_id" in attributes: # pragma no branch
self._repository_id = self._makeIntAttribute(attributes["repository_id"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
class HookDeliveryRequest(github.GithubObject.NonCompletableGithubObject):
"""
This class represents a HookDeliveryRequest.
"""
def _initAttributes(self) -> None:
self._request_headers: Attribute[Dict] = NotSet
self._payload: Attribute[Dict] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"payload": self._payload.value})
@property
def headers(self) -> Optional[dict]:
return self._request_headers.value
@property
def payload(self) -> Optional[dict]:
return self._payload.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "headers" in attributes: # pragma no branch
self._request_headers = self._makeDictAttribute(attributes["headers"])
if "payload" in attributes: # pragma no branch
self._payload = self._makeDictAttribute(attributes["payload"])
class HookDeliveryResponse(github.GithubObject.NonCompletableGithubObject):
"""
This class represents a HookDeliveryResponse.
"""
def __repr__(self) -> str:
return self.get__repr__({"payload": self._payload.value})
@property
def headers(self) -> Optional[dict]:
return self._response_headers.value
@property
def payload(self) -> Optional[str]:
return self._payload.value
def _initAttributes(self) -> None:
self._response_headers: Attribute[Dict] = NotSet
self._payload: Attribute[str] = NotSet
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "headers" in attributes: # pragma no branch
self._response_headers = self._makeDictAttribute(attributes["headers"])
if "payload" in attributes: # pragma no branch
self._payload = self._makeStringAttribute(attributes["payload"])
class HookDelivery(HookDeliverySummary):
"""
This class represents a HookDelivery.
"""
def _initAttributes(self) -> None:
super()._initAttributes()
self._request: Attribute[HookDeliveryRequest] = NotSet
self._response: Attribute[HookDeliveryResponse] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value})
@property
def request(self) -> Optional[HookDeliveryRequest]:
return self._request.value
@property
def response(self) -> Optional[HookDeliveryResponse]:
return self._response.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
super()._useAttributes(attributes)
if "request" in attributes: # pragma no branch
self._request = self._makeClassAttribute(HookDeliveryRequest, attributes["request"])
if "response" in attributes: # pragma no branch
self._response = self._makeClassAttribute(HookDeliveryResponse, attributes["response"])
# self._response = self._makeDictAttribute(attributes["response"])
| 8,838
|
Python
|
.py
| 173
| 44.375723
| 99
| 0.60487
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,474
|
View.py
|
PyGithub_PyGithub/github/View.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Justin Kufro <jkufro@andrew.cmu.edu> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime
from typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class View(NonCompletableGithubObject):
"""
This class represents a popular Path for a GitHub repository.
The reference can be found here
https://docs.github.com/en/rest/reference/repos#traffic
"""
def _initAttributes(self) -> None:
self._timestamp: Attribute[datetime] = NotSet
self._count: Attribute[int] = NotSet
self._uniques: Attribute[int] = NotSet
def __repr__(self) -> str:
return self.get__repr__(
{
"timestamp": self._timestamp.value,
"count": self._count.value,
"uniques": self._uniques.value,
}
)
@property
def timestamp(self) -> datetime:
return self._timestamp.value
@property
def count(self) -> int:
return self._count.value
@property
def uniques(self) -> int:
return self._uniques.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "timestamp" in attributes: # pragma no branch
self._timestamp = self._makeDatetimeAttribute(attributes["timestamp"])
if "count" in attributes: # pragma no branch
self._count = self._makeIntAttribute(attributes["count"])
if "uniques" in attributes: # pragma no branch
self._uniques = self._makeIntAttribute(attributes["uniques"])
| 4,579
|
Python
|
.py
| 75
| 56.533333
| 82
| 0.507124
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,475
|
CheckSuite.py
|
PyGithub_PyGithub/github/CheckSuite.py
|
############################ Copyrights and license ############################
# #
# Copyright 2020 Dhruv Manilawala <dhruvmanila@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Yannick Jadoul <yannick.jadoul@belgacom.net> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING, Any
import github.CheckRun
import github.GitCommit
import github.GithubApp
import github.PullRequest
import github.Repository
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_defined, is_optional
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.CheckRun import CheckRun
from github.GitCommit import GitCommit
from github.GithubApp import GithubApp
from github.PullRequest import PullRequest
from github.Repository import Repository
class CheckSuite(CompletableGithubObject):
"""
This class represents check suites.
The reference can be found here
https://docs.github.com/en/rest/reference/checks#check-suites
"""
def _initAttributes(self) -> None:
self._after: Attribute[str] = NotSet
self._app: Attribute[GithubApp] = NotSet
self._before: Attribute[str] = NotSet
self._check_runs_url: Attribute[str] = NotSet
self._conclusion: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._head_branch: Attribute[str] = NotSet
self._head_commit: Attribute[GitCommit] = NotSet
self._head_sha: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._latest_check_runs_count: Attribute[int] = NotSet
self._pull_requests: Attribute[list[PullRequest]] = NotSet
self._repository: Attribute[Repository] = NotSet
self._status: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"id": self._id.value, "url": self._url.value})
@property
def after(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._after)
return self._after.value
@property
def app(self) -> GithubApp:
"""
:type: :class:`github.GithubApp.GithubApp`
"""
self._completeIfNotSet(self._app)
return self._app.value
@property
def before(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._before)
return self._before.value
@property
def check_runs_url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._check_runs_url)
return self._check_runs_url.value
@property
def conclusion(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._conclusion)
return self._conclusion.value
@property
def created_at(self) -> datetime:
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def head_branch(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._head_branch)
return self._head_branch.value
@property
def head_commit(self) -> GitCommit:
"""
:type: :class:`github.GitCommit.GitCommit`
"""
self._completeIfNotSet(self._head_commit)
return self._head_commit.value
@property
def head_sha(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._head_sha)
return self._head_sha.value
@property
def id(self) -> int:
"""
:type: int
"""
self._completeIfNotSet(self._id)
return self._id.value
@property
def latest_check_runs_count(self) -> int:
"""
:type: int
"""
self._completeIfNotSet(self._latest_check_runs_count)
return self._latest_check_runs_count.value
@property
def pull_requests(self) -> list[PullRequest]:
"""
:type: list of :class:`github.PullRequest.PullRequest`
"""
self._completeIfNotSet(self._pull_requests)
return self._pull_requests.value
@property
def repository(self) -> Repository:
"""
:type: :class:`github.Repository.Repository`
"""
self._completeIfNotSet(self._repository)
return self._repository.value
@property
def status(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._status)
return self._status.value
@property
def updated_at(self) -> datetime:
"""
:type: datetime.datetime
"""
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
"""
:type: string
"""
self._completeIfNotSet(self._url)
return self._url.value
def rerequest(self) -> bool:
"""
:calls: `POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest <https://docs.github.com/en/rest/reference/checks#rerequest-a-check-suite>`_
:rtype: bool
"""
request_headers = {"Accept": "application/vnd.github.v3+json"}
status, _, _ = self._requester.requestJson("POST", f"{self.url}/rerequest", headers=request_headers)
return status == 201
def get_check_runs(
self,
check_name: Opt[str] = NotSet,
status: Opt[str] = NotSet,
filter: Opt[str] = NotSet,
) -> PaginatedList[CheckRun]:
"""
:calls: `GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs <https://docs.github.com/en/rest/reference/checks#list-check-runs-in-a-check-suite>`_
"""
assert is_optional(check_name, str), check_name
assert is_optional(status, str), status
assert is_optional(filter, str), filter
url_parameters: dict[str, Any] = {}
if is_defined(check_name):
url_parameters["check_name"] = check_name
if is_defined(status):
url_parameters["status"] = status
if is_defined(filter):
url_parameters["filter"] = filter
return PaginatedList(
github.CheckRun.CheckRun,
self._requester,
f"{self.url}/check-runs",
url_parameters,
headers={"Accept": "application/vnd.github.v3+json"},
list_item="check_runs",
)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "after" in attributes: # pragma no branch
self._after = self._makeStringAttribute(attributes["after"])
if "app" in attributes: # pragma no branch
self._app = self._makeClassAttribute(github.GithubApp.GithubApp, attributes["app"])
if "before" in attributes: # pragma no branch
self._before = self._makeStringAttribute(attributes["before"])
if "check_runs_url" in attributes: # pragma no branch
self._check_runs_url = self._makeStringAttribute(attributes["check_runs_url"])
if "conclusion" in attributes: # pragma no branch
self._conclusion = self._makeStringAttribute(attributes["conclusion"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "head_branch" in attributes: # pragma no branch
self._head_branch = self._makeStringAttribute(attributes["head_branch"])
if "head_commit" in attributes: # pragma no branch
# This JSON swaps the 'sha' attribute for an 'id' attribute.
# The GitCommit object only looks for 'sha'
if "id" in attributes["head_commit"]:
attributes["head_commit"]["sha"] = attributes["head_commit"]["id"]
self._head_commit = self._makeClassAttribute(github.GitCommit.GitCommit, attributes["head_commit"])
if "head_sha" in attributes: # pragma no branch
self._head_sha = self._makeStringAttribute(attributes["head_sha"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "latest_check_runs_count" in attributes: # pragma no branch
self._latest_check_runs_count = self._makeIntAttribute(attributes["latest_check_runs_count"])
if "pull_requests" in attributes: # pragma no branch
self._pull_requests = self._makeListOfClassesAttribute(
github.PullRequest.PullRequest, attributes["pull_requests"]
)
if "repository" in attributes: # pragma no branch
self._repository = self._makeClassAttribute(github.Repository.Repository, attributes["repository"])
if "status" in attributes: # pragma no branch
self._status = self._makeStringAttribute(attributes["status"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 11,437
|
Python
|
.py
| 256
| 37.078125
| 169
| 0.584469
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,476
|
GitignoreTemplate.py
|
PyGithub_PyGithub/github/GitignoreTemplate.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 typing import Any, Dict
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class GitignoreTemplate(NonCompletableGithubObject):
"""
This class represents GitignoreTemplates.
The reference can be found here
https://docs.github.com/en/rest/reference/gitignore
"""
def _initAttributes(self) -> None:
self._source: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def source(self) -> str:
return self._source.value
@property
def name(self) -> str:
return self._name.value
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "source" in attributes: # pragma no branch
self._source = self._makeStringAttribute(attributes["source"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
| 4,012
|
Python
|
.py
| 61
| 62.491803
| 80
| 0.49797
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,477
|
OrganizationCustomProperty.py
|
PyGithub_PyGithub/github/OrganizationCustomProperty.py
|
############################ Copyrights and license ############################
# #
# Copyright 2024 Jacky Lam <jacky.lam@r2studiohk.com> #
# #
# 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 __future__ import annotations
from typing import Any
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet, Opt, is_optional
class CustomProperty:
"""
This class represents a CustomProperty for an Organization. Use this class to create a new post parameter object.
The reference can be found here
https://docs.github.com/en/rest/orgs/custom-properties#create-or-update-custom-properties-for-an-organization
"""
def __init__(
self,
property_name: str,
value_type: str,
required: Opt[bool] = NotSet,
default_value: Opt[None | str | list[str]] = NotSet,
description: Opt[str | None] = NotSet,
allowed_values: Opt[list[str] | None] = NotSet,
values_editable_by: Opt[str | None] = NotSet,
):
assert isinstance(property_name, str), property_name
assert isinstance(value_type, str), value_type
assert value_type in ["string", "single_select"], value_type
assert is_optional(required, bool), required
assert is_optional(default_value, (type(None), str, list)), default_value
assert is_optional(description, (str, type(None))), description
assert is_optional(allowed_values, (list, type(None))), allowed_values
assert is_optional(values_editable_by, (str, type(None))), values_editable_by
if values_editable_by is not NotSet:
assert values_editable_by in ["org_actors", "org_and_repo_actors"], values_editable_by
self.property_name = property_name
self.value_type = value_type
self.required = required
self.default_value = default_value
self.description = description
self.allowed_values = allowed_values
self.values_editable_by = values_editable_by
def to_dict(self) -> dict[str, Any]:
return NotSet.remove_unset_items(self.__dict__)
class OrganizationCustomProperty(NonCompletableGithubObject):
"""
This class represents a CustomProperty for an Organization.
The reference can be found here
https://docs.github.com/en/rest/orgs/custom-properties
"""
@property
def property_name(self) -> str:
return self._property_name.value
@property
def value_type(self) -> str:
return self._value_type.value
@property
def required(self) -> Opt[bool | None]:
return self._required.value
@property
def default_value(self) -> Opt[str | list[str] | None]:
return self._default_value.value
@property
def description(self) -> Opt[str | None]:
return self._description.value
@property
def allowed_values(self) -> Opt[list[str] | None]:
return self._allowed_values.value
@property
def values_editable_by(self) -> Opt[str | None]:
return self._values_editable_by.value
def _initAttributes(self) -> None:
self._property_name: Attribute[str] = NotSet
self._value_type: Attribute[str] = NotSet
self._required: Attribute[bool] = NotSet
self._default_value: Attribute[str | list[str]] = NotSet
self._description: Attribute[str] = NotSet
self._allowed_values: Attribute[list[str]] = NotSet
self._values_editable_by: Attribute[str] = NotSet
def _useAttributes(self, attributes: dict[str, Any]) -> None:
self._property_name = self._makeStringAttribute(attributes["property_name"])
self._value_type = self._makeStringAttribute(attributes["value_type"])
if "required" in attributes:
self._required = self._makeBoolAttribute(attributes["required"])
if "default_value" in attributes:
self._default_value = self._makeStringAttribute(attributes["default_value"])
if "description" in attributes:
self._description = self._makeStringAttribute(attributes["description"])
if "allowed_values" in attributes:
self._allowed_values = self._makeListOfStringsAttribute(attributes["allowed_values"])
if "values_editable_by" in attributes:
self._values_editable_by = self._makeStringAttribute(attributes["values_editable_by"])
class RepositoryCustomPropertyValues(NonCompletableGithubObject):
"""
This class represents CustomPropertyValues for a Repository.
The reference can be found here
https://docs.github.com/en/rest/orgs/custom-properties#list-custom-property-values-for-organization-repositories
"""
@property
def respository_id(self) -> int:
return self._repository_id.value
@property
def repository_name(self) -> str:
return self._repository_name.value
@property
def repository_full_name(self) -> str:
return self._repository_full_name.value
@property
def properties(self) -> dict[str, str]:
return self._properties.value
def _initAttributes(self) -> None:
self._repository_id: Attribute[int] = NotSet
self._repository_name: Attribute[str] = NotSet
self._repository_full_name: Attribute[str] = NotSet
self._properties: Attribute[dict[str, str]] = NotSet
def _useAttributes(self, attributes: dict[str, Any]) -> None:
self._repository_id = self._makeIntAttribute(attributes["repository_id"])
self._repository_name = self._makeStringAttribute(attributes["repository_name"])
self._repository_full_name = self._makeStringAttribute(attributes["repository_full_name"])
properties = {p["property_name"]: p["value"] for p in attributes["properties"]}
self._properties = self._makeDictAttribute(properties)
| 7,333
|
Python
|
.py
| 136
| 47.382353
| 117
| 0.60818
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,478
|
AuthenticatedUser.py
|
PyGithub_PyGithub/github/AuthenticatedUser.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Steve English <steve.english@navetas.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Cameron White <cawhite@pdx.edu> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 poulp <mathieu.nerv@gmail.com> #
# Copyright 2014 Tomas Radej <tradej@redhat.com> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 E. Dunham <github@edunham.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Balázs Rostás <rostas.balazs@gmail.com> #
# Copyright 2017 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2018 Bruce Richardson <itsbruce@workshy.org> #
# Copyright 2018 Riccardo Pittau <elfosardo@users.noreply.github.com> #
# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 bryanhuntesl <31992054+bryanhuntesl@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Jamie van Brunschot <j.brunschot@coolblue.nl> #
# Copyright 2019 Jon Dufresne <jon.dufresne@gmail.com> #
# Copyright 2019 Pavan Kunisetty <nagapavan@users.noreply.github.com> #
# Copyright 2019 Rigas Papathanasopoulos <rigaspapas@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Surya Teja <94suryateja@gmail.com> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Anuj Bansal <bansalanuj1996@gmail.com> #
# Copyright 2020 Glenn McDonald <testworksau@users.noreply.github.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 MeggyCal <MeggyCal@users.noreply.github.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Yuya Nakamura <yuyan7sh@gmail.com> #
# Copyright 2021 sshekdar-VMware <87147229+sshekdar-VMware@users.noreply.github.com>#
# Copyright 2021 秋葉 <ambiguous404@gmail.com> #
# Copyright 2022 KimSia Sim <245021+simkimsia@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Kevin Grandjean <Muscaw@users.noreply.github.com> #
# Copyright 2023 Mark Amery <markamery@btinternet.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 chantra <chantra@users.noreply.github.com> #
# Copyright 2024 Chris Wells <ping@cwlls.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com>#
# #
# 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 __future__ import annotations
import urllib.parse
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, NamedTuple
import github.Authorization
import github.Event
import github.Gist
import github.GithubObject
import github.Invitation
import github.Issue
import github.Membership
import github.Migration
import github.NamedUser
import github.Notification
import github.Organization
import github.Plan
import github.Repository
import github.UserKey
from github import Consts
from github.GithubObject import (
Attribute,
CompletableGithubObject,
NotSet,
Opt,
is_defined,
is_optional,
is_optional_list,
is_undefined,
)
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.Authorization import Authorization
from github.Event import Event
from github.Gist import Gist
from github.InputFileContent import InputFileContent
from github.Installation import Installation
from github.Invitation import Invitation
from github.Issue import Issue
from github.Label import Label
from github.Membership import Membership
from github.Migration import Migration
from github.NamedUser import NamedUser
from github.Notification import Notification
from github.Organization import Organization
from github.Plan import Plan
from github.Project import Project
from github.Repository import Repository
from github.Team import Team
from github.UserKey import UserKey
class EmailData(NamedTuple):
email: str
primary: bool
verified: bool
visibility: str
class AuthenticatedUser(CompletableGithubObject):
"""
This class represents AuthenticatedUsers as returned by https://docs.github.com/en/rest/reference/users#get-the-authenticated-user
An AuthenticatedUser object can be created by calling ``get_user()`` on a Github object.
"""
def _initAttributes(self) -> None:
self._avatar_url: Attribute[str] = NotSet
self._bio: Attribute[str] = NotSet
self._blog: Attribute[str] = NotSet
self._collaborators: Attribute[int] = NotSet
self._company: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._disk_usage: Attribute[int] = NotSet
self._email: Attribute[str] = NotSet
self._events_url: Attribute[str] = NotSet
self._followers: Attribute[int] = NotSet
self._followers_url: Attribute[str] = NotSet
self._following: Attribute[int] = NotSet
self._following_url: Attribute[str] = NotSet
self._gists_url: Attribute[str] = NotSet
self._gravatar_id: Attribute[str] = NotSet
self._hireable: Attribute[bool] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._location: Attribute[str] = NotSet
self._login: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
self._node_id: Attribute[str] = NotSet
self._organizations_url: Attribute[str] = NotSet
self._owned_private_repos: Attribute[int] = NotSet
self._plan: Attribute[github.Plan.Plan] = NotSet
self._private_gists: Attribute[int] = NotSet
self._public_gists: Attribute[int] = NotSet
self._public_repos: Attribute[int] = NotSet
self._received_events_url: Attribute[str] = NotSet
self._repos_url: Attribute[str] = NotSet
self._site_admin: Attribute[bool] = NotSet
self._starred_url: Attribute[str] = NotSet
self._subscriptions_url: Attribute[str] = NotSet
self._total_private_repos: Attribute[int] = NotSet
self._type: Attribute[str] = NotSet
self._updated_at: Attribute[datetime] = NotSet
self._url: Attribute[str] = NotSet
self._two_factor_authentication: Attribute[bool] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"login": self._login.value})
@property
def avatar_url(self) -> str:
self._completeIfNotSet(self._avatar_url)
return self._avatar_url.value
@property
def bio(self) -> str:
self._completeIfNotSet(self._bio)
return self._bio.value
@property
def blog(self) -> str:
self._completeIfNotSet(self._blog)
return self._blog.value
@property
def collaborators(self) -> int:
self._completeIfNotSet(self._collaborators)
return self._collaborators.value
@property
def company(self) -> str:
self._completeIfNotSet(self._company)
return self._company.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def disk_usage(self) -> int:
self._completeIfNotSet(self._disk_usage)
return self._disk_usage.value
@property
def email(self) -> str:
self._completeIfNotSet(self._email)
return self._email.value
@property
def events_url(self) -> str:
self._completeIfNotSet(self._events_url)
return self._events_url.value
@property
def followers(self) -> int:
self._completeIfNotSet(self._followers)
return self._followers.value
@property
def followers_url(self) -> str:
self._completeIfNotSet(self._followers_url)
return self._followers_url.value
@property
def following(self) -> int:
self._completeIfNotSet(self._following)
return self._following.value
@property
def following_url(self) -> str:
self._completeIfNotSet(self._following_url)
return self._following_url.value
@property
def gists_url(self) -> str:
self._completeIfNotSet(self._gists_url)
return self._gists_url.value
@property
def gravatar_id(self) -> str:
self._completeIfNotSet(self._gravatar_id)
return self._gravatar_id.value
@property
def hireable(self) -> bool:
self._completeIfNotSet(self._hireable)
return self._hireable.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def location(self) -> str:
self._completeIfNotSet(self._location)
return self._location.value
@property
def login(self) -> str:
self._completeIfNotSet(self._login)
return self._login.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
@property
def organizations_url(self) -> str:
self._completeIfNotSet(self._organizations_url)
return self._organizations_url.value
@property
def owned_private_repos(self) -> int:
self._completeIfNotSet(self._owned_private_repos)
return self._owned_private_repos.value
@property
def plan(self) -> Plan:
self._completeIfNotSet(self._plan)
return self._plan.value
@property
def private_gists(self) -> int:
self._completeIfNotSet(self._private_gists)
return self._private_gists.value
@property
def public_gists(self) -> int:
self._completeIfNotSet(self._public_gists)
return self._public_gists.value
@property
def public_repos(self) -> int:
self._completeIfNotSet(self._public_repos)
return self._public_repos.value
@property
def received_events_url(self) -> str:
self._completeIfNotSet(self._received_events_url)
return self._received_events_url.value
@property
def repos_url(self) -> str:
self._completeIfNotSet(self._repos_url)
return self._repos_url.value
@property
def site_admin(self) -> bool:
self._completeIfNotSet(self._site_admin)
return self._site_admin.value
@property
def starred_url(self) -> str:
self._completeIfNotSet(self._starred_url)
return self._starred_url.value
@property
def subscriptions_url(self) -> str:
self._completeIfNotSet(self._subscriptions_url)
return self._subscriptions_url.value
@property
def total_private_repos(self) -> int:
self._completeIfNotSet(self._total_private_repos)
return self._total_private_repos.value
@property
def type(self) -> str:
self._completeIfNotSet(self._type)
return self._type.value
@property
def updated_at(self) -> datetime:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def two_factor_authentication(self) -> bool:
self._completeIfNotSet(self._two_factor_authentication)
return self._two_factor_authentication.value
def add_to_emails(self, *emails: str) -> None:
"""
:calls: `POST /user/emails <http://docs.github.com/en/rest/reference/users#emails>`_
"""
assert all(isinstance(element, str) for element in emails), emails
post_parameters = {"emails": emails}
headers, data = self._requester.requestJsonAndCheck("POST", "/user/emails", input=post_parameters)
def add_to_following(self, following: NamedUser) -> None:
"""
:calls: `PUT /user/following/{user} <http://docs.github.com/en/rest/reference/users#followers>`_
"""
assert isinstance(following, github.NamedUser.NamedUser), following
headers, data = self._requester.requestJsonAndCheck("PUT", f"/user/following/{following._identity}")
def add_to_starred(self, starred: Repository) -> None:
"""
:calls: `PUT /user/starred/{owner}/{repo} <http://docs.github.com/en/rest/reference/activity#starring>`_
"""
assert isinstance(starred, github.Repository.Repository), starred
headers, data = self._requester.requestJsonAndCheck("PUT", f"/user/starred/{starred._identity}")
def add_to_subscriptions(self, subscription: Repository) -> None:
"""
:calls: `PUT /user/subscriptions/{owner}/{repo} <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
assert isinstance(subscription, github.Repository.Repository), subscription
headers, data = self._requester.requestJsonAndCheck("PUT", f"/user/subscriptions/{subscription._identity}")
def add_to_watched(self, watched: Repository) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/subscription <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
assert isinstance(watched, github.Repository.Repository), watched
headers, data = self._requester.requestJsonAndCheck(
"PUT",
f"/repos/{watched._identity}/subscription",
input={"subscribed": True},
)
def create_authorization(
self,
scopes: Opt[list[str]] = NotSet,
note: Opt[str] = NotSet,
note_url: Opt[str] = NotSet,
client_id: Opt[str] = NotSet,
client_secret: Opt[str] = NotSet,
onetime_password: str | None = None,
) -> Authorization:
"""
:calls: `POST /authorizations <https://docs.github.com/en/developers/apps/authorizing-oauth-apps>`_
"""
assert is_optional_list(scopes, str), scopes
assert is_optional(note, str), note
assert is_optional(note_url, str), note_url
assert is_optional(client_id, str), client_id
assert is_optional(client_secret, str), client_secret
assert onetime_password is None or isinstance(onetime_password, str), onetime_password
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"scopes": scopes,
"note": note,
"note_url": note_url,
"client_id": client_id,
"client_secret": client_secret,
}
)
if onetime_password is not None:
request_header = {Consts.headerOTP: onetime_password} # pragma no cover (Should be covered)
else:
request_header = None
headers, data = self._requester.requestJsonAndCheck(
"POST",
"/authorizations",
input=post_parameters,
headers=request_header,
)
return github.Authorization.Authorization(self._requester, headers, data, completed=True)
@staticmethod
def create_fork(
repo: Repository,
name: Opt[str] = NotSet,
default_branch_only: Opt[bool] = NotSet,
) -> Repository:
"""
:calls: `POST /repos/{owner}/{repo}/forks <http://docs.github.com/en/rest/reference/repos#forks>`_
"""
assert isinstance(repo, github.Repository.Repository), repo
return repo.create_fork(
organization=github.GithubObject.NotSet,
name=name,
default_branch_only=default_branch_only,
)
def create_repo_from_template(
self,
name: str,
repo: Repository,
description: Opt[str] = NotSet,
include_all_branches: Opt[bool] = NotSet,
private: Opt[bool] = NotSet,
) -> Repository:
"""
:calls: `POST /repos/{template_owner}/{template_repo}/generate <https://docs.github.com/en/rest/reference/repos#create-a-repository-using-a-template>`_
"""
assert isinstance(name, str), name
assert isinstance(repo, github.Repository.Repository), repo
assert is_optional(description, str), description
assert is_optional(include_all_branches, bool), include_all_branches
assert is_optional(private, bool), private
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"name": name,
"owner": self.login,
"description": description,
"include_all_branches": include_all_branches,
"private": private,
}
)
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"/repos/{repo.owner.login}/{repo.name}/generate",
input=post_parameters,
headers={"Accept": "application/vnd.github.v3+json"},
)
return github.Repository.Repository(self._requester, headers, data, completed=True)
def create_gist(
self,
public: bool,
files: dict[str, InputFileContent],
description: Opt[str] = NotSet,
) -> Gist:
"""
:calls: `POST /gists <http://docs.github.com/en/rest/reference/gists>`_
"""
assert isinstance(public, bool), public
assert all(isinstance(element, github.InputFileContent) for element in files.values()), files
assert is_undefined(description) or isinstance(description, str), description
post_parameters = {
"public": public,
"files": {key: value._identity for key, value in files.items()},
}
if is_defined(description):
post_parameters["description"] = description
headers, data = self._requester.requestJsonAndCheck("POST", "/gists", input=post_parameters)
return github.Gist.Gist(self._requester, headers, data, completed=True)
def create_key(self, title: str, key: str) -> UserKey:
"""
:calls: `POST /user/keys <http://docs.github.com/en/rest/reference/users#git-ssh-keys>`_
:param title: string
:param key: string
:rtype: :class:`github.UserKey.UserKey`
"""
assert isinstance(title, str), title
assert isinstance(key, str), key
post_parameters = {
"title": title,
"key": key,
}
headers, data = self._requester.requestJsonAndCheck("POST", "/user/keys", input=post_parameters)
return github.UserKey.UserKey(self._requester, headers, data, completed=True)
def create_project(self, name: str, body: Opt[str] = NotSet) -> Project:
"""
:calls: `POST /user/projects <https://docs.github.com/en/rest/reference/projects#create-a-user-project>`_
:param name: string
:param body: string
:rtype: :class:`github.Project.Project`
"""
assert isinstance(name, str), name
assert is_undefined(body) or isinstance(body, str), body
post_parameters = {
"name": name,
"body": body,
}
headers, data = self._requester.requestJsonAndCheck(
"POST",
"/user/projects",
input=post_parameters,
headers={"Accept": Consts.mediaTypeProjectsPreview},
)
return github.Project.Project(self._requester, headers, data, completed=True)
def create_repo(
self,
name: str,
description: Opt[str] = NotSet,
homepage: Opt[str] = NotSet,
private: Opt[bool] = NotSet,
has_issues: Opt[bool] = NotSet,
has_wiki: Opt[bool] = NotSet,
has_downloads: Opt[bool] = NotSet,
has_projects: Opt[bool] = NotSet,
has_discussions: Opt[bool] = NotSet,
auto_init: Opt[bool] = NotSet,
license_template: Opt[str] = NotSet,
gitignore_template: Opt[str] = NotSet,
allow_squash_merge: Opt[bool] = NotSet,
allow_merge_commit: Opt[bool] = NotSet,
allow_rebase_merge: Opt[bool] = NotSet,
delete_branch_on_merge: Opt[bool] = NotSet,
) -> Repository:
"""
:calls: `POST /user/repos <http://docs.github.com/en/rest/reference/repos>`_
"""
assert isinstance(name, str), name
assert is_optional(description, str), description
assert is_optional(homepage, str), homepage
assert is_optional(private, bool), private
assert is_optional(has_issues, bool), has_issues
assert is_optional(has_wiki, bool), has_wiki
assert is_optional(has_downloads, bool), has_downloads
assert is_optional(has_projects, bool), has_projects
assert is_optional(has_discussions, bool), has_discussions
assert is_optional(auto_init, bool), auto_init
assert is_optional(license_template, str), license_template
assert is_optional(gitignore_template, str), gitignore_template
assert is_optional(allow_squash_merge, bool), allow_squash_merge
assert is_optional(allow_merge_commit, bool), allow_merge_commit
assert is_optional(allow_rebase_merge, bool), allow_rebase_merge
assert is_optional(delete_branch_on_merge, bool), delete_branch_on_merge
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"name": name,
"description": description,
"homepage": homepage,
"private": private,
"has_issues": has_issues,
"has_wiki": has_wiki,
"has_downloads": has_downloads,
"has_projects": has_projects,
"has_discussions": has_discussions,
"auto_init": auto_init,
"license_template": license_template,
"gitignore_template": gitignore_template,
"allow_squash_merge": allow_squash_merge,
"allow_merge_commit": allow_merge_commit,
"allow_rebase_merge": allow_rebase_merge,
"delete_branch_on_merge": delete_branch_on_merge,
}
)
headers, data = self._requester.requestJsonAndCheck("POST", "/user/repos", input=post_parameters)
return github.Repository.Repository(self._requester, headers, data, completed=True)
def edit(
self,
name: Opt[str] = NotSet,
email: Opt[str] = NotSet,
blog: Opt[str] = NotSet,
company: Opt[str] = NotSet,
location: Opt[str] = NotSet,
hireable: Opt[bool] = NotSet,
bio: Opt[str] = NotSet,
) -> None:
"""
:calls: `PATCH /user <http://docs.github.com/en/rest/reference/users>`_
"""
assert is_optional(name, str), name
assert is_optional(email, str), email
assert is_optional(blog, str), blog
assert is_optional(company, str), company
assert is_optional(location, str), location
assert is_optional(hireable, bool), hireable
assert is_optional(bio, str), bio
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"name": name,
"email": email,
"blog": blog,
"company": company,
"location": location,
"hireable": hireable,
"bio": bio,
}
)
headers, data = self._requester.requestJsonAndCheck("PATCH", "/user", input=post_parameters)
self._useAttributes(data)
def get_authorization(self, id: int) -> Authorization:
"""
:calls: `GET /authorizations/{id} <https://docs.github.com/en/developers/apps/authorizing-oauth-apps>`_
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"/authorizations/{id}")
return github.Authorization.Authorization(self._requester, headers, data, completed=True)
def get_authorizations(self) -> PaginatedList[Authorization]:
"""
:calls: `GET /authorizations <https://docs.github.com/en/developers/apps/authorizing-oauth-apps>`_
"""
return PaginatedList(github.Authorization.Authorization, self._requester, "/authorizations", None)
def get_emails(self) -> list[EmailData]:
"""
:calls: `GET /user/emails <http://docs.github.com/en/rest/reference/users#emails>`_
"""
headers, data = self._requester.requestJsonAndCheck("GET", "/user/emails")
return [EmailData(**item) for item in data]
def get_events(self) -> PaginatedList[Event]:
"""
:calls: `GET /events <http://docs.github.com/en/rest/reference/activity#events>`_
"""
return PaginatedList(github.Event.Event, self._requester, "/events", None)
def get_followers(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /user/followers <http://docs.github.com/en/rest/reference/users#followers>`_
"""
return PaginatedList(github.NamedUser.NamedUser, self._requester, "/user/followers", None)
def get_following(self) -> PaginatedList[NamedUser]:
"""
:calls: `GET /user/following <http://docs.github.com/en/rest/reference/users#followers>`_
"""
return PaginatedList(github.NamedUser.NamedUser, self._requester, "/user/following", None)
def get_gists(self, since: Opt[datetime] = NotSet) -> PaginatedList[Gist]:
"""
:calls: `GET /gists <http://docs.github.com/en/rest/reference/gists>`_
:param since: datetime format YYYY-MM-DDTHH:MM:SSZ
:rtype: :class:`PaginatedList` of :class:`github.Gist.Gist`
"""
assert is_optional(since, datetime), since
url_parameters: dict[str, Any] = {}
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(github.Gist.Gist, self._requester, "/gists", url_parameters)
def get_issues(
self,
filter: Opt[str] = NotSet,
state: Opt[str] = NotSet,
labels: Opt[list[Label]] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[Issue]:
"""
:calls: `GET /issues <http://docs.github.com/en/rest/reference/issues>`_
"""
assert is_optional(filter, str), filter
assert is_optional(state, str), state
assert is_optional_list(labels, github.Label.Label), labels
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(since, datetime), since
url_parameters: dict[str, Any] = {}
if is_defined(filter):
url_parameters["filter"] = filter
if is_defined(state):
url_parameters["state"] = state
if is_defined(labels):
url_parameters["labels"] = ",".join(label.name for label in labels)
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(github.Issue.Issue, self._requester, "/issues", url_parameters)
def get_user_issues(
self,
filter: Opt[str] = NotSet,
state: Opt[str] = NotSet,
labels: Opt[list[Label]] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[Issue]:
"""
:calls: `GET /user/issues <http://docs.github.com/en/rest/reference/issues>`_
"""
assert is_optional(filter, str), filter
assert is_optional(state, str), state
assert is_optional_list(labels, github.Label.Label), labels
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(since, datetime), since
url_parameters: dict[str, Any] = {}
if is_defined(filter):
url_parameters["filter"] = filter
if is_defined(state):
url_parameters["state"] = state
if is_defined(labels):
url_parameters["labels"] = ",".join(label.name for label in labels)
if is_defined(sort):
url_parameters["sort"] = sort
if is_defined(direction):
url_parameters["direction"] = direction
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(github.Issue.Issue, self._requester, "/user/issues", url_parameters)
def get_key(self, id: int) -> UserKey:
"""
:calls: `GET /user/keys/{id} <http://docs.github.com/en/rest/reference/users#git-ssh-keys>`_
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"/user/keys/{id}")
return github.UserKey.UserKey(self._requester, headers, data, completed=True)
def get_keys(self) -> PaginatedList[UserKey]:
"""
:calls: `GET /user/keys <http://docs.github.com/en/rest/reference/users#git-ssh-keys>`_
"""
return PaginatedList(github.UserKey.UserKey, self._requester, "/user/keys", None)
def get_notification(self, id: str) -> Notification:
"""
:calls: `GET /notifications/threads/{id} <http://docs.github.com/en/rest/reference/activity#notifications>`_
"""
assert isinstance(id, str), id
headers, data = self._requester.requestJsonAndCheck("GET", f"/notifications/threads/{id}")
return github.Notification.Notification(self._requester, headers, data, completed=True)
def get_notifications(
self,
all: Opt[bool] = NotSet,
participating: Opt[bool] = NotSet,
since: Opt[datetime] = NotSet,
before: Opt[datetime] = NotSet,
) -> PaginatedList[Notification]:
"""
:calls: `GET /notifications <http://docs.github.com/en/rest/reference/activity#notifications>`_
"""
assert is_optional(all, bool), all
assert is_optional(participating, bool), participating
assert is_optional(since, datetime), since
assert is_optional(before, datetime), before
params: dict[str, Any] = {}
if is_defined(all):
# convert True, False to true, false for api parameters
params["all"] = "true" if all else "false"
if is_defined(participating):
# convert True, False to true, false for api parameters
params["participating"] = "true" if participating else "false"
if is_defined(since):
params["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
if is_defined(before):
params["before"] = before.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(github.Notification.Notification, self._requester, "/notifications", params)
def get_organization_events(self, org: Organization) -> PaginatedList[Event]:
"""
:calls: `GET /users/{user}/events/orgs/{org} <http://docs.github.com/en/rest/reference/activity#events>`_
"""
assert isinstance(org, github.Organization.Organization), org
return PaginatedList(
github.Event.Event,
self._requester,
f"/users/{self.login}/events/orgs/{org.login}",
None,
)
def get_orgs(self) -> PaginatedList[Organization]:
"""
:calls: `GET /user/orgs <http://docs.github.com/en/rest/reference/orgs>`_
"""
return PaginatedList(github.Organization.Organization, self._requester, "/user/orgs", None)
def get_repo(self, name: str) -> Repository:
"""
:calls: `GET /repos/{owner}/{repo} <http://docs.github.com/en/rest/reference/repos>`_
"""
assert isinstance(name, str), name
name = urllib.parse.quote(name)
headers, data = self._requester.requestJsonAndCheck("GET", f"/repos/{self.login}/{name}")
return github.Repository.Repository(self._requester, headers, data, completed=True)
def get_repos(
self,
visibility: Opt[str] = NotSet,
affiliation: Opt[str] = NotSet,
type: Opt[str] = NotSet,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
) -> PaginatedList[Repository]:
"""
:calls: `GET /user/repos <http://docs.github.com/en/rest/reference/repos>`_
"""
assert is_optional(visibility, str), visibility
assert is_optional(affiliation, str), affiliation
assert is_optional(type, str), type
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
url_parameters = NotSet.remove_unset_items(
{
"visibility": visibility,
"affiliation": affiliation,
"type": type,
"sort": sort,
"direction": direction,
}
)
return PaginatedList(github.Repository.Repository, self._requester, "/user/repos", url_parameters)
def get_starred(self) -> PaginatedList[Repository]:
"""
:calls: `GET /user/starred <http://docs.github.com/en/rest/reference/activity#starring>`_
"""
return PaginatedList(github.Repository.Repository, self._requester, "/user/starred", None)
def get_starred_gists(self) -> PaginatedList[Gist]:
"""
:calls: `GET /gists/starred <http://docs.github.com/en/rest/reference/gists>`_
"""
return PaginatedList(github.Gist.Gist, self._requester, "/gists/starred", None)
def get_subscriptions(self) -> PaginatedList[Repository]:
"""
:calls: `GET /user/subscriptions <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
return PaginatedList(github.Repository.Repository, self._requester, "/user/subscriptions", None)
def get_teams(self) -> PaginatedList[Team]:
"""
:calls: `GET /user/teams <http://docs.github.com/en/rest/reference/teams>`_
"""
return PaginatedList(github.Team.Team, self._requester, "/user/teams", None)
def get_watched(self) -> PaginatedList[Repository]:
"""
:calls: `GET /user/subscriptions <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
return PaginatedList(github.Repository.Repository, self._requester, "/user/subscriptions", None)
def get_installations(self) -> PaginatedList[Installation]:
"""
:calls: `GET /user/installations <http://docs.github.com/en/rest/reference/apps>`_
"""
return PaginatedList(
github.Installation.Installation,
self._requester,
"/user/installations",
None,
headers={"Accept": Consts.mediaTypeIntegrationPreview},
list_item="installations",
)
def has_in_following(self, following: NamedUser) -> bool:
"""
:calls: `GET /user/following/{user} <http://docs.github.com/en/rest/reference/users#followers>`_
"""
assert isinstance(following, github.NamedUser.NamedUser), following
status, headers, data = self._requester.requestJson("GET", f"/user/following/{following._identity}")
return status == 204
def has_in_starred(self, starred: Repository) -> bool:
"""
:calls: `GET /user/starred/{owner}/{repo} <http://docs.github.com/en/rest/reference/activity#starring>`_
"""
assert isinstance(starred, github.Repository.Repository), starred
status, headers, data = self._requester.requestJson("GET", f"/user/starred/{starred._identity}")
return status == 204
def has_in_subscriptions(self, subscription: Repository) -> bool:
"""
:calls: `GET /user/subscriptions/{owner}/{repo} <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
assert isinstance(subscription, github.Repository.Repository), subscription
status, headers, data = self._requester.requestJson("GET", f"/user/subscriptions/{subscription._identity}")
return status == 204
def has_in_watched(self, watched: Repository) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/subscription <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
assert isinstance(watched, github.Repository.Repository), watched
status, headers, data = self._requester.requestJson("GET", f"/repos/{watched._identity}/subscription")
return status == 200
def mark_notifications_as_read(self, last_read_at: datetime | None = None) -> None:
"""
:calls: `PUT /notifications <https://docs.github.com/en/rest/reference/activity#notifications>`_
"""
if last_read_at is None:
last_read_at = datetime.now(timezone.utc)
assert isinstance(last_read_at, datetime)
put_parameters = {"last_read_at": last_read_at.strftime("%Y-%m-%dT%H:%M:%SZ")}
headers, data = self._requester.requestJsonAndCheck("PUT", "/notifications", input=put_parameters)
def remove_from_emails(self, *emails: str) -> None:
"""
:calls: `DELETE /user/emails <http://docs.github.com/en/rest/reference/users#emails>`_
"""
assert all(isinstance(element, str) for element in emails), emails
post_parameters = {"emails": emails}
headers, data = self._requester.requestJsonAndCheck("DELETE", "/user/emails", input=post_parameters)
def remove_from_following(self, following: NamedUser) -> None:
"""
:calls: `DELETE /user/following/{user} <http://docs.github.com/en/rest/reference/users#followers>`_
"""
assert isinstance(following, github.NamedUser.NamedUser), following
headers, data = self._requester.requestJsonAndCheck("DELETE", f"/user/following/{following._identity}")
def remove_from_starred(self, starred: Repository) -> None:
"""
:calls: `DELETE /user/starred/{owner}/{repo} <http://docs.github.com/en/rest/reference/activity#starring>`_
"""
assert isinstance(starred, github.Repository.Repository), starred
headers, data = self._requester.requestJsonAndCheck("DELETE", f"/user/starred/{starred._identity}")
def remove_from_subscriptions(self, subscription: Repository) -> None:
"""
:calls: `DELETE /user/subscriptions/{owner}/{repo} <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
assert isinstance(subscription, github.Repository.Repository), subscription
headers, data = self._requester.requestJsonAndCheck("DELETE", f"/user/subscriptions/{subscription._identity}")
def remove_from_watched(self, watched: Repository) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/subscription <http://docs.github.com/en/rest/reference/activity#watching>`_
"""
assert isinstance(watched, github.Repository.Repository), watched
headers, data = self._requester.requestJsonAndCheck("DELETE", f"/repos/{watched._identity}/subscription")
def accept_invitation(self, invitation: Invitation | int) -> None:
"""
:calls: `PATCH /user/repository_invitations/{invitation_id} <https://docs.github.com/en/rest/reference/repos/invitations#>`_
"""
assert isinstance(invitation, github.Invitation.Invitation) or isinstance(invitation, int)
if isinstance(invitation, github.Invitation.Invitation):
invitation = invitation.id
headers, data = self._requester.requestJsonAndCheck(
"PATCH", f"/user/repository_invitations/{invitation}", input={}
)
def get_invitations(self) -> PaginatedList[Invitation]:
"""
:calls: `GET /user/repository_invitations <https://docs.github.com/en/rest/reference/repos#invitations>`_
"""
return PaginatedList(
github.Invitation.Invitation,
self._requester,
"/user/repository_invitations",
None,
)
def create_migration(
self,
repos: list[Repository] | tuple[Repository],
lock_repositories: Opt[bool] = NotSet,
exclude_attachments: Opt[bool] = NotSet,
) -> Migration:
"""
:calls: `POST /user/migrations <https://docs.github.com/en/rest/reference/migrations>`_
"""
assert isinstance(repos, (list, tuple)), repos
assert all(isinstance(repo, str) for repo in repos), repos
assert is_optional(lock_repositories, bool), lock_repositories
assert is_optional(exclude_attachments, bool), exclude_attachments
post_parameters: dict[str, Any] = NotSet.remove_unset_items(
{
"repositories": repos,
"lock_repositories": lock_repositories,
"exclude_attachments": exclude_attachments,
}
)
headers, data = self._requester.requestJsonAndCheck(
"POST",
"/user/migrations",
input=post_parameters,
headers={"Accept": Consts.mediaTypeMigrationPreview},
)
return github.Migration.Migration(self._requester, headers, data, completed=True)
def get_migrations(self) -> PaginatedList[Migration]:
"""
:calls: `GET /user/migrations <https://docs.github.com/en/rest/reference/migrations>`_
"""
return PaginatedList(
github.Migration.Migration,
self._requester,
"/user/migrations",
None,
headers={"Accept": Consts.mediaTypeMigrationPreview},
)
def get_organization_membership(self, org: str) -> Membership:
"""
:calls: `GET /user/memberships/orgs/{org} <https://docs.github.com/en/rest/reference/orgs#get-an-organization-membership-for-the-authenticated-user>`_
"""
assert isinstance(org, str)
org = urllib.parse.quote(org)
headers, data = self._requester.requestJsonAndCheck("GET", f"/user/memberships/orgs/{org}")
return github.Membership.Membership(self._requester, headers, data, completed=True)
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "avatar_url" in attributes: # pragma no branch
self._avatar_url = self._makeStringAttribute(attributes["avatar_url"])
if "bio" in attributes: # pragma no branch
self._bio = self._makeStringAttribute(attributes["bio"])
if "blog" in attributes: # pragma no branch
self._blog = self._makeStringAttribute(attributes["blog"])
if "collaborators" in attributes: # pragma no branch
self._collaborators = self._makeIntAttribute(attributes["collaborators"])
if "company" in attributes: # pragma no branch
self._company = self._makeStringAttribute(attributes["company"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "disk_usage" in attributes: # pragma no branch
self._disk_usage = self._makeIntAttribute(attributes["disk_usage"])
if "email" in attributes: # pragma no branch
self._email = self._makeStringAttribute(attributes["email"])
if "events_url" in attributes: # pragma no branch
self._events_url = self._makeStringAttribute(attributes["events_url"])
if "followers" in attributes: # pragma no branch
self._followers = self._makeIntAttribute(attributes["followers"])
if "followers_url" in attributes: # pragma no branch
self._followers_url = self._makeStringAttribute(attributes["followers_url"])
if "following" in attributes: # pragma no branch
self._following = self._makeIntAttribute(attributes["following"])
if "following_url" in attributes: # pragma no branch
self._following_url = self._makeStringAttribute(attributes["following_url"])
if "gists_url" in attributes: # pragma no branch
self._gists_url = self._makeStringAttribute(attributes["gists_url"])
if "gravatar_id" in attributes: # pragma no branch
self._gravatar_id = self._makeStringAttribute(attributes["gravatar_id"])
if "hireable" in attributes: # pragma no branch
self._hireable = self._makeBoolAttribute(attributes["hireable"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "location" in attributes: # pragma no branch
self._location = self._makeStringAttribute(attributes["location"])
if "login" in attributes: # pragma no branch
self._login = self._makeStringAttribute(attributes["login"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
if "organizations_url" in attributes: # pragma no branch
self._organizations_url = self._makeStringAttribute(attributes["organizations_url"])
if "owned_private_repos" in attributes: # pragma no branch
self._owned_private_repos = self._makeIntAttribute(attributes["owned_private_repos"])
if "plan" in attributes: # pragma no branch
self._plan = self._makeClassAttribute(github.Plan.Plan, attributes["plan"])
if "private_gists" in attributes: # pragma no branch
self._private_gists = self._makeIntAttribute(attributes["private_gists"])
if "public_gists" in attributes: # pragma no branch
self._public_gists = self._makeIntAttribute(attributes["public_gists"])
if "public_repos" in attributes: # pragma no branch
self._public_repos = self._makeIntAttribute(attributes["public_repos"])
if "received_events_url" in attributes: # pragma no branch
self._received_events_url = self._makeStringAttribute(attributes["received_events_url"])
if "repos_url" in attributes: # pragma no branch
self._repos_url = self._makeStringAttribute(attributes["repos_url"])
if "site_admin" in attributes: # pragma no branch
self._site_admin = self._makeBoolAttribute(attributes["site_admin"])
if "starred_url" in attributes: # pragma no branch
self._starred_url = self._makeStringAttribute(attributes["starred_url"])
if "subscriptions_url" in attributes: # pragma no branch
self._subscriptions_url = self._makeStringAttribute(attributes["subscriptions_url"])
if "total_private_repos" in attributes: # pragma no branch
self._total_private_repos = self._makeIntAttribute(attributes["total_private_repos"])
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "two_factor_authentication" in attributes:
self._two_factor_authentication = self._makeBoolAttribute(attributes["two_factor_authentication"])
| 51,025
|
Python
|
.py
| 1,041
| 40.523535
| 159
| 0.623985
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,479
|
PullRequest.py
|
PyGithub_PyGithub/github/PullRequest.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Michael Stead <michael.stead@gmail.com> #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 @tmshn <tmshn@r.recruit.co.jp> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Aaron Levine <allevin@sandia.gov> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Ben Yohay <ben@lightricks.com> #
# Copyright 2018 Brian J. Murrell <brian@interlinx.bc.ca> #
# Copyright 2018 Gilad Shefer <gshefer@redhat.com> #
# Copyright 2018 Martin Monperrus <monperrus@users.noreply.github.com> #
# Copyright 2018 Matt Babineau <9685860+babineaum@users.noreply.github.com> #
# Copyright 2018 Shinichi TAMURA <shnch.tmr@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Thibault Jamet <tjamet@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 per1234 <accounts@perglass.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 MarcoFalke <falke.marco@gmail.com> #
# Copyright 2019 Mark Browning <mark@cerebras.net> #
# Copyright 2019 MurphyZhao <d2014zjt@163.com> #
# Copyright 2019 Olof-Joachim Frahm (欧雅福) <olof@macrolet.net> #
# Copyright 2019 Pavan Kunisetty <nagapavan@users.noreply.github.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Tim Gates <tim.gates@iress.com> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Alice GIRARD <bouhahah@gmail.com> #
# Copyright 2020 Florent Clarret <florent.clarret@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2022 tison <wander4096@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Heitor Polidoro <14806300+heitorpolidoro@users.noreply.github.com>#
# Copyright 2023 Heitor Polidoro <heitor.polidoro@gmail.com> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 sd-kialo <138505487+sd-kialo@users.noreply.github.com> #
# Copyright 2023 vanya20074 <vanya20074@gmail.com> #
# Copyright 2024 Austin Sasko <austintyler0239@yahoo.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Kobbi Gal <85439776+kgal-pan@users.noreply.github.com> #
# #
# 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 __future__ import annotations
import urllib.parse
from datetime import datetime
from typing import TYPE_CHECKING, Any
from typing_extensions import NotRequired, TypedDict
import github.Commit
import github.File
import github.IssueComment
import github.IssueEvent
import github.Label
import github.Milestone
import github.NamedUser
import github.PaginatedList
import github.PullRequestComment
import github.PullRequestMergeStatus
import github.PullRequestPart
import github.PullRequestReview
import github.Team
from github import Consts
from github.GithubObject import (
Attribute,
CompletableGithubObject,
NotSet,
Opt,
is_defined,
is_optional,
is_optional_list,
is_undefined,
)
from github.Issue import Issue
from github.PaginatedList import PaginatedList
if TYPE_CHECKING:
from github.GitRef import GitRef
from github.NamedUser import NamedUser
class ReviewComment(TypedDict):
path: str
position: NotRequired[int]
body: str
line: NotRequired[int]
side: NotRequired[str]
start_line: NotRequired[int]
start_side: NotRequired[str]
class PullRequest(CompletableGithubObject):
"""
This class represents PullRequests.
The reference can be found here
https://docs.github.com/en/rest/reference/pulls
"""
def _initAttributes(self) -> None:
self._additions: Attribute[int] = NotSet
self._assignee: Attribute[github.NamedUser.NamedUser] = NotSet
self._assignees: Attribute[list[NamedUser]] = NotSet
self._base: Attribute[github.PullRequestPart.PullRequestPart] = NotSet
self._body: Attribute[str] = NotSet
self._changed_files: Attribute[int] = NotSet
self._closed_at: Attribute[datetime | None] = NotSet
self._comments: Attribute[int] = NotSet
self._comments_url: Attribute[str] = NotSet
self._commits: Attribute[int] = NotSet
self._commits_url: Attribute[str] = NotSet
self._created_at: Attribute[datetime] = NotSet
self._deletions: Attribute[int] = NotSet
self._diff_url: Attribute[str] = NotSet
self._draft: Attribute[bool] = NotSet
self._head: Attribute[github.PullRequestPart.PullRequestPart] = NotSet
self._html_url: Attribute[str] = NotSet
self._id: Attribute[int] = NotSet
self._issue_url: Attribute[str] = NotSet
self._labels: Attribute[list[github.Label.Label]] = NotSet
self._merge_commit_sha: Attribute[str] = NotSet
self._mergeable: Attribute[bool] = NotSet
self._mergeable_state: Attribute[str] = NotSet
self._merged: Attribute[bool] = NotSet
self._merged_at: Attribute[datetime | None] = NotSet
self._merged_by: Attribute[github.NamedUser.NamedUser] = NotSet
self._milestone: Attribute[github.Milestone.Milestone] = NotSet
self._number: Attribute[int] = NotSet
self._patch_url: Attribute[str] = NotSet
self._rebaseable: Attribute[bool] = NotSet
self._requested_reviewers: Attribute[list[NamedUser]] = NotSet
self._review_comment_url: Attribute[str] = NotSet
self._review_comments: Attribute[int] = NotSet
self._review_comments_url: Attribute[str] = NotSet
self._state: Attribute[str] = NotSet
self._title: Attribute[str] = NotSet
self._updated_at: Attribute[datetime | None] = NotSet
self._url: Attribute[str] = NotSet
self._user: Attribute[github.NamedUser.NamedUser] = NotSet
self._maintainer_can_modify: Attribute[bool] = NotSet
self._node_id: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"number": self._number.value, "title": self._title.value})
@property
def additions(self) -> int:
self._completeIfNotSet(self._additions)
return self._additions.value
@property
def assignee(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._assignee)
return self._assignee.value
@property
def assignees(self) -> list[github.NamedUser.NamedUser]:
self._completeIfNotSet(self._assignees)
return self._assignees.value
@property
def base(self) -> github.PullRequestPart.PullRequestPart:
self._completeIfNotSet(self._base)
return self._base.value
@property
def body(self) -> str:
self._completeIfNotSet(self._body)
return self._body.value
@property
def changed_files(self) -> int:
self._completeIfNotSet(self._changed_files)
return self._changed_files.value
@property
def closed_at(self) -> datetime | None:
self._completeIfNotSet(self._closed_at)
return self._closed_at.value
@property
def comments(self) -> int:
self._completeIfNotSet(self._comments)
return self._comments.value
@property
def comments_url(self) -> str:
self._completeIfNotSet(self._comments_url)
return self._comments_url.value
@property
def commits(self) -> int:
self._completeIfNotSet(self._commits)
return self._commits.value
@property
def commits_url(self) -> str:
self._completeIfNotSet(self._commits_url)
return self._commits_url.value
@property
def created_at(self) -> datetime:
self._completeIfNotSet(self._created_at)
return self._created_at.value
@property
def deletions(self) -> int:
self._completeIfNotSet(self._deletions)
return self._deletions.value
@property
def diff_url(self) -> str:
self._completeIfNotSet(self._diff_url)
return self._diff_url.value
@property
def draft(self) -> bool:
self._completeIfNotSet(self._draft)
return self._draft.value
@property
def head(self) -> github.PullRequestPart.PullRequestPart:
self._completeIfNotSet(self._head)
return self._head.value
@property
def html_url(self) -> str:
self._completeIfNotSet(self._html_url)
return self._html_url.value
@property
def id(self) -> int:
self._completeIfNotSet(self._id)
return self._id.value
@property
def issue_url(self) -> str:
self._completeIfNotSet(self._issue_url)
return self._issue_url.value
@property
def labels(self) -> list[github.Label.Label]:
self._completeIfNotSet(self._labels)
return self._labels.value
@property
def merge_commit_sha(self) -> str:
self._completeIfNotSet(self._merge_commit_sha)
return self._merge_commit_sha.value
@property
def mergeable(self) -> bool:
self._completeIfNotSet(self._mergeable)
return self._mergeable.value
@property
def mergeable_state(self) -> str:
self._completeIfNotSet(self._mergeable_state)
return self._mergeable_state.value
@property
def merged(self) -> bool:
self._completeIfNotSet(self._merged)
return self._merged.value
@property
def merged_at(self) -> datetime | None:
self._completeIfNotSet(self._merged_at)
return self._merged_at.value
@property
def merged_by(self) -> github.NamedUser.NamedUser:
self._completeIfNotSet(self._merged_by)
return self._merged_by.value
@property
def milestone(self) -> github.Milestone.Milestone:
self._completeIfNotSet(self._milestone)
return self._milestone.value
@property
def number(self) -> int:
self._completeIfNotSet(self._number)
return self._number.value
@property
def patch_url(self) -> str:
self._completeIfNotSet(self._patch_url)
return self._patch_url.value
@property
def rebaseable(self) -> bool:
self._completeIfNotSet(self._rebaseable)
return self._rebaseable.value
@property
def review_comment_url(self) -> str:
self._completeIfNotSet(self._review_comment_url)
return self._review_comment_url.value
@property
def review_comments(self) -> int:
self._completeIfNotSet(self._review_comments)
return self._review_comments.value
@property
def review_comments_url(self) -> str:
self._completeIfNotSet(self._review_comments_url)
return self._review_comments_url.value
@property
def state(self) -> str:
self._completeIfNotSet(self._state)
return self._state.value
@property
def title(self) -> str:
self._completeIfNotSet(self._title)
return self._title.value
@property
def updated_at(self) -> datetime | None:
self._completeIfNotSet(self._updated_at)
return self._updated_at.value
@property
def requested_reviewers(self) -> list[github.NamedUser.NamedUser]:
self._completeIfNotSet(self._requested_reviewers)
return self._requested_reviewers.value
@property
def requested_teams(self) -> list[github.Team.Team]:
self._completeIfNotSet(self._requested_teams)
return self._requested_teams.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def user(self) -> NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
@property
def maintainer_can_modify(self) -> bool:
self._completeIfNotSet(self._maintainer_can_modify)
return self._maintainer_can_modify.value
@property
def node_id(self) -> str:
self._completeIfNotSet(self._node_id)
return self._node_id.value
def as_issue(self) -> Issue:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number} <https://docs.github.com/en/rest/reference/issues>`_
"""
headers, data = self._requester.requestJsonAndCheck("GET", self.issue_url)
return github.Issue.Issue(self._requester, headers, data, completed=True)
def create_comment(
self, body: str, commit: github.Commit.Commit, path: str, position: int
) -> github.PullRequestComment.PullRequestComment:
"""
:calls: `POST /repos/{owner}/{repo}/pulls/{number}/comments <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
"""
return self.create_review_comment(body, commit, path, position)
def create_review_comment(
self,
body: str,
commit: github.Commit.Commit,
path: str,
# line replaces deprecated position argument, so we put it between path and side
line: Opt[int] = NotSet,
side: Opt[str] = NotSet,
start_line: Opt[int] = NotSet,
start_side: Opt[int] = NotSet,
in_reply_to: Opt[int] = NotSet,
subject_type: Opt[str] = NotSet,
as_suggestion: bool = False,
) -> github.PullRequestComment.PullRequestComment:
"""
:calls: `POST /repos/{owner}/{repo}/pulls/{number}/comments <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
"""
assert isinstance(body, str), body
assert isinstance(commit, github.Commit.Commit), commit
assert isinstance(path, str), path
assert is_optional(line, int), line
assert is_undefined(side) or side in ["LEFT", "RIGHT"], side
assert is_optional(start_line, int), start_line
assert is_undefined(start_side) or start_side in [
"LEFT",
"RIGHT",
"side",
], start_side
assert is_optional(in_reply_to, int), in_reply_to
assert is_undefined(subject_type) or subject_type in [
"line",
"file",
], subject_type
assert isinstance(as_suggestion, bool), as_suggestion
if as_suggestion:
body = f"```suggestion\n{body}\n```"
post_parameters = NotSet.remove_unset_items(
{
"body": body,
"commit_id": commit._identity,
"path": path,
"line": line,
"side": side,
"start_line": start_line,
"start_side": start_side,
"in_reply_to": in_reply_to,
"subject_type": subject_type,
}
)
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/comments", input=post_parameters)
return github.PullRequestComment.PullRequestComment(self._requester, headers, data, completed=True)
def create_review_comment_reply(self, comment_id: int, body: str) -> github.PullRequestComment.PullRequestComment:
"""
:calls: `POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
"""
assert isinstance(comment_id, int), comment_id
assert isinstance(body, str), body
post_parameters = {"body": body}
headers, data = self._requester.requestJsonAndCheck(
"POST",
f"{self.url}/comments/{comment_id}/replies",
input=post_parameters,
)
return github.PullRequestComment.PullRequestComment(self._requester, headers, data, completed=True)
def create_issue_comment(self, body: str) -> github.IssueComment.IssueComment:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/comments <https://docs.github.com/en/rest/reference/issues#comments>`_
"""
assert isinstance(body, str), body
post_parameters = {
"body": body,
}
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.issue_url}/comments", input=post_parameters)
return github.IssueComment.IssueComment(self._requester, headers, data, completed=True)
def create_review(
self,
commit: Opt[github.Commit.Commit] = NotSet,
body: Opt[str] = NotSet,
event: Opt[str] = NotSet,
comments: Opt[list[ReviewComment]] = NotSet,
) -> github.PullRequestReview.PullRequestReview:
"""
:calls: `POST /repos/{owner}/{repo}/pulls/{number}/reviews <https://docs.github.com/en/free-pro-team@latest/rest/pulls/reviews?apiVersion=2022-11-28#create-a-review-for-a-pull-request>`_
"""
assert is_optional(commit, github.Commit.Commit), commit
assert is_optional(body, str), body
assert is_optional(event, str), event
assert is_optional_list(comments, dict), comments
post_parameters: dict[str, Any] = NotSet.remove_unset_items({"body": body})
post_parameters["event"] = "COMMENT" if is_undefined(event) else event
if is_defined(commit):
post_parameters["commit_id"] = commit.sha
if is_defined(comments):
post_parameters["comments"] = comments
else:
post_parameters["comments"] = []
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.url}/reviews", input=post_parameters)
return github.PullRequestReview.PullRequestReview(self._requester, headers, data, completed=True)
def create_review_request(
self,
reviewers: Opt[list[str] | str] = NotSet,
team_reviewers: Opt[list[str] | str] = NotSet,
) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/pulls/{number}/requested_reviewers <https://docs.github.com/en/rest/reference/pulls#review-requests>`_
"""
assert is_optional(reviewers, str) or is_optional_list(reviewers, str), reviewers
assert is_optional(team_reviewers, str) or is_optional_list(team_reviewers, str), team_reviewers
post_parameters = NotSet.remove_unset_items({"reviewers": reviewers, "team_reviewers": team_reviewers})
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.url}/requested_reviewers", input=post_parameters
)
def delete_review_request(
self,
reviewers: Opt[list[str] | str] = NotSet,
team_reviewers: Opt[list[str] | str] = NotSet,
) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/pulls/{number}/requested_reviewers <https://docs.github.com/en/rest/reference/pulls#review-requests>`_
"""
assert is_optional(reviewers, str) or is_optional_list(reviewers, str), reviewers
assert is_optional(team_reviewers, str) or is_optional_list(team_reviewers, str), team_reviewers
post_parameters = NotSet.remove_unset_items({"reviewers": reviewers, "team_reviewers": team_reviewers})
headers, data = self._requester.requestJsonAndCheck(
"DELETE", f"{self.url}/requested_reviewers", input=post_parameters
)
def edit(
self,
title: Opt[str] = NotSet,
body: Opt[str] = NotSet,
state: Opt[str] = NotSet,
base: Opt[str] = NotSet,
maintainer_can_modify: Opt[bool] = NotSet,
) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/pulls/{number} <https://docs.github.com/en/rest/reference/pulls>`_
"""
assert is_optional(title, str), title
assert is_optional(body, str), body
assert is_optional(state, str), state
assert is_optional(base, str), base
assert is_optional(maintainer_can_modify, bool), maintainer_can_modify
post_parameters = NotSet.remove_unset_items(
{"title": title, "body": body, "state": state, "base": base, "maintainer_can_modify": maintainer_can_modify}
)
headers, data = self._requester.requestJsonAndCheck("PATCH", self.url, input=post_parameters)
self._useAttributes(data)
def get_comment(self, id: int) -> github.PullRequestComment.PullRequestComment:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/comments/{number} <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
"""
return self.get_review_comment(id)
def get_review_comment(self, id: int) -> github.PullRequestComment.PullRequestComment:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/comments/{number} <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self._parentUrl(self.url)}/comments/{id}")
return github.PullRequestComment.PullRequestComment(self._requester, headers, data, completed=True)
def get_comments(
self,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[github.PullRequestComment.PullRequestComment]:
"""
Warning: this only returns review comments. For normal conversation comments, use get_issue_comments.
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/comments <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
:param sort: string 'created' or 'updated'
:param direction: string 'asc' or 'desc'
:param since: datetime
"""
return self.get_review_comments(sort=sort, direction=direction, since=since)
# v3: remove *, added here to force named parameters because order has changed
def get_review_comments(
self,
*,
sort: Opt[str] = NotSet,
direction: Opt[str] = NotSet,
since: Opt[datetime] = NotSet,
) -> PaginatedList[github.PullRequestComment.PullRequestComment]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/comments <https://docs.github.com/en/rest/reference/pulls#review-comments>`_
:param sort: string 'created' or 'updated'
:param direction: string 'asc' or 'desc'
:param since: datetime
"""
assert is_optional(sort, str), sort
assert is_optional(direction, str), direction
assert is_optional(since, datetime), since
url_parameters = NotSet.remove_unset_items({"sort": sort, "direction": direction})
if is_defined(since):
url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
return PaginatedList(
github.PullRequestComment.PullRequestComment,
self._requester,
f"{self.url}/comments",
url_parameters,
)
def get_single_review_comments(self, id: int) -> PaginatedList[github.PullRequestComment.PullRequestComment]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/review/{id}/comments <https://docs.github.com/en/rest/reference/pulls#reviews>`_
"""
assert isinstance(id, int), id
return PaginatedList(
github.PullRequestComment.PullRequestComment,
self._requester,
f"{self.url}/reviews/{id}/comments",
None,
)
def get_commits(self) -> PaginatedList[github.Commit.Commit]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/commits <https://docs.github.com/en/rest/reference/pulls>`_
"""
return PaginatedList(github.Commit.Commit, self._requester, f"{self.url}/commits", None)
def get_files(self) -> PaginatedList[github.File.File]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/files <https://docs.github.com/en/rest/reference/pulls>`_
"""
return PaginatedList(github.File.File, self._requester, f"{self.url}/files", None)
def get_issue_comment(self, id: int) -> github.IssueComment.IssueComment:
"""
:calls: `GET /repos/{owner}/{repo}/issues/comments/{id} <https://docs.github.com/en/rest/reference/issues#comments>`_
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck("GET", f"{self._parentUrl(self.issue_url)}/comments/{id}")
return github.IssueComment.IssueComment(self._requester, headers, data, completed=True)
def get_issue_comments(self) -> PaginatedList[github.IssueComment.IssueComment]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number}/comments <https://docs.github.com/en/rest/reference/issues#comments>`_
"""
return PaginatedList(
github.IssueComment.IssueComment,
self._requester,
f"{self.issue_url}/comments",
None,
)
def get_issue_events(self) -> PaginatedList[github.IssueEvent.IssueEvent]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{issue_number}/events <https://docs.github.com/en/rest/reference/issues#events>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueEvent.IssueEvent`
"""
return PaginatedList(
github.IssueEvent.IssueEvent,
self._requester,
f"{self.issue_url}/events",
None,
headers={"Accept": Consts.mediaTypeLockReasonPreview},
)
def get_review(self, id: int) -> github.PullRequestReview.PullRequestReview:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/reviews/{id} <https://docs.github.com/en/rest/reference/pulls#reviews>`_
:param id: integer
:rtype: :class:`github.PullRequestReview.PullRequestReview`
"""
assert isinstance(id, int), id
headers, data = self._requester.requestJsonAndCheck(
"GET",
f"{self.url}/reviews/{id}",
)
return github.PullRequestReview.PullRequestReview(self._requester, headers, data, completed=True)
def get_reviews(self) -> PaginatedList[github.PullRequestReview.PullRequestReview]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/reviews <https://docs.github.com/en/rest/reference/pulls#reviews>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.PullRequestReview.PullRequestReview`
"""
return PaginatedList(
github.PullRequestReview.PullRequestReview,
self._requester,
f"{self.url}/reviews",
None,
)
def get_review_requests(self) -> tuple[PaginatedList[NamedUser], PaginatedList[github.Team.Team]]:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/requested_reviewers <https://docs.github.com/en/rest/reference/pulls#review-requests>`_
:rtype: tuple of :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` and of :class:`github.PaginatedList.PaginatedList` of :class:`github.Team.Team`
"""
return (
PaginatedList(
github.NamedUser.NamedUser,
self._requester,
f"{self.url}/requested_reviewers",
None,
list_item="users",
),
PaginatedList(
github.Team.Team,
self._requester,
f"{self.url}/requested_reviewers",
None,
list_item="teams",
),
)
def get_labels(self) -> PaginatedList[github.Label.Label]:
"""
:calls: `GET /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
return PaginatedList(github.Label.Label, self._requester, f"{self.issue_url}/labels", None)
def add_to_labels(self, *labels: github.Label.Label | str) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels
post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels]
headers, data = self._requester.requestJsonAndCheck("POST", f"{self.issue_url}/labels", input=post_parameters)
def delete_labels(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.issue_url}/labels")
def remove_from_labels(self, label: github.Label.Label | str) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{number}/labels/{name} <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert isinstance(label, (github.Label.Label, str)), label
if isinstance(label, github.Label.Label):
label = label._identity
else:
label = urllib.parse.quote(label)
headers, data = self._requester.requestJsonAndCheck("DELETE", f"{self.issue_url}/labels/{label}")
def set_labels(self, *labels: github.Label.Label | str) -> None:
"""
:calls: `PUT /repos/{owner}/{repo}/issues/{number}/labels <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert all(isinstance(element, (github.Label.Label, str)) for element in labels), labels
post_parameters = [label.name if isinstance(label, github.Label.Label) else label for label in labels]
headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.issue_url}/labels", input=post_parameters)
def is_merged(self) -> bool:
"""
:calls: `GET /repos/{owner}/{repo}/pulls/{number}/merge <https://docs.github.com/en/rest/reference/pulls>`_
"""
status, headers, data = self._requester.requestJson("GET", f"{self.url}/merge")
return status == 204
def restore_branch(self) -> GitRef:
"""
Convenience function that calls :meth:`Repository.create_git_ref` :rtype: :class:`github.GitRef.GitRef`
"""
return self.head.repo.create_git_ref(f"refs/heads/{self.head.ref}", sha=self.head.sha)
def delete_branch(self, force: bool = False) -> None:
"""
Convenience function that calls :meth:`GitRef.delete` :rtype: bool.
"""
if not force:
remaining_pulls = self.head.repo.get_pulls(head=self.head.ref)
if remaining_pulls.totalCount > 0:
raise RuntimeError(
"This branch is referenced by open pull requests, set force=True to delete this branch."
)
return self.head.repo.get_git_ref(f"heads/{self.head.ref}").delete()
def enable_automerge(
self,
merge_method: Opt[str] = "MERGE",
author_email: Opt[str] = NotSet,
client_mutation_id: Opt[str] = NotSet,
commit_body: Opt[str] = NotSet,
commit_headline: Opt[str] = NotSet,
expected_head_oid: Opt[str] = NotSet,
) -> dict[str, Any]:
"""
:calls: `POST /graphql <https://docs.github.com/en/graphql>`_ with a mutation to enable pull request auto merge
<https://docs.github.com/en/graphql/reference/mutations#enablepullrequestautomerge>
"""
assert is_optional(author_email, str), author_email
assert is_optional(client_mutation_id, str), client_mutation_id
assert is_optional(commit_body, str), commit_body
assert is_optional(commit_headline, str), commit_headline
assert is_optional(expected_head_oid, str), expected_head_oid
assert isinstance(merge_method, str) and merge_method in ["MERGE", "REBASE", "SQUASH"], merge_method
# Define the variables
variables = {
"pullRequestId": self.node_id,
"authorEmail": author_email,
"clientMutationId": client_mutation_id,
"commitBody": commit_body,
"commitHeadline": commit_headline,
"expectedHeadOid": expected_head_oid,
"mergeMethod": merge_method,
}
# Make the request
_, data = self._requester.graphql_named_mutation(
mutation_name="enable_pull_request_auto_merge",
variables={"input": NotSet.remove_unset_items(variables)},
output="actor { avatarUrl login resourcePath url } clientMutationId",
)
return data
def disable_automerge(
self,
client_mutation_id: Opt[str] = NotSet,
) -> dict[str, Any]:
"""
:calls: `POST /graphql <https://docs.github.com/en/graphql>`_ with a mutation to disable pull request auto merge
<https://docs.github.com/en/graphql/reference/mutations#disablepullrequestautomerge>
"""
assert is_optional(client_mutation_id, str), client_mutation_id
# Define the variables
variables = {
"pullRequestId": self.node_id,
"clientMutationId": client_mutation_id,
}
# Make the request
_, data = self._requester.graphql_named_mutation(
mutation_name="disable_pull_request_auto_merge",
variables={"input": NotSet.remove_unset_items(variables)},
output="actor { avatarUrl login resourcePath url } clientMutationId",
)
return data
def merge(
self,
commit_message: Opt[str] = NotSet,
commit_title: Opt[str] = NotSet,
merge_method: Opt[str] = NotSet,
sha: Opt[str] = NotSet,
delete_branch: bool = False,
) -> github.PullRequestMergeStatus.PullRequestMergeStatus:
"""
:calls: `PUT /repos/{owner}/{repo}/pulls/{number}/merge <https://docs.github.com/en/rest/reference/pulls>`_
"""
assert is_optional(commit_message, str), commit_message
assert is_optional(commit_title, str), commit_title
assert is_optional(merge_method, str), merge_method
assert is_optional(sha, str), sha
post_parameters = NotSet.remove_unset_items(
{"commit_message": commit_message, "commit_title": commit_title, "merge_method": merge_method, "sha": sha}
)
headers, data = self._requester.requestJsonAndCheck("PUT", f"{self.url}/merge", input=post_parameters)
if delete_branch:
self.delete_branch()
return github.PullRequestMergeStatus.PullRequestMergeStatus(self._requester, headers, data, completed=True)
def add_to_assignees(self, *assignees: github.NamedUser.NamedUser | str) -> None:
"""
:calls: `POST /repos/{owner}/{repo}/issues/{number}/assignees <https://docs.github.com/en/rest/issues/assignees?apiVersion=2022-11-28#add-assignees-to-an-issue>`_
"""
assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees
post_parameters = {
"assignees": [
assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee
for assignee in assignees
]
}
headers, data = self._requester.requestJsonAndCheck(
"POST", f"{self.issue_url}/assignees", input=post_parameters
)
# Only use the assignees attribute, since we call this PR as an issue
self._useAttributes({"assignees": data["assignees"]})
def remove_from_assignees(self, *assignees: github.NamedUser.NamedUser | str) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/issues/{number}/assignees <https://docs.github.com/en/rest/reference/issues#assignees>`_
"""
assert all(isinstance(element, (github.NamedUser.NamedUser, str)) for element in assignees), assignees
post_parameters = {
"assignees": [
assignee.login if isinstance(assignee, github.NamedUser.NamedUser) else assignee
for assignee in assignees
]
}
headers, data = self._requester.requestJsonAndCheck(
"DELETE", f"{self.issue_url}/assignees", input=post_parameters
)
# Only use the assignees attribute, since we call this PR as an issue
self._useAttributes({"assignees": data["assignees"]})
def update_branch(self, expected_head_sha: Opt[str] = NotSet) -> bool:
"""
:calls `PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch <https://docs.github.com/en/rest/reference/pulls>`_
"""
assert is_optional(expected_head_sha, str), expected_head_sha
post_parameters = NotSet.remove_unset_items({"expected_head_sha": expected_head_sha})
status, headers, data = self._requester.requestJson(
"PUT",
f"{self.url}/update-branch",
input=post_parameters,
headers={"Accept": Consts.updateBranchPreview},
)
return status == 202
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "additions" in attributes: # pragma no branch
self._additions = self._makeIntAttribute(attributes["additions"])
if "assignee" in attributes: # pragma no branch
self._assignee = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["assignee"])
if "assignees" in attributes: # pragma no branch
self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, attributes["assignees"])
elif "assignee" in attributes:
if attributes["assignee"] is not None:
self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, [attributes["assignee"]])
else:
self._assignees = self._makeListOfClassesAttribute(github.NamedUser.NamedUser, [])
if "base" in attributes: # pragma no branch
self._base = self._makeClassAttribute(github.PullRequestPart.PullRequestPart, attributes["base"])
if "body" in attributes: # pragma no branch
self._body = self._makeStringAttribute(attributes["body"])
if "changed_files" in attributes: # pragma no branch
self._changed_files = self._makeIntAttribute(attributes["changed_files"])
if "closed_at" in attributes: # pragma no branch
self._closed_at = self._makeDatetimeAttribute(attributes["closed_at"])
if "comments" in attributes: # pragma no branch
self._comments = self._makeIntAttribute(attributes["comments"])
if "comments_url" in attributes: # pragma no branch
self._comments_url = self._makeStringAttribute(attributes["comments_url"])
if "commits" in attributes: # pragma no branch
self._commits = self._makeIntAttribute(attributes["commits"])
if "commits_url" in attributes: # pragma no branch
self._commits_url = self._makeStringAttribute(attributes["commits_url"])
if "created_at" in attributes: # pragma no branch
self._created_at = self._makeDatetimeAttribute(attributes["created_at"])
if "deletions" in attributes: # pragma no branch
self._deletions = self._makeIntAttribute(attributes["deletions"])
if "diff_url" in attributes: # pragma no branch
self._diff_url = self._makeStringAttribute(attributes["diff_url"])
if "draft" in attributes: # pragma no branch
self._draft = self._makeBoolAttribute(attributes["draft"])
if "head" in attributes: # pragma no branch
self._head = self._makeClassAttribute(github.PullRequestPart.PullRequestPart, attributes["head"])
if "html_url" in attributes: # pragma no branch
self._html_url = self._makeStringAttribute(attributes["html_url"])
if "id" in attributes: # pragma no branch
self._id = self._makeIntAttribute(attributes["id"])
if "issue_url" in attributes: # pragma no branch
self._issue_url = self._makeStringAttribute(attributes["issue_url"])
if "labels" in attributes: # pragma no branch
self._labels = self._makeListOfClassesAttribute(github.Label.Label, attributes["labels"])
if "maintainer_can_modify" in attributes: # pragma no branch
self._maintainer_can_modify = self._makeBoolAttribute(attributes["maintainer_can_modify"])
if "merge_commit_sha" in attributes: # pragma no branch
self._merge_commit_sha = self._makeStringAttribute(attributes["merge_commit_sha"])
if "mergeable" in attributes: # pragma no branch
self._mergeable = self._makeBoolAttribute(attributes["mergeable"])
if "mergeable_state" in attributes: # pragma no branch
self._mergeable_state = self._makeStringAttribute(attributes["mergeable_state"])
if "merged" in attributes: # pragma no branch
self._merged = self._makeBoolAttribute(attributes["merged"])
if "merged_at" in attributes: # pragma no branch
self._merged_at = self._makeDatetimeAttribute(attributes["merged_at"])
if "merged_by" in attributes: # pragma no branch
self._merged_by = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["merged_by"])
if "milestone" in attributes: # pragma no branch
self._milestone = self._makeClassAttribute(github.Milestone.Milestone, attributes["milestone"])
if "number" in attributes: # pragma no branch
self._number = self._makeIntAttribute(attributes["number"])
if "patch_url" in attributes: # pragma no branch
self._patch_url = self._makeStringAttribute(attributes["patch_url"])
if "rebaseable" in attributes: # pragma no branch
self._rebaseable = self._makeBoolAttribute(attributes["rebaseable"])
if "review_comment_url" in attributes: # pragma no branch
self._review_comment_url = self._makeStringAttribute(attributes["review_comment_url"])
if "review_comments" in attributes: # pragma no branch
self._review_comments = self._makeIntAttribute(attributes["review_comments"])
if "review_comments_url" in attributes: # pragma no branch
self._review_comments_url = self._makeStringAttribute(attributes["review_comments_url"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "title" in attributes: # pragma no branch
self._title = self._makeStringAttribute(attributes["title"])
if "updated_at" in attributes: # pragma no branch
self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
if "requested_reviewers" in attributes:
self._requested_reviewers = self._makeListOfClassesAttribute(
github.NamedUser.NamedUser, attributes["requested_reviewers"]
)
if "requested_teams" in attributes:
self._requested_teams = self._makeListOfClassesAttribute(github.Team.Team, attributes["requested_teams"])
if "node_id" in attributes: # pragma no branch
self._node_id = self._makeStringAttribute(attributes["node_id"])
| 46,492
|
Python
|
.py
| 906
| 42.915011
| 194
| 0.629846
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,480
|
AdvisoryVulnerabilityPackage.py
|
PyGithub_PyGithub/github/AdvisoryVulnerabilityPackage.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2022 Eric Nieuwland <eric.nieuwland@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh <jonathan.leitschuh@gmail.com> #
# Copyright 2023 Joseph Henrich <crimsonknave@gmail.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper <coopernetes@proton.me> #
# #
# 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 __future__ import annotations
from typing import Any
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class AdvisoryVulnerabilityPackage(NonCompletableGithubObject):
"""
This class represents an identifier for a package that is vulnerable to a parent SecurityAdvisory.
The reference can be found here
https://docs.github.com/en/rest/security-advisories/repository-advisories
"""
def _initAttributes(self) -> None:
self._ecosystem: Attribute[str] = NotSet
self._name: Attribute[str | None] = NotSet
@property
def ecosystem(self) -> str:
"""
:type: string
"""
return self._ecosystem.value
@property
def name(self) -> str | None:
"""
:type: string or None
"""
return self._name.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "ecosystem" in attributes: # pragma no branch
self._ecosystem = self._makeStringAttribute(attributes["ecosystem"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
| 4,577
|
Python
|
.py
| 71
| 61
| 102
| 0.515239
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,481
|
EnvironmentProtectionRuleReviewer.py
|
PyGithub_PyGithub/github/EnvironmentProtectionRuleReviewer.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Nick Campbell <nicholas.j.campbell@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2023 alson <git@alm.nufan.net> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import Any
import github.NamedUser
import github.Team
from github.GithubObject import Attribute, NonCompletableGithubObject, NotSet
class EnvironmentProtectionRuleReviewer(NonCompletableGithubObject):
"""
This class represents a reviewer for an EnvironmentProtectionRule.
The reference can be found here
https://docs.github.com/en/rest/reference/deployments#environments
"""
def _initAttributes(self) -> None:
self._type: Attribute[str] = NotSet
self._reviewer: Attribute[github.NamedUser.NamedUser | github.Team.Team] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"type": self._type.value})
@property
def type(self) -> str:
return self._type.value
@property
def reviewer(self) -> github.NamedUser.NamedUser | github.Team.Team:
return self._reviewer.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "type" in attributes: # pragma no branch
self._type = self._makeStringAttribute(attributes["type"])
if "reviewer" in attributes: # pragma no branch
assert self._type.value in ("User", "Team")
if self._type.value == "User":
self._reviewer = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["reviewer"])
elif self._type.value == "Team":
self._reviewer = self._makeClassAttribute(github.Team.Team, attributes["reviewer"])
class ReviewerParams:
"""
This class presents reviewers as can be configured for an Environment.
"""
def __init__(self, type_: str, id_: int):
assert isinstance(type_, str) and type_ in ("User", "Team")
assert isinstance(id_, int)
self.type = type_
self.id = id_
def _asdict(self) -> dict:
return {
"type": self.type,
"id": self.id,
}
| 5,105
|
Python
|
.py
| 84
| 56.297619
| 109
| 0.529471
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,482
|
Label.py
|
PyGithub_PyGithub/github/Label.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2013 martinqt <m.ki2@laposte.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Mateusz Loskot <mateusz@loskot.net> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 urllib.parse
from typing import Any, Dict
from github import Consts
from github.GithubObject import Attribute, CompletableGithubObject, NotSet, Opt, is_optional
class Label(CompletableGithubObject):
"""
This class represents Labels.
The reference can be found here
https://docs.github.com/en/rest/reference/issues#labels
"""
def _initAttributes(self) -> None:
self._color: Attribute[str] = NotSet
self._description: Attribute[str] = NotSet
self._name: Attribute[str] = NotSet
self._url: Attribute[str] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"name": self._name.value})
@property
def color(self) -> str:
self._completeIfNotSet(self._color)
return self._color.value
@property
def description(self) -> str:
self._completeIfNotSet(self._description)
return self._description.value
@property
def name(self) -> str:
self._completeIfNotSet(self._name)
return self._name.value
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
def delete(self) -> None:
"""
:calls: `DELETE /repos/{owner}/{repo}/labels/{name} <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
headers, data = self._requester.requestJsonAndCheck("DELETE", self.url)
def edit(self, name: str, color: str, description: Opt[str] = NotSet) -> None:
"""
:calls: `PATCH /repos/{owner}/{repo}/labels/{name} <https://docs.github.com/en/rest/reference/issues#labels>`_
"""
assert isinstance(name, str), name
assert isinstance(color, str), color
assert is_optional(description, str), description
post_parameters = NotSet.remove_unset_items({"new_name": name, "color": color, "description": description})
headers, data = self._requester.requestJsonAndCheck(
"PATCH",
self.url,
input=post_parameters,
headers={"Accept": Consts.mediaTypeLabelDescriptionSearchPreview},
)
self._useAttributes(data)
@property
def _identity(self) -> str:
return urllib.parse.quote(self.name)
def _useAttributes(self, attributes: Dict[str, Any]) -> None:
if "color" in attributes: # pragma no branch
self._color = self._makeStringAttribute(attributes["color"])
if "description" in attributes: # pragma no branch
self._description = self._makeStringAttribute(attributes["description"])
if "name" in attributes: # pragma no branch
self._name = self._makeStringAttribute(attributes["name"])
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
| 6,165
|
Python
|
.py
| 106
| 52.933962
| 119
| 0.541453
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,483
|
Membership.py
|
PyGithub_PyGithub/github/Membership.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2015 Matt Babineau <mbabineau@dataxu.com> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Martijn Koster <mak-github@greenhills.co.uk> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Pavan Kunisetty <nagapavan@users.noreply.github.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Mark Walker <mark.walker@realbuzz.com> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 __future__ import annotations
from typing import TYPE_CHECKING, Any
import github.NamedUser
import github.Organization
from github.GithubObject import Attribute, CompletableGithubObject, NotSet
if TYPE_CHECKING:
from github.NamedUser import NamedUser
from github.Organization import Organization
class Membership(CompletableGithubObject):
"""
This class represents Membership of an organization.
The reference can be found here
https://docs.github.com/en/rest/reference/orgs
"""
def _initAttributes(self) -> None:
self._url: Attribute[str] = NotSet
self._state: Attribute[str] = NotSet
self._role: Attribute[str] = NotSet
self._organization_url: Attribute[str] = NotSet
self._organization: Attribute[Organization] = NotSet
self._user: Attribute[NamedUser] = NotSet
def __repr__(self) -> str:
return self.get__repr__({"url": self._url.value})
@property
def url(self) -> str:
self._completeIfNotSet(self._url)
return self._url.value
@property
def state(self) -> str:
self._completeIfNotSet(self._state)
return self._state.value
@property
def role(self) -> str:
self._completeIfNotSet(self._role)
return self._role.value
@property
def organization_url(self) -> str:
self._completeIfNotSet(self._organization_url)
return self._organization_url.value
@property
def organization(self) -> Organization:
self._completeIfNotSet(self._organization)
return self._organization.value
@property
def user(self) -> NamedUser:
self._completeIfNotSet(self._user)
return self._user.value
def _useAttributes(self, attributes: dict[str, Any]) -> None:
if "url" in attributes: # pragma no branch
self._url = self._makeStringAttribute(attributes["url"])
if "state" in attributes: # pragma no branch
self._state = self._makeStringAttribute(attributes["state"])
if "role" in attributes: # pragma no branch
self._role = self._makeStringAttribute(attributes["role"])
if "organization_url" in attributes: # pragma no branch
self._organization_url = self._makeStringAttribute(attributes["organization_url"])
if "organization" in attributes: # pragma no branch
self._organization = self._makeClassAttribute(github.Organization.Organization, attributes["organization"])
if "user" in attributes: # pragma no branch
self._user = self._makeClassAttribute(github.NamedUser.NamedUser, attributes["user"])
| 6,059
|
Python
|
.py
| 102
| 54.705882
| 119
| 0.558249
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,484
|
PullRequestReview.py
|
PyGithub_PyGithub/tests/PullRequestReview.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Aaron Levine <allevin@sandia.gov> #
# Copyright 2017 Mike Miller <github@mikeage.net> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Gilad Shefer <gshefer@redhat.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Olof-Joachim Frahm (欧雅福) <olof@macrolet.net> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Claire Johns <42869556+johnsc1@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Gael Colas <gael.colas@plus.ai> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# #
# 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 datetime import datetime, timezone
from . import Framework
class PullRequestReview(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("PyGithub/PyGithub", lazy=True)
self.pull = self.repo.get_pull(538)
# Test ability to create a review
self.created_pullreview = self.pull.create_review(
self.repo.get_commit("2f0e4e55fe87e38d26efc9aa1346f56abfbd6c52"),
"Some review created by PyGithub",
)
# Test ability to get all reviews
self.pullreviews = self.pull.get_reviews()
# Test ability to get a single review
self.pullreview = self.pull.get_review(28482091)
def testDoesNotModifyPullRequest(self):
self.assertEqual(self.pull.id, 111649703)
def testEdit(self):
self.pullreview.edit("Comment edited by PyGithub")
self.assertEqual(self.pullreview.body, "Comment edited by PyGithub")
def testDismiss(self):
self.pullreview.dismiss("with prejudice")
self.assertEqual(self.pullreview.state, "DISMISSED")
def testAttributes(self):
self.assertEqual(self.pullreview.id, 28482091)
self.assertEqual(self.pullreview.user.login, "jzelinskie")
self.assertEqual(self.pullreview.body, "")
self.assertEqual(self.pullreview.commit_id, "7a0fcb27b7cd6c346fc3f76216ccb6e0f4ca3bcc")
self.assertEqual(self.pullreview.state, "APPROVED")
self.assertEqual(
self.pullreview.html_url,
"https://github.com/PyGithub/PyGithub/pull/538#pullrequestreview-28482091",
)
self.assertEqual(
self.pullreview.pull_request_url,
"https://api.github.com/repos/PyGithub/PyGithub/pulls/538",
)
self.assertEqual(
self.pullreview.submitted_at,
datetime(2017, 3, 22, 19, 6, 59, tzinfo=timezone.utc),
)
self.assertIn(self.created_pullreview.id, [r.id for r in self.pullreviews])
self.assertEqual(
repr(self.pullreview),
'PullRequestReview(user=NamedUser(login="jzelinskie"), id=28482091)',
)
| 5,653
|
Python
|
.py
| 90
| 57.477778
| 95
| 0.54193
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,485
|
conftest.py
|
PyGithub_PyGithub/tests/conftest.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Matthew Neal <meneal@matthews-mbp.raleigh.ibm.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 Sam Corbett <sam.corbett@cloudsoftcorp.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 . import Framework
def pytest_addoption(parser):
parser.addoption("--record", action="store_true", help="record mode")
parser.addoption("--auth_with_token", action="store_true", help="auth using a token")
parser.addoption("--auth_with_jwt", action="store_true", help="auth using JWT")
def pytest_configure(config):
if config.getoption("record"):
Framework.activateRecordMode()
if config.getoption("auth_with_token"):
Framework.activateTokenAuthMode()
if config.getoption("auth_with_jwt"):
Framework.activateJWTAuthMode()
| 3,338
|
Python
|
.py
| 46
| 70.413043
| 89
| 0.500456
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,486
|
GitTree.py
|
PyGithub_PyGithub/tests/GitTree.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 . import Framework
class GitTree(Framework.TestCase):
def setUp(self):
super().setUp()
self.tree = self.g.get_user().get_repo("PyGithub").get_git_tree("f492784d8ca837779650d1fb406a1a3587a764ad")
def testAttributes(self):
self.assertEqual(self.tree.sha, "f492784d8ca837779650d1fb406a1a3587a764ad")
self.assertEqual(len(self.tree.tree), 11)
self.assertEqual(self.tree.tree[0].mode, "100644")
self.assertEqual(self.tree.tree[0].path, ".gitignore")
self.assertEqual(self.tree.tree[0].sha, "8a9af1462c3f4e3358315c2d2e6ef1e7334c59dd")
self.assertEqual(self.tree.tree[0].size, 53)
self.assertEqual(self.tree.tree[0].type, "blob")
self.assertEqual(
self.tree.tree[0].url,
"https://api.github.com/repos/jacquev6/PyGithub/git/blobs/8a9af1462c3f4e3358315c2d2e6ef1e7334c59dd",
)
self.assertEqual(self.tree.tree[6].mode, "040000")
self.assertEqual(self.tree.tree[6].path, "ReplayDataForIntegrationTest")
self.assertEqual(self.tree.tree[6].sha, "60b4602b2c2070246c5df078fb7a5150b45815eb")
self.assertEqual(self.tree.tree[6].size, None)
self.assertEqual(self.tree.tree[6].type, "tree")
self.assertEqual(
self.tree.tree[6].url,
"https://api.github.com/repos/jacquev6/PyGithub/git/trees/60b4602b2c2070246c5df078fb7a5150b45815eb",
)
self.assertEqual(
self.tree.url,
"https://api.github.com/repos/jacquev6/PyGithub/git/trees/f492784d8ca837779650d1fb406a1a3587a764ad",
)
self.assertEqual(
repr(self.tree),
'GitTree(sha="f492784d8ca837779650d1fb406a1a3587a764ad")',
)
self.assertEqual(
repr(self.tree.tree[0]),
'GitTreeElement(sha="8a9af1462c3f4e3358315c2d2e6ef1e7334c59dd", path=".gitignore")',
)
| 4,666
|
Python
|
.py
| 72
| 59.291667
| 115
| 0.537154
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,487
|
Issue142.py
|
PyGithub_PyGithub/tests/Issue142.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Adam Baratz <adam.baratz@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# #
# 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
from . import Framework
class Issue142(Framework.TestCase):
def testDecodeJson(self):
self.assertEqual(github.Github().get_rate_limit().core.limit, 60)
| 2,861
|
Python
|
.py
| 38
| 73.842105
| 85
| 0.458481
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,488
|
Issue140.py
|
PyGithub_PyGithub/tests/Issue140.py
|
############################ Copyrights and license ############################
# #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 AetherDeity <aetherdeity+github@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 . import Framework
class Issue140(Framework.TestCase): # https://github.com/jacquev6/PyGithub/issues/140
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("twitter/bootstrap")
def testGetDirContentsThenLazyCompletionOfFile(self):
contents = self.repo.get_contents("js")
self.assertEqual(len(contents), 15)
n = 0
for content in contents:
if content.path == "js/bootstrap-affix.js":
self.assertEqual(len(content.content), 4722) # Lazy completion
n += 1
elif content.path == "js/tests":
self.assertEqual(content.content, None) # No completion at all
n += 1
self.assertEqual(n, 2)
def testGetFileContents(self):
contents = self.repo.get_contents("js/bootstrap-affix.js")
self.assertEqual(contents.encoding, "base64")
self.assertEqual(
contents.url,
"https://api.github.com/repos/twitter/bootstrap/contents/js/bootstrap-affix.js",
)
self.assertEqual(len(contents.content), 4722)
def testGetDirContentsWithRef(self):
self.assertEqual(
len(self.repo.get_contents("js", "8c7f9c66a7d12f47f50618ef420868fe836d0c33")),
15,
)
| 3,819
|
Python
|
.py
| 61
| 57.180328
| 92
| 0.50693
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,489
|
BranchProtection.py
|
PyGithub_PyGithub/tests/BranchProtection.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# #
# 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 . import Framework
class BranchProtection(Framework.TestCase):
def setUp(self):
super().setUp()
self.branch_protection = self.g.get_repo("curvewise-forks/PyGithub").get_branch("master").get_protection()
def testAttributes(self):
self.assertTrue(self.branch_protection.required_status_checks.strict)
self.assertEqual(self.branch_protection.required_status_checks.contexts, ["build (3.10)"])
self.assertTrue(self.branch_protection.required_linear_history)
self.assertEqual(
self.branch_protection.url,
"https://api.github.com/repos/curvewise-forks/PyGithub/branches/master/protection",
)
self.assertEqual(
self.branch_protection.__repr__(),
'BranchProtection(url="https://api.github.com/repos/curvewise-forks/PyGithub/branches/master/protection")',
)
self.assertFalse(self.branch_protection.allow_force_pushes)
self.assertFalse(self.branch_protection.allow_deletions)
self.assertFalse(self.branch_protection.required_conversation_resolution)
self.assertFalse(self.branch_protection.lock_branch)
self.assertFalse(self.branch_protection.allow_fork_syncing)
| 4,070
|
Python
|
.py
| 57
| 67.385965
| 119
| 0.536543
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,490
|
PullRequest1684.py
|
PyGithub_PyGithub/tests/PullRequest1684.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Matthew Neal <meneal@matthews-mbp.raleigh.ibm.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 Sam Corbett <sam.corbett@cloudsoftcorp.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Olof-Joachim Frahm (欧雅福) <olof@macrolet.net> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Victor Zeng <zacker150@users.noreply.github.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# #
# 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 . import Framework
class PullRequest1684(Framework.TestCase):
def setUp(self):
super().setUp()
self.user = self.g.get_user("ReDASers")
self.repo = self.user.get_repo("Phishing-Detection")
def testGetRunners(self):
runners = self.repo.get_self_hosted_runners()
self.assertEqual(19, runners.totalCount)
runner = runners[0]
self.assertEqual(1363, runner.id)
self.assertEqual("windows", runner.os)
self.assertEqual("0D80B14DC506", runner.name)
self.assertEqual("offline", runner.status)
self.assertFalse(runner.busy)
labels = runner.labels()
self.assertEqual(3, len(labels))
self.assertEqual("self-hosted", labels[0]["name"])
self.assertEqual("Windows", labels[1]["name"])
self.assertEqual("X64", labels[2]["name"])
def testDeleteRunnerObject(self):
runners = self.repo.get_self_hosted_runners()
initial_length = runners.totalCount
runner_to_delete = runners[0]
result = self.repo.remove_self_hosted_runner(runner_to_delete)
self.assertTrue(result)
runners = self.repo.get_self_hosted_runners()
ids = [runner.id for runner in self.repo.get_self_hosted_runners()]
self.assertEqual(initial_length - 1, runners.totalCount)
self.assertNotIn(runner_to_delete.id, ids)
def testDeleteRunnerId(self):
ids = [runner.id for runner in self.repo.get_self_hosted_runners()]
id_to_delete = ids[0]
result = self.repo.remove_self_hosted_runner(id_to_delete)
self.assertTrue(result)
ids = [runner.id for runner in self.repo.get_self_hosted_runners()]
self.assertNotIn(id_to_delete, ids)
| 4,672
|
Python
|
.py
| 73
| 59.164384
| 85
| 0.534148
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,491
|
Exceptions.py
|
PyGithub_PyGithub/tests/Exceptions.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2016 humbug <bah> #
# Copyright 2017 Hugo <hugovk@users.noreply.github.com> #
# Copyright 2017 Simon <spam@esemi.ru> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 Tuuu Nya <yuzesheji@qq.com> #
# Copyright 2018 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 pickle
import github
from . import Framework
class Exceptions(Framework.TestCase):
def testInvalidInput(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.g.get_user().create_key("Bad key", "xxx")
self.assertEqual(raisedexp.exception.status, 422)
self.assertEqual(
raisedexp.exception.data,
{
"errors": [
{
"code": "custom",
"field": "key",
"message": "key is invalid. It must begin with 'ssh-rsa' or 'ssh-dss'. Check that you're copying the public half of the key",
"resource": "PublicKey",
}
],
"message": "Validation Failed",
},
)
def testNonJsonDataReturnedByGithub(self):
# Replay data was forged according to https://github.com/jacquev6/PyGithub/pull/182
with self.assertRaises(github.GithubException) as raisedexp:
# 503 would be retried, disable retries
self.get_github(retry=None, pool_size=self.pool_size).get_user("jacquev6")
self.assertEqual(raisedexp.exception.status, 503)
self.assertEqual(
raisedexp.exception.data,
{
"data": "<html><body><h1>503 Service Unavailable</h1>No server is available to handle this request.</body></html>",
},
)
def testUnknownObject(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.g.get_user().get_repo("Xxx")
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(raisedexp.exception.data, {"message": "Not Found"})
self.assertEqual(str(raisedexp.exception), '404 {"message": "Not Found"}')
def testUnknownUser(self):
with self.assertRaises(github.GithubException) as raisedexp:
self.g.get_user("ThisUserShouldReallyNotExist")
self.assertEqual(raisedexp.exception.status, 404)
self.assertEqual(raisedexp.exception.data, {"message": "Not Found"})
self.assertEqual(str(raisedexp.exception), '404 {"message": "Not Found"}')
def testBadAuthentication(self):
with self.assertRaises(github.GithubException) as raisedexp:
github.Github(auth=github.Auth.Login("BadUser", "BadPassword")).get_user().login
self.assertEqual(raisedexp.exception.status, 401)
self.assertEqual(raisedexp.exception.data, {"message": "Bad credentials"})
self.assertEqual(str(raisedexp.exception), '401 {"message": "Bad credentials"}')
def testExceptionPickling(self):
pickle.loads(pickle.dumps(github.GithubException("foo", "bar", None)))
def testJSONParseError(self):
# Replay data was forged to force a JSON error
with self.assertRaises(ValueError):
self.g.get_user("jacquev6")
class SpecificExceptions(Framework.TestCase):
def testBadCredentials(self):
self.assertRaises(
github.BadCredentialsException,
lambda: github.Github(auth=github.Auth.Login("BadUser", "BadPassword")).get_user().login,
)
def test2FARequired(self):
self.assertRaises(
github.TwoFactorException,
lambda: github.Github(auth=github.Auth.Login("2fauser", "password")).get_user().login,
)
def testUnknownObject(self):
self.assertRaises(github.UnknownObjectException, lambda: self.g.get_user().get_repo("Xxx"))
def testBadUserAgent(self):
self.assertRaises(
github.BadUserAgentException,
lambda: github.Github(auth=self.login, user_agent="").get_user().name,
)
def testRateLimitExceeded(self):
# rate limit errors would be retried if retry is not set None
g = github.Github(retry=None)
def exceed():
for i in range(100):
g.get_user("jacquev6")
self.assertRaises(github.RateLimitExceededException, exceed)
def testAuthenticatedRateLimitExceeded(self):
def exceed():
for i in range(100):
res = self.g.search_code("jacquev6")
res.get_page(0)
with self.assertRaises(github.RateLimitExceededException) as raised:
exceed()
self.assertEqual(raised.exception.headers.get("retry-after"), "60")
def testIncompletableObject(self):
github.UserKey.UserKey.setCheckAfterInitFlag(False)
obj = github.UserKey.UserKey(None, {}, {}, False)
self.assertRaises(github.IncompletableObject, obj._completeIfNeeded)
| 7,821
|
Python
|
.py
| 134
| 50.514925
| 149
| 0.562427
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,492
|
CheckRun.py
|
PyGithub_PyGithub/tests/CheckRun.py
|
############################ Copyrights and license ############################
# #
# Copyright 2020 Dhruv Manilawala <dhruvmanila@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime, timezone
from . import Framework
class CheckRun(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("PyGithub/PyGithub")
self.testrepo = self.g.get_repo("dhruvmanila/pygithub-testing")
self.check_run_id = 1039891953
self.check_run_ref = "6bc9ecc8c849df4e45e60c1e6a5df8876180a20a"
self.check_run = self.repo.get_check_run(self.check_run_id)
self.commit = self.repo.get_commit(self.check_run_ref)
def testAttributes(self):
self.assertEqual(self.check_run.app.id, 15368)
self.assertEqual(self.check_run.app.slug, "github-actions")
self.assertEqual(self.check_run.check_suite_id, 1110219217)
self.assertEqual(
self.check_run.completed_at,
datetime(2020, 8, 28, 4, 21, 21, tzinfo=timezone.utc),
)
self.assertEqual(self.check_run.conclusion, "success")
self.assertEqual(
self.check_run.details_url,
"https://github.com/PyGithub/PyGithub/runs/1039891953",
)
self.assertEqual(self.check_run.external_id, "6b512fe7-587c-5ecc-c4a3-03b7358c152d")
self.assertEqual(self.check_run.head_sha, "6bc9ecc8c849df4e45e60c1e6a5df8876180a20a")
self.assertEqual(
self.check_run.html_url,
"https://github.com/PyGithub/PyGithub/runs/1039891953",
)
self.assertEqual(self.check_run.id, 1039891953)
self.assertEqual(self.check_run.name, "test (Python 3.8)")
self.assertEqual(self.check_run.node_id, "MDg6Q2hlY2tSdW4xMDM5ODkxOTUz")
self.assertEqual(self.check_run.output.annotations_count, 0)
self.assertEqual(len(self.check_run.pull_requests), 0)
self.assertEqual(
self.check_run.started_at,
datetime(2020, 8, 28, 4, 20, 27, tzinfo=timezone.utc),
)
self.assertEqual(self.check_run.status, "completed")
self.assertEqual(
self.check_run.url,
"https://api.github.com/repos/PyGithub/PyGithub/check-runs/1039891953",
)
self.assertEqual(repr(self.check_run), 'CheckRun(id=1039891953, conclusion="success")')
def testCheckRunOutputAttributes(self):
check_run_output = self.repo.get_check_run(1039891917).output
self.assertEqual(check_run_output.title, "test (Python 3.6)")
self.assertEqual(
check_run_output.summary,
"There are 1 failures, 0 warnings, and 0 notices.",
)
self.assertIsNone(check_run_output.text)
self.assertEqual(check_run_output.annotations_count, 1)
self.assertEqual(
check_run_output.annotations_url,
"https://api.github.com/repos/PyGithub/PyGithub/check-runs/1039891917/annotations",
)
self.assertEqual(repr(check_run_output), 'CheckRunOutput(title="test (Python 3.6)")')
def testGetCheckRunsForRef(self):
check_runs = self.commit.get_check_runs()
self.assertEqual(check_runs.totalCount, 4)
self.assertListEqual(
[check_run.id for check_run in check_runs],
[1039891953, 1039891931, 1039891917, 1039891902],
)
def testGetCheckRunsForRefFilterByCheckName(self):
check_runs = self.commit.get_check_runs(check_name="test (Python 3.6)")
self.assertEqual(check_runs.totalCount, 1)
self.assertListEqual([check_run.id for check_run in check_runs], [1039891917])
def testGetCheckRunsForRefFilterByStatus(self):
completed_check_runs = self.commit.get_check_runs(status="completed")
self.assertEqual(completed_check_runs.totalCount, 4)
self.assertListEqual(
[check_run.id for check_run in completed_check_runs],
[1039891953, 1039891931, 1039891917, 1039891902],
)
queued_check_runs = self.commit.get_check_runs(status="queued")
self.assertEqual(queued_check_runs.totalCount, 0)
in_progress_check_runs = self.commit.get_check_runs(status="in_progress")
self.assertEqual(in_progress_check_runs.totalCount, 0)
def testGetCheckRunsForRefFilterByFilter(self):
latest_check_runs = self.commit.get_check_runs(filter="latest")
all_check_runs = self.commit.get_check_runs(filter="all")
self.assertEqual(latest_check_runs.totalCount, 4)
self.assertListEqual(
[check_run.id for check_run in latest_check_runs],
[1039891953, 1039891931, 1039891917, 1039891902],
)
self.assertEqual(all_check_runs.totalCount, 4)
self.assertListEqual(
[check_run.id for check_run in all_check_runs],
[1039891953, 1039891931, 1039891917, 1039891902],
)
def testCreateCheckRunInProgress(self):
check_run = self.testrepo.create_check_run(
name="basic_check_run",
head_sha="0283d46537193f1fed7d46859f15c5304b9836f9",
status="in_progress",
external_id="50",
details_url="https://www.example.com",
started_at=datetime(2020, 9, 4, 1, 14, 52),
output={"title": "PyGithub Check Run Test", "summary": "Test summary"},
)
self.assertEqual(check_run.name, "basic_check_run")
self.assertEqual(check_run.head_sha, "0283d46537193f1fed7d46859f15c5304b9836f9")
self.assertEqual(check_run.status, "in_progress")
self.assertEqual(check_run.external_id, "50")
self.assertEqual(
check_run.started_at,
datetime(2020, 9, 4, 1, 14, 52, tzinfo=timezone.utc),
)
self.assertEqual(check_run.output.title, "PyGithub Check Run Test")
self.assertEqual(check_run.output.summary, "Test summary")
self.assertIsNone(check_run.output.text)
self.assertEqual(check_run.output.annotations_count, 0)
# We don't want to keep this hanging
check_run.edit(conclusion="success")
self.assertEqual(check_run.conclusion, "success")
self.assertEqual(check_run.status, "completed")
def testCreateCheckRunCompleted(self):
check_run = self.testrepo.create_check_run(
name="completed_check_run",
head_sha="0283d46537193f1fed7d46859f15c5304b9836f9",
status="completed",
started_at=datetime(2020, 10, 20, 10, 30, 29),
conclusion="success",
completed_at=datetime(2020, 10, 20, 11, 30, 50),
output={
"title": "Readme report",
"summary": "There are 0 failures, 2 warnings, and 1 notices.",
"text": "You may have some misspelled words on lines 2 and 4.",
"annotations": [
{
"path": "README.md",
"annotation_level": "warning",
"title": "Spell Checker",
"message": "Check your spelling for 'banaas'.",
"raw_details": "Do you mean 'bananas' or 'banana'?",
"start_line": 2,
"end_line": 2,
},
{
"path": "README.md",
"annotation_level": "warning",
"title": "Spell Checker",
"message": "Check your spelling for 'aples'",
"raw_details": "Do you mean 'apples' or 'Naples'",
"start_line": 4,
"end_line": 4,
},
],
"images": [
{
"alt": "Test Image",
"image_url": "http://example.com/images/42",
}
],
},
actions=[
{
"label": "Fix",
"identifier": "fix_errors",
"description": "Allow us to fix these errors for you",
}
],
)
self.assertEqual(check_run.name, "completed_check_run")
self.assertEqual(check_run.head_sha, "0283d46537193f1fed7d46859f15c5304b9836f9")
self.assertEqual(check_run.status, "completed")
self.assertEqual(
check_run.started_at,
datetime(2020, 10, 20, 10, 30, 29, tzinfo=timezone.utc),
),
self.assertEqual(check_run.conclusion, "success")
self.assertEqual(
check_run.completed_at,
datetime(2020, 10, 20, 11, 30, 50, tzinfo=timezone.utc),
),
self.assertEqual(check_run.output.annotations_count, 2)
def testUpdateCheckRunSuccess(self):
# This is a different check run created for this test
check_run = self.testrepo.create_check_run(
name="edit_check_run",
head_sha="0283d46537193f1fed7d46859f15c5304b9836f9",
status="in_progress",
external_id="100",
started_at=datetime(2020, 10, 20, 14, 24, 31),
output={"title": "Check run for testing edit method", "summary": ""},
)
self.assertEqual(check_run.name, "edit_check_run")
self.assertEqual(check_run.status, "in_progress")
check_run.edit(
status="completed",
conclusion="success",
output={
"title": "Check run for testing edit method",
"summary": "This is the summary of editing check run as completed.",
},
)
self.assertEqual(check_run.name, "edit_check_run")
self.assertEqual(check_run.status, "completed")
self.assertEqual(check_run.conclusion, "success")
self.assertEqual(check_run.output.title, "Check run for testing edit method")
self.assertEqual(
check_run.output.summary,
"This is the summary of editing check run as completed.",
)
self.assertEqual(check_run.output.annotations_count, 0)
def testUpdateCheckRunFailure(self):
# This is a different check run created for this test
check_run = self.testrepo.create_check_run(
name="fail_check_run",
head_sha="0283d46537193f1fed7d46859f15c5304b9836f9",
status="in_progress",
external_id="101",
started_at=datetime(2020, 10, 20, 10, 14, 51),
output={"title": "Check run for testing failure", "summary": ""},
)
self.assertEqual(check_run.name, "fail_check_run")
self.assertEqual(check_run.status, "in_progress")
check_run.edit(
status="completed",
conclusion="failure",
output={
"title": "Check run for testing failure",
"summary": "There is 1 whitespace error.",
"text": "You may have a whitespace error in the file 'test.py'",
"annotations": [
{
"path": "test.py",
"annotation_level": "failure",
"title": "whitespace checker",
"message": "Remove the unnecessary whitespace from the file.",
"start_line": 2,
"end_line": 2,
"start_column": 17,
"end_column": 18,
}
],
},
actions=[
{
"label": "Fix",
"identifier": "fix_errors",
"description": "Allow us to fix these errors for you",
}
],
)
self.assertEqual(check_run.status, "completed")
self.assertEqual(check_run.conclusion, "failure")
self.assertEqual(check_run.output.annotations_count, 1)
def testUpdateCheckRunAll(self):
check_run = self.testrepo.get_check_run(1279259090)
check_run.edit(
name="update_all_params",
head_sha="0283d46537193f1fed7d46859f15c5304b9836f9",
details_url="https://www.example-url.com",
external_id="49",
started_at=datetime(2020, 10, 20, 1, 10, 20),
completed_at=datetime(2020, 10, 20, 2, 20, 30),
actions=[
{
"label": "Hello World!",
"identifier": "identity",
"description": "Hey! This is a test",
}
],
)
self.assertEqual(check_run.name, "update_all_params")
self.assertEqual(check_run.head_sha, "0283d46537193f1fed7d46859f15c5304b9836f9")
self.assertEqual(check_run.details_url, "https://www.example-url.com")
self.assertEqual(check_run.external_id, "49")
self.assertEqual(
check_run.started_at,
datetime(2020, 10, 20, 1, 10, 20, tzinfo=timezone.utc),
)
self.assertEqual(
check_run.completed_at,
datetime(2020, 10, 20, 2, 20, 30, tzinfo=timezone.utc),
)
def testCheckRunAnnotationAttributes(self):
check_run = self.testrepo.get_check_run(1280914700)
self.assertEqual(check_run.name, "annotations")
annotation = check_run.get_annotations()[0]
self.assertEqual(annotation.annotation_level, "warning")
self.assertIsNone(annotation.end_column)
self.assertEqual(annotation.end_line, 2)
self.assertEqual(annotation.message, "Check your spelling for 'banaas'.")
self.assertEqual(annotation.path, "README.md")
self.assertEqual(annotation.raw_details, "Do you mean 'bananas' or 'banana'?")
self.assertIsNone(annotation.start_column)
self.assertEqual(annotation.start_line, 2)
self.assertEqual(annotation.title, "Spell Checker")
self.assertEqual(repr(annotation), 'CheckRunAnnotation(title="Spell Checker")')
def testListCheckRunAnnotations(self):
check_run = self.testrepo.get_check_run(1280914700)
self.assertEqual(check_run.name, "annotations")
self.assertEqual(check_run.status, "completed")
annotation_list = check_run.get_annotations()
self.assertEqual(annotation_list.totalCount, 2)
self.assertListEqual([annotation.start_line for annotation in annotation_list], [2, 4])
| 16,266
|
Python
|
.py
| 326
| 38.389571
| 95
| 0.568046
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,493
|
Workflow.py
|
PyGithub_PyGithub/tests/Workflow.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Mahesh Raju <coder@mahesh.net> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Thomas Burghout <thomas.burghout@nedap.com> #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# #
# 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 datetime import datetime, timezone
from . import Framework
class Workflow(Framework.TestCase):
def setUp(self):
super().setUp()
self.workflow = self.g.get_repo("PyGithub/PyGithub").get_workflow("check.yml")
def testAttributes(self):
self.assertEqual(
repr(self.workflow),
'Workflow(url="https://api.github.com/repos/PyGithub/PyGithub/actions/workflows/1026390", name="check")',
)
self.assertEqual(self.workflow.id, 1026390)
self.assertEqual(self.workflow.name, "check")
self.assertEqual(self.workflow.path, ".github/workflows/check.yml")
self.assertEqual(self.workflow.state, "active")
timestamp = datetime(2020, 4, 15, 0, 48, 32, tzinfo=timezone.utc)
self.assertEqual(self.workflow.created_at, timestamp)
self.assertEqual(self.workflow.updated_at, timestamp)
self.assertEqual(
self.workflow.url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/workflows/1026390",
)
self.assertEqual(
self.workflow.html_url,
"https://github.com/PyGithub/PyGithub/blob/master/.github/workflows/check.yml",
)
self.assertEqual(
self.workflow.badge_url,
"https://github.com/PyGithub/PyGithub/workflows/check/badge.svg",
)
def testGetRunsWithNoArguments(self):
self.assertListKeyEqual(
self.workflow.get_runs(),
lambda r: r.id,
[109950033, 109168419, 108934155, 108817672],
)
def testGetRunsWithObjects(self):
sfdye = self.g.get_user("sfdye")
master = self.g.get_repo("PyGithub/PyGithub").get_branch("master")
self.assertListKeyEqual(
self.workflow.get_runs(actor=sfdye, branch=master, event="push", status="completed"),
lambda r: r.id,
[100957683, 94845611, 93946842, 92714488],
)
def testGetRunsWithStrings(self):
self.assertListKeyEqual(
self.workflow.get_runs(actor="s-t-e-v-e-n-k", branch="master"),
lambda r: r.id,
[109950033, 108817672, 108794468, 107927403, 105213061, 105212023],
)
def testGetRunsWithHeadSha(self):
self.assertListKeyEqual(
self.workflow.get_runs(head_sha="3a6235b56eecc0e193c1e267b064c155c6ebc022"),
lambda r: r.id,
[3349872717],
)
def testGetRunsWithCreated(self):
self.assertListKeyEqual(
self.workflow.get_runs(created="2022-12-24"),
lambda r: r.id,
[3770390952],
)
def testCreateDispatchWithBranch(self):
dispatch_inputs = {"logLevel": "Warning", "message": "Log Message"}
workflow = self.g.get_repo("wrecker/PyGithub").get_workflow("manual_dispatch.yml")
branch = self.g.get_repo("wrecker/PyGithub").get_branch("workflow_dispatch_branch")
self.assertTrue(workflow.create_dispatch(branch, dispatch_inputs))
def testCreateDispatchWithTag(self):
dispatch_inputs = {"logLevel": "Warning", "message": "Log Message"}
workflow = self.g.get_repo("wrecker/PyGithub").get_workflow("manual_dispatch.yml")
tags = self.g.get_repo("wrecker/PyGithub").get_tags()
tag = [t for t in tags if t.name == "workflow_dispatch_tag"].pop()
self.assertTrue(workflow.create_dispatch(tag, dispatch_inputs))
def testCreateDispatchWithString(self):
dispatch_inputs = {"logLevel": "Warning", "message": "Log Message"}
workflow = self.g.get_repo("wrecker/PyGithub").get_workflow("manual_dispatch.yml")
ref_str = "main"
self.assertTrue(workflow.create_dispatch(ref_str, dispatch_inputs))
def testCreateDispatchForNonTriggerEnabled(self):
workflow = self.g.get_repo("wrecker/PyGithub").get_workflow("check.yml")
self.assertFalse(workflow.create_dispatch("main"))
| 6,941
|
Python
|
.py
| 118
| 52.008475
| 117
| 0.56954
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,494
|
Migration.py
|
PyGithub_PyGithub/tests/Migration.py
|
############################ Copyrights and license ############################
# #
# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Christoph Reiter <reiter.christoph@gmail.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime, timedelta, timezone
import github
from . import Framework
class Migration(Framework.TestCase):
def setUp(self):
super().setUp()
self.user = self.g.get_user()
self.migration = self.user.get_migrations()[0]
def testAttributes(self):
self.assertEqual(self.migration.id, 25320)
self.assertEqual(self.migration.owner.login, "singh811")
self.assertEqual(self.migration.guid, "608bceae-b790-11e8-8b43-4e3cb0dd56cc")
self.assertEqual(self.migration.state, "exported")
self.assertEqual(self.migration.lock_repositories, False)
self.assertEqual(self.migration.exclude_attachments, False)
self.assertEqual(len(self.migration.repositories), 1)
self.assertEqual(self.migration.repositories[0].name, "sample-repo")
self.assertEqual(self.migration.url, "https://api.github.com/user/migrations/25320")
self.assertEqual(
self.migration.created_at,
datetime(2018, 9, 14, 1, 35, 35, tzinfo=timezone(timedelta(seconds=19800))),
)
self.assertEqual(
self.migration.updated_at,
datetime(2018, 9, 14, 1, 35, 46, tzinfo=timezone(timedelta(seconds=19800))),
)
self.assertEqual(
repr(self.migration),
'Migration(url="https://api.github.com/user/migrations/25320", state="exported")',
)
def testGetArchiveUrlWhenNotExported(self):
self.assertRaises(github.UnknownObjectException, lambda: self.migration.get_archive_url())
def testGetStatus(self):
self.assertEqual(self.migration.get_status(), "exported")
def testGetArchiveUrlWhenExported(self):
self.assertEqual(
self.migration.get_archive_url(),
"https://github-cloud.s3.amazonaws.com/migration/25320/24575?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAISTNZFOVBIJMK3TQ%2F20180913%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180913T201100Z&X-Amz-Expires=300&X-Amz-Signature=a0aeb638facd0c78c1ed3ca86022eddbee91e5fe1bb48ee830f54b8b7b305026&X-Amz-SignedHeaders=host&actor_id=41840111&response-content-disposition=filename%3D608bceae-b790-11e8-8b43-4e3cb0dd56cc.tar.gz&response-content-type=application%2Fx-gzip",
)
def testDelete(self):
self.assertEqual(self.migration.delete(), None)
def testGetArchiveUrlWhenDeleted(self):
self.assertRaises(github.UnknownObjectException, lambda: self.migration.get_archive_url())
def testUnlockRepo(self):
self.assertEqual(self.migration.unlock_repo("sample-repo"), None)
| 4,883
|
Python
|
.py
| 73
| 61.232877
| 485
| 0.586703
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,495
|
WorkflowRun.py
|
PyGithub_PyGithub/tests/WorkflowRun.py
|
############################ Copyrights and license ############################
# #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2020 Yannick Jadoul <yannick.jadoul@belgacom.net> #
# Copyright 2021 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jeppe Fihl-Pearson <tenzer@tenzer.dk> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Sasha Chung <50770626+nuang-ee@users.noreply.github.com> #
# Copyright 2024 Chris Gavin <chris@chrisgavin.me> #
# #
# 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 datetime import datetime, timezone
from . import Framework
class WorkflowRun(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("PyGithub/PyGithub")
self.workflow_run = self.repo.get_workflow_run(3881497935)
def testAttributes(self):
self.assertEqual(
repr(self.workflow_run),
'WorkflowRun(url="https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935", id=3881497935)',
)
self.assertEqual(self.workflow_run.id, 3881497935)
self.assertEqual(self.workflow_run.name, "CI")
self.assertEqual(self.workflow_run.head_branch, "feat/workflow-run")
self.assertEqual(self.workflow_run.head_sha, "c6e5cac67a58a4eb11f1f28567a77a6e2cc8ee98")
self.assertEqual(self.workflow_run.path, ".github/workflows/ci.yml")
self.assertEqual(self.workflow_run.display_title, "TEST PR")
self.assertEqual(self.workflow_run.run_number, 930)
self.assertEqual(self.workflow_run.run_attempt, 1)
self.assertEqual(
self.workflow_run.run_started_at,
datetime(2023, 1, 10, 8, 24, 19, tzinfo=timezone.utc),
)
self.assertEqual(self.workflow_run.event, "pull_request")
self.assertEqual(self.workflow_run.status, "completed")
self.assertEqual(self.workflow_run.conclusion, "success")
self.assertEqual(self.workflow_run.workflow_id, 1903133)
self.assertEqual(
self.workflow_run.url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935",
)
self.assertEqual(
self.workflow_run.html_url,
"https://github.com/PyGithub/PyGithub/actions/runs/3881497935",
)
self.assertEqual(self.workflow_run.pull_requests, [])
created_at = datetime(2023, 1, 10, 8, 24, 19, tzinfo=timezone.utc)
self.assertEqual(self.workflow_run.created_at, created_at)
updated_at = datetime(2023, 1, 10, 8, 28, 20, tzinfo=timezone.utc)
self.assertEqual(self.workflow_run.updated_at, updated_at)
self.assertEqual(
self.workflow_run.jobs_url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935/jobs",
)
self.assertEqual(
self.workflow_run.logs_url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935/logs",
)
self.assertEqual(
self.workflow_run.check_suite_url,
"https://api.github.com/repos/PyGithub/PyGithub/check-suites/10279069747",
)
self.assertEqual(
self.workflow_run.artifacts_url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935/artifacts",
)
self.assertEqual(
self.workflow_run.cancel_url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935/cancel",
)
self.assertEqual(
self.workflow_run.rerun_url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/runs/3881497935/rerun",
)
self.assertEqual(
self.workflow_run.workflow_url,
"https://api.github.com/repos/PyGithub/PyGithub/actions/workflows/1903133",
)
self.assertEqual(self.workflow_run.head_commit.message, "add attribute 'name' on WorkflowRun")
self.assertEqual(self.workflow_run.repository.name, "PyGithub")
self.assertEqual(self.workflow_run.head_repository.name, "PyGithub")
def test_timing(self):
timing = self.workflow_run.timing()
self.assertEqual(
timing.billable,
{
"UBUNTU": {
"job_runs": [
{"duration_ms": 0, "job_id": 10545727758},
{"duration_ms": 0, "job_id": 10545727888},
{"duration_ms": 0, "job_id": 10545728039},
{"duration_ms": 0, "job_id": 10545728190},
{"duration_ms": 0, "job_id": 10545728356},
],
"jobs": 5,
"total_ms": 0,
}
},
)
self.assertEqual(timing.run_duration_ms, 241000)
def test_rerun(self):
wr = self.repo.get_workflow_run(3910280793)
self.assertFalse(wr.rerun())
def test_rerun_failed_jobs(self):
wr = self.repo.get_workflow_run(3881497935)
self.assertTrue(wr.rerun_failed_jobs())
def test_rerun_with_successful_run(self):
wr = self.repo.get_workflow_run(3881497935)
self.assertFalse(wr.rerun())
def test_cancel(self):
wr = self.repo.get_workflow_run(3911660493)
self.assertFalse(wr.cancel())
def test_delete(self):
wr = self.repo.get_workflow_run(3881497935)
self.assertFalse(wr.delete())
def test_jobs(self):
self.assertListKeyEqual(
self.workflow_run.jobs(),
lambda j: j.id,
[10545727758, 10545727888, 10545728039, 10545728190, 10545728356],
)
| 7,395
|
Python
|
.py
| 140
| 43.935714
| 119
| 0.559161
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,496
|
GraphQl.py
|
PyGithub_PyGithub/tests/GraphQl.py
|
############################ Copyrights and license ############################
# #
# Copyright 2024 Enrico Minack <github@enrico.minack.dev> #
# #
# 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 typing import Any, Dict
import github
from github import Github
from . import Framework
class GraphQl(Framework.TestCase):
def setUp(self):
super().setUp()
def expected(self, base_url: str = "https://github.com") -> Dict[Any, Any]:
return {
"data": {
"disablePullRequestAutoMerge": {
"actor": {
"avatarUrl": "https://avatars.githubusercontent.com/u/14806300?u=786f9f8ef8782d45381b01580f7f7783cf9c7e37&v=4",
"login": "heitorpolidoro",
"resourcePath": "/heitorpolidoro",
"url": f"{base_url}/heitorpolidoro",
},
"clientMutationId": None,
}
}
}
def testRequesterGraphQlPrefix(self):
get_graphql_prefix = github.Requester.Requester.get_graphql_prefix
assert "/graphql" == get_graphql_prefix(None)
assert "/graphql" == get_graphql_prefix("")
assert "/graphql" == get_graphql_prefix("/")
assert "/api/graphql" == get_graphql_prefix("/api/v3")
assert "/path/to/github/api/graphql" == get_graphql_prefix("/path/to/github/api/v3")
assert "/path/to/github/graphql" == get_graphql_prefix("/path/to/github")
def testDefaultUrl(self):
pull = self.g.get_repo("PyGithub/PyGithub").get_pull(31)
response = pull.disable_automerge()
assert response == self.expected()
def testOtherUrl(self):
base_url = "https://my.enterprise.com/api/v3"
gh = Github(base_url=base_url)
pull = gh.get_repo("PyGithub/PyGithub").get_pull(31)
response = pull.disable_automerge()
assert response == self.expected(base_url)
def testOtherPort(self):
base_url = "https://my.enterprise.com:8080/api/v3"
gh = Github(base_url=base_url)
pull = gh.get_repo("PyGithub/PyGithub").get_pull(31)
response = pull.disable_automerge()
assert response == self.expected(base_url)
| 3,757
|
Python
|
.py
| 66
| 49.409091
| 135
| 0.490899
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,497
|
ProjectColumn.py
|
PyGithub_PyGithub/tests/ProjectColumn.py
|
############################ Copyrights and license ############################
# #
# Copyright 2020 Florent Clarret <florent.clarret@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 datetime import datetime, timezone
from . import Framework
class ProjectColumn(Framework.TestCase):
def setUp(self):
super().setUp()
self.get_project_column = self.g.get_project_column(8700460)
self.move_project_column = self.g.get_project_column(8748065)
def testGetProjectColumn(self):
self.assertEqual(self.get_project_column.id, 8700460)
self.assertEqual(self.get_project_column.name, "c1")
self.assertEqual(
self.get_project_column.cards_url,
"https://api.github.com/projects/columns/8700460/cards",
)
self.assertEqual(self.get_project_column.node_id, "MDEzOlByb2plY3RDb2x1bW44NzAwNDYw")
self.assertEqual(
self.get_project_column.project_url,
"https://api.github.com/projects/4294766",
)
self.assertEqual(
self.get_project_column.url,
"https://api.github.com/projects/columns/8700460",
)
self.assertEqual(
self.get_project_column.created_at,
datetime(2020, 4, 13, 20, 29, 53, tzinfo=timezone.utc),
)
self.assertEqual(
self.get_project_column.updated_at,
datetime(2020, 4, 14, 18, 9, 38, tzinfo=timezone.utc),
)
def testGetAllCards(self):
cards = self.get_project_column.get_cards(archived_state="all")
self.assertEqual(cards.totalCount, 3)
self.assertEqual(cards[0].id, 36285184)
self.assertEqual(cards[0].note, "Note3")
self.assertEqual(cards[1].id, 36281526)
self.assertEqual(cards[1].note, "Note2")
self.assertEqual(cards[2].id, 36281516)
self.assertEqual(cards[2].note, "Note1")
def testGetArchivedCards(self):
cards = self.get_project_column.get_cards(archived_state="archived")
self.assertEqual(cards.totalCount, 1)
self.assertEqual(cards[0].id, 36281516)
self.assertEqual(cards[0].note, "Note1")
def testGetNotArchivedCards(self):
cards = self.get_project_column.get_cards(archived_state="not_archived")
self.assertEqual(cards.totalCount, 2)
self.assertEqual(cards[0].id, 36285184)
self.assertEqual(cards[0].note, "Note3")
self.assertEqual(cards[1].id, 36281526)
self.assertEqual(cards[1].note, "Note2")
def testGetCards(self):
cards = self.get_project_column.get_cards()
self.assertEqual(cards.totalCount, 2)
self.assertEqual(cards[0].id, 36285184)
self.assertEqual(cards[0].note, "Note3")
self.assertEqual(cards[1].id, 36281526)
self.assertEqual(cards[1].note, "Note2")
def testCreateCard(self):
new_card = self.get_project_column.create_card(note="NewCard")
self.assertEqual(new_card.id, 36290228)
self.assertEqual(new_card.note, "NewCard")
def testDelete(self):
project_column = self.g.get_project_column(8747987)
self.assertTrue(project_column.delete())
def testEdit(self):
self.move_project_column.edit("newTestColumn")
self.assertEqual(self.move_project_column.id, 8748065)
self.assertEqual(self.move_project_column.name, "newTestColumn")
def testMoveFirst(self):
self.assertTrue(self.move_project_column.move(position="first"))
def testMoveLast(self):
self.assertTrue(self.move_project_column.move(position="last"))
def testMoveAfter(self):
self.assertTrue(self.move_project_column.move(position="after:8700460"))
| 5,474
|
Python
|
.py
| 100
| 47.83
| 93
| 0.570629
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,498
|
RequiredStatusChecks.py
|
PyGithub_PyGithub/tests/RequiredStatusChecks.py
|
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> #
# Copyright 2013 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2014 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2016 Jannis Gebauer <ja.geb@me.com> #
# Copyright 2016 Peter Buckley <dx-pbuckley@users.noreply.github.com> #
# Copyright 2017 Nicolas Agustín Torres <nicolastrres@gmail.com> #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2018 sfdye <tsfdye@gmail.com> #
# Copyright 2019 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2019 TechnicalPirate <35609336+TechnicalPirate@users.noreply.github.com>#
# Copyright 2019 Wan Liuyang <tsfdye@gmail.com> #
# Copyright 2020 Steve Kowalik <steven@wedontsleep.org> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 . import Framework
class RequiredStatusChecks(Framework.TestCase):
def setUp(self):
super().setUp()
self.required_status_checks = (
self.g.get_user().get_repo("PyGithub").get_branch("integrations").get_required_status_checks()
)
def testAttributes(self):
self.assertTrue(self.required_status_checks.strict)
self.assertEqual(self.required_status_checks.contexts, ["foo/bar"])
self.assertEqual(
self.required_status_checks.url,
"https://api.github.com/repos/jacquev6/PyGithub/branches/integrations/protection/required_status_checks",
)
self.assertEqual(
self.required_status_checks.__repr__(),
'RequiredStatusChecks(url="https://api.github.com/repos/jacquev6/PyGithub/branches/integrations/protection/required_status_checks", strict=True)',
)
| 3,731
|
Python
|
.py
| 53
| 66.679245
| 158
| 0.507077
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|
12,499
|
Artifact.py
|
PyGithub_PyGithub/tests/Artifact.py
|
#!/usr/bin/env python
############################ Copyrights and license ############################
# #
# Copyright 2022 Aleksei Fedotov <lexa@cfotr.com> #
# Copyright 2023 Enrico Minack <github@enrico.minack.dev> #
# Copyright 2023 Trim21 <trim21.me@gmail.com> #
# #
# 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
from . import Framework
class Artifact(Framework.TestCase):
def setUp(self):
super().setUp()
self.repo = self.g.get_repo("transmission-web-control/transmission-web-control")
def testGetArtifactsFromWorkflow(self):
artifact = self.repo.get_workflow_run(5138169628).get_artifacts()[0]
self.assertEqual(artifact.name, "build-tar")
self.assertFalse(artifact.expired)
self.assertEqual(repr(artifact), 'Artifact(name="build-tar", id=724958104)')
def testGetArtifactsFromRepoWithName(self):
artifacts = self.repo.get_artifacts(name="build-tar")
self.assertEqual(artifacts.totalCount, 296)
assert all(x.name == "build-tar" for x in artifacts)
artifact = artifacts[0]
self.assertEqual(artifact.name, "build-tar")
self.assertEqual(repr(artifact), 'Artifact(name="build-tar", id=724959170)')
def testGetSingleArtifactFromRepo(self):
artifact = self.repo.get_artifact(719509139)
self.assertEqual(artifact.name, "build-zip")
self.assertFalse(artifact.expired)
self.assertEqual(repr(artifact), 'Artifact(name="build-zip", id=719509139)')
def testGetArtifactsFromRepo(self):
artifact_id = 719509139
artifacts = self.repo.get_artifacts()
for item in artifacts:
if item.id == artifact_id:
artifact = item
break
else:
assert False, f"No artifact {artifact_id} is found"
self.assertEqual(
repr(artifact),
f'Artifact(name="build-zip", id={artifact_id})',
)
def testGetNonexistentArtifact(self):
artifact_id = 396724437
repo_name = "lexa/PyGithub"
repo = self.g.get_repo(repo_name)
with self.assertRaises(github.GithubException):
repo.get_artifact(artifact_id)
def testDelete(self):
artifact_id = 396724439
repo_name = "lexa/PyGithub"
repo = self.g.get_repo(repo_name)
artifact = repo.get_artifact(artifact_id)
self.assertTrue(artifact.delete())
with self.assertRaises(github.GithubException):
repo.get_artifact(artifact_id)
| 4,106
|
Python
|
.py
| 74
| 49.040541
| 88
| 0.528006
|
PyGithub/PyGithub
| 6,892
| 1,756
| 334
|
LGPL-3.0
|
9/5/2024, 5:11:50 PM (Europe/Amsterdam)
|