Skip to content

Instantly share code, notes, and snippets.

@zikani03
Last active September 15, 2021 19:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zikani03/95b9c191893547f9ccb70ab7dc152aba to your computer and use it in GitHub Desktop.
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
#!/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://username@github.com/username/repo1.git
$ python chremote.py --d /path/to/directory
$ cd repo1
$ git remote get-url origin
git@github.com: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