Back to Tech Blog
AutomationPythonGitHubProductivity

Tired of Manually Setting Up GitHub Repositories? Let's Automate It Like a Pro!

Stop wasting time on repetitive repo setup. Learn how to automate GitHub repository creation, initialization, and pushing with Python.

November 29, 2024
5 min read

Let me guess: You've got an idea for the next big project, your fingers are itching to code, but wait — ugh, you need to:

  1. Create a GitHub repository online
  2. Clone it locally
  3. Add files, commit changes, and push it back up

Every. Single. Time. It's repetitive, boring, and worst of all, it's killing your vibe!

But hey, why work hard when you can work smart? In just a few steps, you can automate the entire process with Python and let the machines do the heavy lifting for you.

Ready? Let's turn this snooze-fest into an exciting "push-and-done" adventure!

What Are We Automating Here?#

This script isn't just some "meh" automation — it's your new repo-genie

  • Creates a GitHub repository online without you even opening a browser
  • Initializes a Git repository locally
  • Adds files, commits changes, and pushes them

And the best part? It still lets you step in anytime for manual tweaks. This is smart work, not dependency!

First Things First: The Key to Automation is Your GitHub Token#

To use GitHub's API in our script, you'll need a Personal Access Token (PAT). This token acts as a "key" to authenticate you without exposing your GitHub password. Think of it as the magic wand that makes this whole automation work.

Here's how you can get one:

1. Head to GitHub Settings#

Navigate to GitHub → Settings → Developer Settings → Personal Access Tokens → Tokens (classic).

2. Generate Your Token#

  • Click Generate Token
  • Give it a meaningful name like Repo Automation
  • Assign it all necessary permissions (especially for repo access)

3. Save It Securely#

  • Option 1: Store it somewhere safe (like a password manager)
  • Option 2: Add it to your system's environment variables so you don't need to type it every time

Step 1: Let's Create the Repo Online!#

Imagine snapping your fingers and having a shiny new repo appear in your GitHub account. Well, that's essentially what this script does!

Code
import requests
import subprocess
import os
 
def create_github_repo(repo_name, repo_desc, github_username, github_token):
    user_url = f"https://api.github.com/user"
    response = requests.get(user_url, auth=(github_username, github_token))
    if response.status_code != 200:
        print("Error authenticating with GitHub")
        exit(1)
 
    # Get user's information from GitHub API
    user_data = response.json()
    user_id = user_data["login"]
 
    # Set up repository creation parameters
    repo_params = {
        "name": repo_name,
        "description": repo_desc,
        "private": False
    }
 
    # Create new repository with GitHub API
    repo_url = "https://api.github.com/user/repos"
    response = requests.post(repo_url, json=repo_params, auth=(github_username, github_token))
    if response.status_code != 201:
        print("Error creating repository")
        print(response.json())
        exit(1)
 
    print(f"Repository '{repo_name}' created successfully!")
 
# Set up repository creation parameters
repo_name = input("Enter your repository name: ")
repo_desc = input("Enter a description for your repository: ")
github_username = input("Enter your GitHub username: ")
github_token = os.getenv("GITHUB_TOKEN")
 
if github_token:
    github_token = github_token
else:
    print("Please set the GITHUB_TOKEN environment variable or provide a valid GitHub token")
    github_token = input("Enter your GitHub Token: ")
 
# Create new GitHub repository
create_github_repo(repo_name, repo_desc, github_username, github_token)

What Happens Here?#

  • Authenticates You: It uses your GitHub username and personal access token
  • Creates the Repo: With just a few API calls, you've got a repo up and ready
  • Error Handling: Messed up your credentials? No problem — the script will tell you what went wrong (nicely)

Step 2: Local Repo — Let's Get Things Rolling#

Now that your repo is alive and kicking on GitHub, it's time to set up shop locally.

Code
def initialize_repo():
    # Create a new Git repository in the current directory
    subprocess.run(['git', 'init'])
 
def add_files():
    # Add files to the repository
    with open('README.md', 'w') as f:
        f.write('This is a sample repository.')
    with open('LICENSE', 'w') as f:
        f.write('License information.')

Why This is Cool#

  • Automatic Initialization: No need to remember git init
  • Default Files: It creates a README.md and a LICENSE so your repo doesn't feel empty and sad

Step 3: Commit It Like a Rockstar!#

Git commits are like journal entries for your code — so let's make them snappy and meaningful.

Code
def commit_changes(message):
    # Commit files with a custom message
    subprocess.run(['git', 'add', '.'])
    subprocess.run(['git', 'commit', '-m', message])

Why Automate This?#

Who wants to type git add and git commit every time? This does it for you in one clean motion. Plus, you can pour all your creativity into the commit message!

Step 4: Push It Real Good (to GitHub, That Is)#

Time to send your code where it belongs — up in the GitHub cloud!

Code
def push_to_github():
    # Push the changes to the GitHub repo
    subprocess.run(['git', 'remote', 'add', 'origin', f'https://github.com/{github_username}/{repo_name}.git'])
    subprocess.run(['git', 'push', '--set-upstream', 'origin', 'master'])
 
def main():
    # Initialize the repository
    initialize_repo()
 
    # Add files
    add_files()
 
    # Commit changes
    message = input("Enter a commit message: ")
    commit_changes(message)
 
    # Push changes to GitHub
    push_to_github()
 
if __name__ == '__main__':
    main()

Final Thoughts: Make Your Life Easier#

With a secure Personal Access Token, you're set to automate all those boring repo setup steps and focus on creating something amazing. Store the token securely, let the script do the grunt work, and watch as automation transforms your workflow into pure magic.

No more manual clicks — just smooth sailing. So, what are you waiting for? Unleash the power of Python and take control of your repo game!

Share: