3

I'm new to python. What I'm trying to do is to create a remote git repository on my GitHub account and then be able to clone it locally. I want to do all this in a python program. If it is easier to create a local git repo and then push it to my GitHub account then that is fine as well. All I can do right now is create a local git repo and that took only 2 lines of code.

import git
import os
repo_dir = os.path.join("testrepo")
r = git.Repo.init(repo_dir)

what I need to be able to do now is push this local repo into my GitHub account to have a remote one as well. As I said if doing the other way around is better/easier then that works as well. I read a lot about the different APIs that are provided (Pygithub, Github) but the documentation is giving me a headache. I have a hard time understanding what the methods return and how to use them. The goal is to be able to automate the process of creating a project and pushing it to GitHub with a python script that I will then run from the command line. Also, this is the first time I'm posting on StackOverflow so I apologize if I did not follow any conventions. Again I would appreciate clear explanations since it has only been 3 days since I started with python.

phd
  • 82,685
  • 13
  • 120
  • 165
Gboy
  • 31
  • 3

1 Answers1

0

I would suggest creating a remote repository, and then cloning it to your local machine.

Then to create the remote repository, you're going to have to make an API request to the GitHub API, but first, you'll need an access token from GitHub. You can make one of these from their web UI.

And then we'll use Requests: HTTP for Humans to make the POST request to the GitHub API:

import subprocess
import requests
import sys

# Notice that you username and token are required here
r = requests.post(
  "https://api.github.com/users/<username>/repos?access_token=<generated token>", 
  data={
  "name": "Hello-World",
  "description": "This is your first repository",
  "homepage": "https://github.com",
  "private": false,
  "has_issues": true,
  "has_projects": true,
  "has_wiki": true
})

if r.status_code != 200:
  sys.exit()

And now that the remote repository has been created, you can clone it to your machine

clone_url = r.text.clone_url
subprocess.check_output(['git', 'clone', clone_url], cwd=repo_dir)

I didn't actually run this code, but I think it should get you pretty close, good luck!

Community
  • 1
  • 1
Zach Olivare
  • 3,805
  • 3
  • 32
  • 45