Skip to content

Instantly share code, notes, and snippets.

@Askill
Created March 5, 2024 18:28
Show Gist options
  • Save Askill/5dd0984acdbb75d29b5aad71919994e2 to your computer and use it in GitHub Desktop.
Save Askill/5dd0984acdbb75d29b5aad71919994e2 to your computer and use it in GitHub Desktop.
mirror all starred git repos to your private git server
import os
import subprocess
import requests
# Replace with your GitHub token
GITHUB_TOKEN = ''
# Replace with your private Git server's HTTPS URL
PRIVATE_GIT_SERVER = 'https://user_name:pat@domain/user_name/'
GIT_SERVER_USERNAME = 'john'
GIT_SERVER_PAT = ''
def get_starred_repos(user):
headers = {'Authorization': f'token {GITHUB_TOKEN}'}
url = f'https://api.github.com/users/{user}/starred'
repos = []
page = 1
while True:
response = requests.get(url, headers=headers, params={'page': page})
if response.status_code == 200:
repos.extend(response.json())
if len(response.json()) == 0:
break
page += 1
else:
break
return repos
def create_repo_on_forgejo(repo_url, repo_name):
data = {
'name': repo_name,
'description': repo_url,
'auto_init': True,
'private': True
}
url = f'https://domain/api/v1/user/repos?token={GIT_SERVER_PAT}' # Adjust the URL as per Forgejo's API
response = requests.post(url, json=data)
if response.status_code == 201:
return True
else:
print(f"Failed to create repository {repo_name} on Forgejo: {response.text}")
return False
def mirror_repo_to_forgejo(repo_url, destination):
# Clone the repository
subprocess.run(['git', 'clone', '--mirror', repo_url ], check=True)
# Change directory to the cloned repo
repo_name = repo_url.split('/')[-1]
os.chdir(repo_name)
# Push to the Forgejo Git server
subprocess.run(['git', 'remote', 'add', 'forgejo', destination], check=True)
subprocess.run(['git', 'push', 'forgejo', '--mirror'], check=True)
# Change back to the parent directory
os.chdir('..')
def main():
user = '' # Replace with the GitHub username
repos = get_starred_repos(user)
for repo in repos:
repo_url = repo['clone_url'] # Assuming HTTPS URL; adjust for SSH if necessary
repo_name = repo_url.split('/')[-1].replace('.git', '')
# Create the repository on Forgejo if it doesn't exist
if not create_repo_on_forgejo(repo_url, repo_name):
print(f"Skipping {repo_name} due to failure in creating it on Forgejo.")
continue
# Mirror the repository to Forgejo
mirror_repo_to_forgejo(repo_url, PRIVATE_GIT_SERVER + repo_name )
if __name__ == '__main__':
main()
@Askill
Copy link
Author

Askill commented Mar 7, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment