Skip to content

Instantly share code, notes, and snippets.

@aaditkamat
Created November 20, 2024 15:44
Show Gist options
  • Save aaditkamat/ce54c6fc0b9cc049cad7abfaf56109d7 to your computer and use it in GitHub Desktop.
Save aaditkamat/ce54c6fc0b9cc049cad7abfaf56109d7 to your computer and use it in GitHub Desktop.
Python script to clean GitHub fork
import os
import datetime
import pytz
from github import Github
from github.GithubException import GithubException
def cleanup_inactive_forks(github_token, username, repos_to_delete, inactive_days=30):
"""
Remove GitHub forks that haven't been updated in the past month.
:param github_token: Personal access token with repo delete permissions
:param username: GitHub username of the account to clean up forks from
:param inactive_days: Number of days since last update to consider a fork inactive
"""
# Create a GitHub instance with authentication
g = Github(github_token)
# Get the user object
user = g.get_user()
# Set the timezone to UTC for consistent date comparisons
utc = pytz.UTC
# Calculate the cutoff date for inactive forks
cutoff_date = utc.localize(datetime.datetime.now() - datetime.timedelta(days=inactive_days))
# Track forks processed and deleted
processed_forks = 0
deleted_forks = 0
try:
# Iterate through all repositories owned by the user
for repo in user.get_repos():
# Check if the repository is a fork
if repo.fork:
processed_forks += 1
# Get the last updated time and make it timezone aware
last_updated = repo.updated_at.replace(tzinfo=utc)
# Check if the fork is older than the cutoff date or repo in the list of
# repositories to delete
if last_updated < cutoff_date or repo.full_name in repos_to_delete:
try:
# Delete the inactive fork
repo.delete()
print(f"Deleted fork: {repo.full_name}")
deleted_forks += 1
except GithubException as e:
print(f"Error deleting fork {repo.full_name}: {e}")
# Print summary
print(f"\nSummary:")
print(f"Total forks processed: {processed_forks}")
print(f"Forks deleted: {deleted_forks}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
if __name__ == "__main__":
# Replace with your GitHub personal access token
GITHUB_TOKEN = os.getenv('GITHUB_TOKEN')
# Replace with your GitHub username
GITHUB_USERNAME = 'aaditkamat'
# List of repositories to delete (optional)
REPOS_TO_DELETE = [
"waka-readme-stats",
"www.passportjs.org",
"ZtM-Job-Board",
"data-pipeline-automation-with-github-actions-4503382"
]
# Optional: Customize the number of days for inactivity (default is 30)
cleanup_inactive_forks(GITHUB_TOKEN, GITHUB_USERNAME, REPOS_TO_DELETE, inactive_days=30)
python -m venv venv
source venv/bin/activate
pip install PyGithub pytz
python github_clean_fork.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment