Create a Gogs Repository via Script

Sep 26, 2021

When I’m prototyping or even when starting a new project, I tend to create the git repository too late. I usually create the repository precisely at the moment I think “I should have created a git repo, and committed all those changes already hours ago.” This repo creation “procrastination” is just laziness to go to the Web-UI, create a repository, and initialize it locally (it’s not even 2 minutes). How can I reduce the friction to a minimum? Right, by automating and making the process as painless as possible.

So I created a script that…

  • Creates a new repository on my Gogs server
  • Creates a new folder locally
  • Clones the remote repository into that local folder
  • Sets up the main branch
  • Creates an initial commit with a README file

It’s a python script I called newrepo. To make it work, you need an API-token. To create one, open the Gogs Web-UI, click on your profile picture ❯ Your Settings ❯ Applications ❯ Generate New Token.

Screenshot of Gogs UI with Applications-Settings open. User is able to enter a Token Name and click on a “Generate New Token” button.

Copy the token value and define an environment variable GOGS_TOKEN that contains the token.

Then create a newrepo file for the script. This is the source code:

#!/usr/bin/env python3

import requests
import os
import sys

if (len(sys.argv) == 0):
    print("newrepo example-name")
    exit(1)

name = sys.argv[1]
print(f"Name: {name}")

os.system(f"mkdir \"{name}\"")
os.chdir(f"./{name}")

gogsUser = "testuser" # <-- replace with your username
gogsHost = "https://try.gogs.io" # <-- replace with your Gogs server
url = f"{gogsHost}/api/v1/admin/users/{gogsUser}/repos"
authToken = os.environ.get('GOGS_TOKEN')

createResponse = requests.post(
    url,
    data={
        'name': name,
        'description': 'TODO',
        'private': True
    },
    headers={"Authorization": f"token {authToken}"}
)
createJson = createResponse.json()

gitUrl = createJson['clone_url']
# Sanitize if necessary:
# gitUrl = gitUrl.replace(':3000/', '/').replace('http://', 'https://')

print(f"Response: {createJson}")
print(f"Git URL: {gitUrl}")

os.system(f"git clone \"{gitUrl}\" .")
os.system(f"git checkout -b main")
with open("README.md", "w") as text_file:
    text_file.write(f"# {name}")
os.system("git add README.md")
os.system("git commit -m \"Initial commit\"")
os.system("git push -u origin main")

After chmod +x newrepo, and newrepo being in a folder added to the PATH environment variable, you can start a new project by simply running newrepo my-new-project. You’ll then have a new folder, initialized with git, including a set up remote repository you can push to.

You can find more information in the official Gogs API documentation, especially the Repositories API.

If you’re using this script, let me know whether it works for you. Enjoy, and never go git-less anymore!

You might also like