############################ Copyrights and license ############################
# #
# Copyright 2012 Christopher Gilbert #
# Copyright 2012 Steve English #
# Copyright 2012 Vincent Jacques #
# Copyright 2012 Zearin #
# Copyright 2013 AKFish #
# Copyright 2013 Adrian Petrescu #
# Copyright 2013 Cameron White #
# Copyright 2013 David Farr #
# Copyright 2013 Mark Roddy #
# Copyright 2013 Vincent Jacques #
# Copyright 2013 martinqt #
# Copyright 2014 Vincent Jacques #
# Copyright 2015 Aaron Levine #
# Copyright 2015 Christopher Wilcox #
# Copyright 2015 Dan Vanderkam #
# Copyright 2015 Ed Holland #
# Copyright 2015 Enix Yu #
# Copyright 2015 Jay #
# Copyright 2015 Jonathan Debonis #
# Copyright 2015 Kevin Lewandowski #
# Copyright 2015 Kyle Hornberg #
# Copyright 2016 @tmshn #
# Copyright 2016 Dustin Spicuzza #
# Copyright 2016 Enix Yu #
# Copyright 2016 Jannis Gebauer #
# Copyright 2016 Per Øyvind Karlsen #
# Copyright 2016 Peter Buckley #
# Copyright 2016 Sylvus #
# Copyright 2016 fukatani #
# Copyright 2016 ghfan #
# Copyright 2017 Andreas Lutro #
# Copyright 2017 Ben Firshman #
# Copyright 2017 Chris McBride #
# Copyright 2017 Hugo #
# Copyright 2017 Jannis Gebauer #
# Copyright 2017 Jason White #
# Copyright 2017 Jimmy Zelinskie #
# Copyright 2017 Simon #
# Copyright 2018 Aaron L. Levine #
# Copyright 2018 AetherDeity #
# Copyright 2018 Alice GIRARD #
# Copyright 2018 Andrew Smith #
# Copyright 2018 Benoit Latinier #
# Copyright 2018 Brian Torres-Gil #
# Copyright 2018 Hayden Fuss #
# Copyright 2018 Ilya Konstantinov #
# Copyright 2018 Jacopo Notarstefano #
# Copyright 2018 John Hui #
# Copyright 2018 Justin Kufro #
# Copyright 2018 Mateusz Loskot #
# Copyright 2018 Michael Behrisch #
# Copyright 2018 Nicholas Buse #
# Copyright 2018 Philip May #
# Copyright 2018 Raihaan <31362124+res0nance@users.noreply.github.com> #
# Copyright 2018 Shinichi TAMURA #
# Copyright 2018 Steve Kowalik #
# Copyright 2018 Vinay Hegde #
# Copyright 2018 Wan Liuyang #
# Copyright 2018 Will Yardley #
# Copyright 2018 Yossarian King #
# Copyright 2018 per1234 #
# Copyright 2018 sechastain #
# Copyright 2018 sfdye #
# Copyright 2019 Adam Baratz #
# Copyright 2019 Alex #
# Copyright 2019 Kevin LaFlamme #
# Copyright 2019 Olof-Joachim Frahm (欧雅福) #
# Copyright 2019 Steve Kowalik #
# Copyright 2019 Tim Gates #
# Copyright 2019 Wan Liuyang #
# Copyright 2019 Will Li #
# Copyright 2020 Alice GIRARD #
# Copyright 2020 Anuj Bansal #
# Copyright 2020 Chris de Graaf #
# Copyright 2020 Dhruv Manilawala #
# Copyright 2020 Dominic Davis-Foster #
# Copyright 2020 Florent Clarret #
# Copyright 2020 Glenn McDonald #
# Copyright 2020 Huw Jones #
# Copyright 2020 Mark Bromell #
# Copyright 2020 Max Wittig #
# Copyright 2020 Pascal Hofmann #
# Copyright 2020 Steve Kowalik #
# Copyright 2020 Tim Gates #
# Copyright 2020 Victor Zeng #
# Copyright 2020 ton-katsu #
# Copyright 2021 Chris Keating #
# Copyright 2021 Floyd Hightower #
# Copyright 2021 Mark Walker #
# Copyright 2021 Steve Kowalik #
# Copyright 2021 Tanner <51724788+lightningboltemoji@users.noreply.github.com> #
# Copyright 2021 xmo-odoo #
# Copyright 2022 Aleksei Fedotov #
# Copyright 2022 Eric Nieuwland #
# Copyright 2022 Ibrahim Hussaini #
# Copyright 2022 KimSia Sim <245021+simkimsia@users.noreply.github.com> #
# Copyright 2022 Marco Köpcke #
# Copyright 2023 Andrew Collington #
# Copyright 2023 Andrew Dawes <53574062+AndrewJDawes@users.noreply.github.com> #
# Copyright 2023 Armen Martirosyan #
# Copyright 2023 BradChengIRESS <49461141+BradChengIRESS@users.noreply.github.com>#
# Copyright 2023 Enrico Minack #
# Copyright 2023 Felipe Peter #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Jonathan Greg <31892308+jmgreg31@users.noreply.github.com> #
# Copyright 2023 Jonathan Leitschuh #
# Copyright 2023 Joseph Henrich #
# Copyright 2023 Kevin Grandjean #
# Copyright 2023 Mark Amery #
# Copyright 2023 Mauricio Alejandro Martínez Pacheco #
# Copyright 2023 Mauricio Alejandro Martínez Pacheco #
# Copyright 2023 Max Mehl <6170081+mxmehl@users.noreply.github.com> #
# Copyright 2023 Micael <10292135+notmicaelfilipe@users.noreply.github.com> #
# Copyright 2023 Mikhail f. Shiryaev #
# Copyright 2023 Oskar Jansson <56458534+janssonoskar@users.noreply.github.com>#
# Copyright 2023 Philipp A #
# Copyright 2023 Roberto Pastor Muela <37798125+RobPasMue@users.noreply.github.com>#
# Copyright 2023 Sol Redfern <59831933+Tsuesun@users.noreply.github.com> #
# Copyright 2023 Trim21 #
# Copyright 2023 Wojciech Barczyński <104033489+WojciechBarczynski@users.noreply.github.com>#
# Copyright 2023 alson #
# Copyright 2023 chantra #
# Copyright 2024 Benjamin K <53038537+treee111@users.noreply.github.com> #
# Copyright 2024 Enrico Minack #
# Copyright 2024 Heitor Polidoro #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2024 Thomas Cooper #
# 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 . #
# #
################################################################################
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.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.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 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 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 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} `_
: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 `_
: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 `_
: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} `_
: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} `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
"""
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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
"""
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 `_
: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 `_
: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
: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} `_
: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} `_
: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} `_
"""
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} `_
: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} `_
: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} `_
: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 `_
: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} `_
: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,
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} `_
"""
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(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,
"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} `_
: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 `_
: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} `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `_
: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} `_
: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 `_
: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} `_
: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 `_
: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} `_
: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 `_
: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 `_
"""
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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `:, 'commit': :class:`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 `_
: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} `_
: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} `_
: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 `:, 'commit': :class:`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} `_
: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 `:, 'commit': :class:`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} `_
"""
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 `_
: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} `_
: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 `_
: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 `_
: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 `_
: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 `_
: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} `_
: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} `_
: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} `_
: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 `_
: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} `_
: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} `_
: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} `_
: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} `_
: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 `_
: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} `_
: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 `_
: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} `_
: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 `_
: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 `_
: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} `_
: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 `_
: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} `_
: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 `_
: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} `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `_
: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 `_
"""
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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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} `_
: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 `_
: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} `_
: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} `_
: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} `_
: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} `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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 `_
: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} `_
: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} `_
: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} `_
: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 `_
: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 `_
: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 `_
: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}