Created
February 13, 2018 10:56
-
-
Save igniteflow/d9bcf00e143274eb15c79941818aaff2 to your computer and use it in GitHub Desktop.
Git auto user. Switch git user/email based on active 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/env python | |
""" | |
Checks and sets git username and email based on dir root matching | |
1. Add the following to ~/.bashrc | |
function cd { | |
builtin cd "$@" | |
if [ -d ".git" ] ; then | |
$HOME/.gitautouser | |
fi | |
} | |
2. Save this Python file to ~/.gitautouser and run `chmod +rx ~/.gitautouser` | |
""" | |
import subprocess | |
PROJECTS_DIR = lambda x: '/home/ptysoe/Projects/{}'.format(x) | |
GIT_USER_NAME = 'Phil Tysoe' | |
USER_CONFIG = { | |
# path (matched with startswith()): (username, email) | |
PROJECTS_DIR('work'): (GIT_USER_NAME, '[email protected]'), | |
PROJECTS_DIR('personal'): (GIT_USER_NAME, '[email protected]'), | |
} | |
def check_config(command_arg, value): | |
command = ['git', 'config', command_arg] | |
output = subprocess.check_output(command).replace('\n', '') | |
if output != value: | |
subprocess.check_output(command + [value]) | |
new_value = subprocess.check_output(command).replace('\n', '') | |
print('git {} updated from {} -> {}'.format( | |
command_arg, | |
output, | |
new_value | |
)) | |
def main(): | |
current_dir = subprocess.check_output('pwd') | |
for path_root in USER_CONFIG.keys(): | |
if current_dir.startswith(path_root): | |
username, email = USER_CONFIG[path_root] | |
check_config('user.name', username) | |
check_config('user.email', email) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment