Last active
September 15, 2021 19:45
-
-
Save zikani03/95b9c191893547f9ccb70ab7dc152aba to your computer and use it in GitHub Desktop.
chremote.py: Change https -> ssh remote urls for GitHub repos in a directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
"""Changes remote urls for repositories in a given directory to SSH remotes | |
for repositories in a given directory. Since GitHub removed password based auth. | |
Run it using: `python chremote.py --d /path/to/directory` | |
Basic interaction is outlined below; | |
``` | |
$ ls /path/to/directory | |
repo1 repo2 repo3 repo4 | |
$ cd repo1 | |
$ git remote get-url origin | |
https://[email protected]/username/repo1.git | |
$ python chremote.py --d /path/to/directory | |
$ cd repo1 | |
$ git remote get-url origin | |
[email protected]:username/repo1.git | |
``` | |
@author [zikani03](https://github.com/zikani03) | |
""" | |
import argparse | |
import os | |
import re | |
import subprocess | |
def change_remotes(dir_name, remote_name): | |
res = subprocess.run(f'git remote get-url {remote_name}'.split(' '), capture_output=True) | |
remote_url = str(res.stdout, encoding='utf-8').strip() | |
if remote_url.startswith('git@'): | |
return True | |
git_ssh_url = re.sub(r'http(s)?://(\w+@)?', 'git@', remote_url).replace('github.com/', 'github.com:') | |
if subprocess.run(f'git remote set-url {remote_name} {git_ssh_url}'.split(' ')): | |
return True | |
return False | |
def change_remotes_in_dir(dir_name): | |
abs_path_to_root_dir = os.path.abspath(dir_name) | |
files = [os.path.join(abs_path_to_root_dir, f) for f in os.listdir(abs_path_to_root_dir)] | |
for f in files: | |
if not os.path.isdir(f): | |
continue | |
os.chdir(f) | |
if os.path.exists(os.path.join(f, '.git')): | |
change_remotes(f, 'origin') | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
parser.add_argument("--d", help='Directory containing git repos') | |
args = parser.parse_args() | |
change_remotes_in_dir(args.d) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment