Skip to content

Instantly share code, notes, and snippets.

@tarocco
Last active March 20, 2017 00:05
Show Gist options
  • Save tarocco/dcb2f5e0a2b2572c5cf1be1bf978e15e to your computer and use it in GitHub Desktop.
Save tarocco/dcb2f5e0a2b2572c5cf1be1bf978e15e to your computer and use it in GitHub Desktop.
Use UTF-8 (en)coding, fixed double print
#!/usr/bin/env python
# coding=utf-8
'''
GitHub Switch User (ghsu)
Author: Tarocco 🐰
License: MIT License
'''
import sys
import os
import re
import subprocess
from subprocess import CalledProcessError, PIPE
import argparse
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def main():
parser = argparse.ArgumentParser(
description='Switch between GitHub identities'
)
parser.add_argument(
'--global',
dest='git_global',
action='store_true',
help='Switch user in global git configuration instead of work tree',
)
parser.add_argument(
'id',
help='Id file name suffix (this is your GitHub user name)',
)
parser.add_argument(
'email',
help='The email address associated with your GitHub account',
)
args = parser.parse_args()
git_global = args.git_global
id_ssh = args.id
email = args.email
if not git_global:
try:
subprocess.check_call(
['git', 'rev-parse', '--is-inside-work-tree'], stdout=PIPE)
except CalledProcessError as e:
# Error printed to stderror
return
if git_global:
subprocess.check_call(['git', 'config', '--global', 'user.name', id_ssh])
subprocess.check_call(['git', 'config', '--global', 'user.email', email])
l = ['Switched ', bcolors.WARNING, 'global', bcolors.ENDC, ' id to ', id_ssh]
else:
origin = subprocess.check_output(['git', 'remote', '-v']).decode()
for line in origin.splitlines():
remote, url, mode = re.split('\t| ', line)
url_new = re.sub(
r'^ghsu_?([^:]*)(:.*$)',
'ghsu_' + id_ssh.lower() + r'\2',
url)
subprocess.check_call(['git', 'remote', 'set-url', remote, url_new])
subprocess.check_call(['git', 'config', 'user.name', id_ssh])
subprocess.check_call(['git', 'config', 'user.email', email])
l = ['Switched id to ', id_ssh]
print(''.join(l));
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment