Skip to content

Instantly share code, notes, and snippets.

@pgarciacamou
Created April 28, 2019 23:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pgarciacamou/3b67320e2940c8d7fa3d7bbd73873106 to your computer and use it in GitHub Desktop.
Save pgarciacamou/3b67320e2940c8d7fa3d7bbd73873106 to your computer and use it in GitHub Desktop.
Use `.gitemail` and `.npmregistry` files to switch user per project.
# Automatically assign local git user email
# This code expects the following
# file ".gitemail" to exist and contain only 1 row with an email
# file ".npmregistry" to exist and contain only 1 row with the registry url
#
# Note: if any of the files don't exist then the default will be used
setup-dev-user() {
local expected_git_email=$(grep -hs ^ ./.gitemail)
local current_git_email="$(git config user.email)"
local default_git_email="example@company.com"
local expected_npm_registry=$(grep -hs ^ ./.npmregistry)
local current_npm_registry="$(npm config get registry)"
local default_npm_registry="https://npm.company.com/"
if [ -n "$expected_git_email" ]; then
if [ "$current_git_email" != "$expected_git_email" ]; then
git config user.email "${expected_git_email}"
echo "Git user set to \"$(git config user.name) <$(git config user.email)>\""
fi
elif [ "$current_git_email" != "$default_git_email" ]; then
git config user.email "$default_git_email"
echo "Git user reverted to \"$(git config user.name) <$(git config user.email)>\""
fi
if [ -n "$expected_npm_registry" ]; then
if [ "$current_npm_registry" != "$expected_npm_registry" ]; then
npm config set registry "${expected_npm_registry}"
echo "Npm registry set to $(npm config get registry)"
fi
elif [ "$current_npm_registry" != "$default_npm_registry" ]; then
npm config set registry "$default_npm_registry"
echo "Npm registry reverted to $(npm config get registry)"
fi
}
add-zsh-hook chpwd setup-dev-user
setup-dev-user

This little script must be attached at the end of the .zshrc

What does it do?

It checks in the current directory for file .gitemail and .npmregistry.

Disadvantages

Does not search recursively. I didn't implement that because:

  1. This fit my purposes at the time of writting
  2. I'm not super zsh script-savy
  3. This script is executed on every change of directory (e.g. cd ../) and a recursive find might slow the terminal.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment