Skip to content

Instantly share code, notes, and snippets.

@calvang
Last active August 21, 2021 22:28
Show Gist options
  • Save calvang/db755fa53df24ba86d487ba1765b3fc5 to your computer and use it in GitHub Desktop.
Save calvang/db755fa53df24ba86d487ba1765b3fc5 to your computer and use it in GitHub Desktop.
Migrate Github repositories from HTTP to SSH for a given username
import os
from sys import argv
import re
import subprocess
user = None
ignore = [
"node_modules",
".git",
"env",
"venv"
]
def switch_remotes(remotes, repo_path):
"""Set all HTTP remotes to use SSH"""
for remote, url in remotes.items():
print("...Replacing HTTP with SSH:", remote, url)
subprocess.run([
"git",
"-C",
repo_path,
"remote",
"set-url",
remote,
f"[email protected]:{url}"])
def http2ssh(root_dir, recursive=True):
"""Checks if git repository, switches from HTTP to SSH if possible"""
for item in os.listdir(root_dir):
item_path = os.path.join(root_dir, item)
item_git = os.path.join(item_path, ".git")
item_git_config = os.path.join(item_git, "config")
if os.path.exists(item_git_config):
print("Found git repo:", item_path)
with open(os.path.join(item_git, "config"), "r") as f:
lines = f.readlines()
remotes = {}
remote = None
# Find remotes to change to SSH
for line in lines:
if "[remote" in line:
remote = re.findall('"([^"]*)"', line)[0]
elif f"https://github.com/{user}" in line and remote is not None:
url = line.split("https://github.com/")[1].rstrip()
remotes[remote] = url
print("...Changes queued:", remote, url)
switch_remotes(remotes, item_path)
if os.path.isdir(item_path) and item not in ignore:
http2ssh(item_path, recursive)
if __name__ == "__main__":
if len(argv) == 3:
user = argv[2]
elif len(argv) == 2:
user = input("Enter github username: ")
else:
print("Usage: python http2ssh.py <root_dir> <gh_user>")
exit(0)
print("Updating repositories for", user)
http2ssh(argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment