Pragmatically Transfer Codebase to new Git Account Repo without changing ownership of old Git Account Repo

Waleed JavedWaleed Javed
2 min read

If you want to transfer the repository and its code to another GitHub account programmatically, you can follow these steps:

  1. Clone the Repository: First, you need to clone the repository from your current account to your local machine using Git.

     git clone https://github.com/current_username/repository_name.git
    
  2. Change Remote URL: Next, navigate into the cloned repository and change the remote URL to point to the new GitHub account.

     cd repository_name
     git remote set-url origin https://github.com/new_username/repository_name.git
    
  3. Push Changes to New Repository: Now, push the code from your local machine to the repository under the new GitHub account.

     git push -u origin master
    
  4. Verify Transfer: After pushing the code, verify that the repository and its code have been transferred to the new GitHub account by visiting the repository page on GitHub.

If you are like me and don't want to do this manually,

Here's a Python script to automate these steps:

import os
import shutil
import subprocess

def transfer_repository(current_username, new_username, repository_name):
    # Clone the repository
    subprocess.run(['git', 'clone', f'https://github.com/{current_username}/{repository_name}.git'])

    # Change current directory to cloned repository
    os.chdir(repository_name)

    # Set new remote URL
    subprocess.run(['git', 'remote', 'set-url', 'origin', f'https://github.com/{new_username}/{repository_name}.git'])

    # Push changes to new repository
    subprocess.run(['git', 'push', '-u', 'origin', 'master'])

    print(f"Repository '{repository_name}' transferred from '{current_username}' to '{new_username}' successfully.")

    # Navigate back to the previous directory
    os.chdir('..')

if __name__ == "__main__":
    current_username = 'current_username'
    new_username = 'new_username'
    repository_name = 'repository_name'

    transfer_repository(current_username, new_username, repository_name)

Replace 'current_username', 'new_username', and 'repository_name' with your actual values.

This script automates the process of cloning the repository, changing the remote URL, and pushing the code to the new repository under the new GitHub account. Run this script, and it will transfer the repository and its code accordingly.

P.s Let's connect.
You can follow me on Hashnode, and I also share content on these platforms:

0
Subscribe to my newsletter

Read articles from Waleed Javed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Waleed Javed
Waleed Javed

Building Enterprise Softwares🚀 | Sharing insights on Linkedin/in/Waleed-javed