Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AndrewLaganaro/f5f7fac884bd59fca3ce02462bbcc9cb to your computer and use it in GitHub Desktop.
Save AndrewLaganaro/f5f7fac884bd59fca3ce02462bbcc9cb to your computer and use it in GitHub Desktop.
Fork a github repo, clone it, and set the upstream to the forked url

Git Fork-Clone-Upstream

This python script is designed to fork a repository, clone it locally, and set the upstream url for the newly created repository to the original url. I found myself duplicating this task far too much, so this script should help reduce the amount of me doing all these tasks.

This is my initial steps to learning python.

How to use

$ python git-fork-clone-upstream.py https://github.com/jenkinsci/jenkins

It will fork the repo (if it isn't forked already), and clone it locally.

TODO:

  • Read from ~/.github file with just the oauth token not need to set it as an environment variable. (done)
  • Would be nice to have a message about failing to clone repo because directory already exists. (done)
  • Might be better to have an argument instead of using os.environ. (done)

License

MIT

from github import Github
import sys
from os.path import expanduser
import os
from git import Repo, GitCommandError
f = open(expanduser("~/.github"), "r")
token = f.readline()[len("oauth="):].lstrip().rstrip()
g = Github(token)
user = g.get_user()
url = str(sys.argv[1]).replace("https://github.com/", "").split("/")
org = g.get_organization(url[0])
repo = org.get_repo(url[1])
my_fork = user.create_fork(repo)
try:
local_repo = Repo.clone_from("git@github.com:" + str(user.login) + "/" + str(repo.name) + ".git",
os.getcwd() + "/" + str(repo.name), branch="master")
Repo.create_remote(local_repo, "upstream", "git@github.com:" + url[0] + "/" + url[1] + ".git")
except GitCommandError:
print "Directory already exists and is not empty. Not cloning."
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment