Skip to content

Instantly share code, notes, and snippets.

@shakir915
Created July 15, 2025 04:44
Show Gist options
  • Save shakir915/72f494993fe53a9386972a16ce94556f to your computer and use it in GitHub Desktop.
Save shakir915/72f494993fe53a9386972a16ce94556f to your computer and use it in GitHub Desktop.
remove recent (1 hour) github repo
#!/usr/bin/env python3
"""
Delete GitHub repositories created in the last hour.
Requires: pip install PyGithub
"""
import os
from datetime import datetime, timedelta, timezone
from github import Github
def delete_recent_repos():
# GitHub credentials
GITHUB_USERNAME = "shakir915" # UPDATE THIS
GITHUB_TOKEN = "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"
# Use hardcoded token or fallback to environment variable
token = GITHUB_TOKEN or os.getenv('GITHUB_TOKEN')
if not token:
print("Error: GITHUB_TOKEN not set in code or environment variable")
print("Create a personal access token at: https://github.com/settings/tokens")
return
# Initialize GitHub client
g = Github(token)
try:
# Get authenticated user
user = g.get_user()
print(f"Authenticated as: {user.login}")
# Calculate cutoff time (1 hour ago)
cutoff_time = datetime.now(timezone.utc) - timedelta(hours=1)
print(f"Looking for repos created after: {cutoff_time}")
# Get all repositories for the user
repos = user.get_repos(sort='created', direction='desc')
deleted_count = 0
for repo in repos:
# Check if repo was created in the last hour
if repo.created_at > cutoff_time:
print(f"Found recent repo: {repo.name} (created: {repo.created_at})")
# Ask for confirmation before deleting
confirm = input(f"Delete '{repo.name}'? (y/N): ").lower().strip()
if confirm == 'y':
try:
repo.delete()
print(f"✓ Deleted: {repo.name}")
deleted_count += 1
except Exception as e:
print(f"✗ Failed to delete {repo.name}: {e}")
else:
print(f"Skipped: {repo.name}")
else:
# Since repos are sorted by creation date (newest first),
# we can break here as older repos won't match
break
print(f"\nSummary: {deleted_count} repositories deleted")
except Exception as e:
print(f"Error: {e}")
def delete_recent_repos_batch():
"""
Alternative version that deletes all recent repos without individual confirmation
"""
# GitHub credentials
GITHUB_USERNAME = "shakir915" # UPDATE THIS
GITHUB_TOKEN = "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"
# Use hardcoded token or fallback to environment variable
token = GITHUB_TOKEN or os.getenv('GITHUB_TOKEN')
if not token:
print("Error: GITHUB_TOKEN not set in code or environment variable")
return
g = Github(token)
try:
user = g.get_user()
cutoff_time = datetime.now(timezone.utc) - timedelta(hours=1)
repos = user.get_repos(sort='created', direction='desc')
recent_repos = []
for repo in repos:
if repo.created_at > cutoff_time:
recent_repos.append(repo)
else:
break
if not recent_repos:
print("No repositories found created in the last hour")
return
print(f"Found {len(recent_repos)} repositories created in the last hour:")
for repo in recent_repos:
print(f" - {repo.name} (created: {repo.created_at})")
# Final confirmation for batch delete
confirm = input(f"\nDelete ALL {len(recent_repos)} repositories? (y/N): ").lower().strip()
if confirm == 'y':
deleted_count = 0
for repo in recent_repos:
try:
repo.delete()
print(f"✓ Deleted: {repo.name}")
deleted_count += 1
except Exception as e:
print(f"✗ Failed to delete {repo.name}: {e}")
print(f"\nSummary: {deleted_count}/{len(recent_repos)} repositories deleted")
else:
print("Operation cancelled")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
print("GitHub Repository Cleanup Tool")
print("=" * 40)
mode = input("Choose mode:\n1. Interactive (confirm each repo)\n2. Batch (confirm all at once)\nEnter choice (1/2): ").strip()
if mode == "1":
delete_recent_repos()
elif mode == "2":
delete_recent_repos_batch()
else:
print("Invalid choice. Using interactive mode.")
delete_recent_repos()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment