Skip to content

Instantly share code, notes, and snippets.

@SmallEndian
Created June 4, 2019 11:35
Show Gist options
  • Select an option

  • Save SmallEndian/cae7610cc9a8460afa26e63c68fc20f8 to your computer and use it in GitHub Desktop.

Select an option

Save SmallEndian/cae7610cc9a8460afa26e63c68fc20f8 to your computer and use it in GitHub Desktop.
Create github repos on the fly
#!/usr/bin/env python3
"""
gitinit: For these times when you want push your current repository to github. gitinit creates a new public or private repository and then outputs the new url to configure your git remote.
Pushing with https is _bad_, so that info is not shown
"""
__author__ = "Jonathan Sid-Otmane"
import os
import sys
import argparse
import requests
class tcolors:
"""
Thanks to https://stackoverflow.com/a/287944/4595006
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
api_url = "https://api.github.com"
api_endpoint = "/user/repos"
token_url = "https://github.com/settings/tokens"
api_token = None
def create_repo(name, desc, public):
"""
Calls the github api: https://developer.github.com/v3/repos/#create
"""
body = {"name": name, "description": desc, 'private': not public}
headers = {'authorization': "token %s" % api_token}
with requests.post(
api_url + "/user/repos", json=body, headers=headers) as resp:
try:
resp.raise_for_status()
resp = resp.json()
print("New repository created!\nOwner: %s\nRepository name: %s" %
(resp["owner"]["login"], resp["name"]))
print("Use: %sgit remote add origin %s%s" %
(tcolors.OKGREEN, resp['ssh_url'], tcolors.ENDC))
except:
print("%s%s%s" % (tcolors.FAIL, resp.json()["message"],
tcolors.ENDC))
print(resp.text)
def main():
global api_token
parser = argparse.ArgumentParser(
description="Create a github repository from the command line.")
parser.add_argument(
"name", type=str, help="Name of your future repository.")
parser.add_argument(
"description",
type=str,
nargs="?",
default="",
help="A short, one line description.")
parser.add_argument(
"-p",
"--publish",
action="store_true",
help="Makes your repository public")
args = vars(parser.parse_args())
if 'github_token' not in os.environ:
print(
"You need to export a github token as an environment variable \nSee %s"
% token_url)
print('%sexport github_token="TOKEN_VALUE" %s' % (tcolors.FAIL,
tcolors.ENDC))
sys.exit(3)
api_token = os.environ['github_token']
create_repo(args["name"], args["description"], args["publish"])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment