How to create a new repository with PyGithub - python

How can I create a new repository with PyGithub on Github?
In particular I like to know how to use the create_repo method? How do I generate a AuthenticatedUser?

The solution to my question is the following
g = Github(token)
user = g.get_user()
repo = user.create_repo(full_name)

I stumbled across this question trying to figure out how to coax PyGithub into creating a Repository within an Organization and thought it would be relevant here.
g = Github(token)
organization = g.get_organization("org-name")
organization.create_repo(
name,
allow_rebase_merge=True,
auto_init=False,
description=description,
has_issues=True,
has_projects=False,
has_wiki=False,
private=True,
)
The full set of keyword arguments may be found here: https://developer.github.com/v3/repos/#input

I stumbled onto this question when trying to figure out how to create an AuthenticatedUser object. Turns out you get a NamedUser when you pass any argument to get_user, and if you give it no arguments, you get the AuthenticatedUser corresponding to the creds you used when creating the Github object.
As a minimal example, the following:
from github import Github
g = Github("my GitHub API token")
user = g.get_user('myname')
print user
authed = g.get_user()
print authed
yields
<github.NamedUser.NamedUser object at 0x7f95d5eeed10>
<github.AuthenticatedUser.AuthenticatedUser object at 0x7f95d5684410>
Once you have an AuthenticatedUser object, you can call CreateRepo as explained in the docs that you linked.

To create a repository, you can use GitPython. Here is a tutorial on how to init a rep. It's as simple as:
import git
repo_dir = os.path.join(rw_dir, 'my-new-repo')
file_name = os.path.join(repo_dir, 'new-file')
r = git.Repo.init(repo_dir)
You can also use Dulwich to create a repository:
from dulwich.repo import Repo
x = Repo.init("/path/to/new/repo")
Once you have that done, you can use PyGithub to access the repositories (or stick to the APIs provided above):
from github import Github
g = Github("user", "password")
for repo in g.get_user().get_repos():
print repo.name

Answer to the question:
login via token:
g = Github(token)
user = g.get_user()
repo = user.create_repo(repo_name)
print(repo)#To
login via username and password:
g = Github("user", "password")
user = g.get_user()
repo = user.create_repo(repo_name)
print(repo)
Github Enterprise with the custom hostname.
login to Enterprise GitHub which has organizations
g = Github(base_url="https://{hostname}/api/v3", login_or_token="token")
org = g.get_organization("org name")
repo = org.create_repo(repo_name)

Related

Pushing local repository to remote repository using python Github

The code should do the following in order:
It should download/clone the public Github repository locally.
The should remove all the git history (and branches)
Use the Github API to create a new Github repository initialized with the input github repository content that you downloaded locally. The new repository should be named
using name supplied.
I am able to do 1 and 3 but asks for log-in 2 times. I am not able to initialize the new remote repo with local repo.
local_repo = repo1 how?
And removing git history? where can I find git history in the cloned repo.
import git,os,tempfile,os,fnmatch,sys
from github import Github
username = sys.argv[1]
password = sys.argv[2]
input_repo_url = sys.argv[3]
output_repo_name = sys.argv[4]
tempdir=tempfile.mkdtemp(prefix="",suffix="")
predictable_filename = "myfile"
saved_umask = os.umask(77)
path = os.path.join(tempdir,predictable_filename)
print("Cloning the repository at "+path)
local_repo = git.Repo.clone_from(input_repo_url,path, branch="master")
print("Clone successful!")
g = Github(username,password)
user = g.get_user()
repo1 = user.create_repo(output_repo_name)
print("New repository created at "+username+" account ")
print(repo1)
target_url = "https://github.com/"+username+"/"+output_repo_name+".git"
print(target_url)
print("Pushing cloned repo to target repo")
local_repo.create_remote("new",url=target_url)
local_repo.git.push("new")
print("Success!!")

Creating Gist with PyGithub

Is there an option to create new Gist with PyGithub?
There is such API option on GitHub, however it seems to be missing in PyGithub.
Use Github.get_user followed by AuthenticatedUser.create_gist:
gh = github.Github("auth token")
gh_auth_user = gh.get_user()
gist = gh_auth_user.create_gist(public=False, files={"myfile.txt": github.InputFileContent("my contents")}, description="my description")

PyGitHub: Unable to access private repositories of my team

I want to access a private repository of a team that I am part of. However, I am not able to access it. It throws an exception as follows:
UnknownObjectException: 404 {u'documentation_url': u'https://developer.github.com/v3/repos/#list-teams', u'message': u'Not Found'}
My code:
from github import Github
import pandas as pd
git = Github("token")
org = git.get_organization('org')
org.get_repo('repo_name')
It throws n error at the above statement.
I want to access this repository and get the count of number of teams who have access to the repository. However, I got the above mentioned error at the last line of the above code.
Can someone help me to fix this?
For future readers who are security-minded like me and want a read-only Personal Access Token, to read your private repos, you will need this enabled (and the OP will have to generate a new token).
For Github Enterprise:
from github import Github
g = Github(base_url="https://your_host_name/api/v3", login_or_token="your_access_token")
org = g.get_organization("your_org")
repo = org.get_repo(repo_name) # getting the repo
print(repo)
For Github :
from github import Github
g = Github(username,password))
repo = g.get_repo(repo_name) # getting the repo
print(repo)
Which repo_name is used?
Example: team_X/repo_1
If using github() directly: repo = github().get_repo("team_X/repo_1")
If using org object to get repo: repo = org.get_repo("repo_1")

Github repo results when using github3.py library

I'm looking through some of the user documentation for github3.py library.
I'm trying to list all of a user's repos.
If I use the code below, with gr = gh.repos.list().all(), I get the expected results.
But, if I use gr = gh.repos.list(user='username',type='all'), I get this error: <pygithub3.core.result.smart.Result object at 0x00000000033728D0>
Looking at the docs, this should work, but I'm new to Python and this library so I may be missing something??
#!/usr/bin/env python
from pygithub3 import Github
import requests
auth = dict(login="xxxx", user = "xxxx", token="xxxxx", repo="my-repo")
gh = Github(**auth)
gr = gh.repos.list().all()
print gr
Try this way:
from pygithub3 import Github
auth = dict(login="my-github-login", password="my-github-password")
g = Github(**auth)
print g.repos.list(user='user-whose-repos-I-want-to-get').all()

How can I find all public repos in github that a user contributes to?

I'm using the github3 python library and am trying to find all public repos that users from our organization have contributed to (to reward the support of open source!).
I've got the list of users for the organization, but now what?
Can I use the public events iterator to find repos?
#!/usr/bin/env python
import argparse
import github3
def get_organization(github, name):
for organization in github.iter_orgs():
if organization.login == name:
return organization
def main(args):
github = github3.login(args.github_username, password=args.github_password)
organization = get_organization(github, args.organization)
# Get a list of all current organization contributors
orgMembers = [member.login for member in organization.iter_members()]
# now what?
You can take an example of test_github.py:
def test_iter_user_repos(self):
self.response('repo', _iter=True)
self.get('https://api.github.com/users/sigmavirus24/repos')
self.conf.update(params={'type': 'all', 'direction': 'desc'})
next(self.g.iter_user_repos('sigmavirus24', 'all', direction='desc'))
self.mock_assertions()
self.conf.update(params={"sort": "created"})
self.get('https://api.github.com/users/sigmavirus24/repos')
assert isinstance(next(self.g.iter_user_repos('sigmavirus24', sort="created")),
github3.repos.Repository)
self.mock_assertions()
It is based on the GitHub API mentioned in "How to retrieve the list of all github repositories of a person?":
/users/:user/repos
(public repos only)

Categories