Skip to content

Instantly share code, notes, and snippets.

@aeons
Created August 9, 2019 10:29
Show Gist options
  • Save aeons/96ba10653baf4adc75198ccdb174fe1b to your computer and use it in GitHub Desktop.
Save aeons/96ba10653baf4adc75198ccdb174fe1b to your computer and use it in GitHub Desktop.
Convert github https remote to corresponding ssh remote
#!/usr/bin/env python3
from collections import namedtuple
import re
import subprocess
import sys
Remote = namedtuple("Remote", ["name", "user", "repo"])
def parse_remotes():
regex = re.compile(
"([^\t]+)\thttps://(?:www\\.)?github.com/(.+)/(.*?)(?:.git)? \\(fetch\\)"
)
git_remote_p = subprocess.run(["git", "remote", "-v"], capture_output=True)
output = git_remote_p.stdout.decode().split("\n")
matches = [regex.search(s) for s in output]
return [Remote(*match.groups()) for match in matches if match is not None]
def confirm(remotes):
print("Changing the following remotes from https to ssh:")
for remote in remotes:
print(f"\t{remote.name}")
answer = input("Proceed? (y/n) ")
return answer.lower() == "y"
def convert_remote(remote):
new_url = f"[email protected]:{remote.user}/{remote.repo}.git"
subprocess.run(["git", "remote", "set-url", remote.name, new_url], check=True)
def main():
remotes = parse_remotes()
if len(sys.argv) > 1:
remotes = [r for r in remotes if r.name in sys.argv[1:]]
if not remotes:
print("No matching remotes found")
sys.exit()
proceed = confirm(remotes)
if proceed:
for remote in remotes:
convert_remote(remote)
print("Done")
else:
print("Doing nothing")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment