Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created February 13, 2018 10:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igniteflow/d9bcf00e143274eb15c79941818aaff2 to your computer and use it in GitHub Desktop.
Save igniteflow/d9bcf00e143274eb15c79941818aaff2 to your computer and use it in GitHub Desktop.
Git auto user. Switch git user/email based on active directory
#!/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, 'phil@work.com'),
PROJECTS_DIR('personal'): (GIT_USER_NAME, 'phil@personal.com'),
}
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