Created
July 7, 2023 05:39
-
-
Save BaksiLi/3ad3f68acce64e56e38a71e8f5b2fe9e to your computer and use it in GitHub Desktop.
zsh function for switching git users (for team, multiple accounts etc.)
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
function git_user_switcher() { | |
# Define an associative array to store the user settings | |
typeset -A -g git_users | |
# Add the users to the dictionary | |
# Format: username "name email gpg_key" | |
git_users=( | |
adam "adam [email protected]" | |
) | |
function git-user() { | |
# If no arguments are provided, print the current git user info | |
if [ $# -eq 0 ]; then | |
if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then | |
if git config user.signingkey > /dev/null; then | |
echo "Git user: $(git config user.name) <$(git config user.email)>, GPG Key: $(git config user.signingkey)" | |
else | |
echo "Git user: $(git config user.name) <$(git config user.email)>" | |
fi | |
else | |
echo "Not a git repository" | |
fi | |
return | |
fi | |
# Check if the user exists in the dictionary | |
if [[ -z "${git_users[$1]}" ]]; then | |
echo "User $1 not found" | |
return 1 | |
fi | |
# Check if the current directory is a git repository | |
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then | |
echo "Not a git repository" | |
return 1 | |
fi | |
# Split the user settings into an array | |
local user_settings=("${(@s/ /)git_users[$1]}") | |
# Set the git config | |
git config user.name "${user_settings[1]}" | |
git config user.email "${user_settings[2]}" | |
# If a GPG key is provided, set it | |
if [ -n "${user_settings[3]}" ]; then | |
git config user.signingkey "${user_settings[3]}" | |
echo "Git user has been set to: ${user_settings[1]} <${user_settings[2]}>, GPG Key: ${user_settings[3]}" | |
else | |
# If no GPG key is provided, unset it | |
git config --unset user.signingkey | |
echo "Git user has been set to: ${user_settings[1]} <${user_settings[2]}>" | |
fi | |
} | |
}; git_user_switcher |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment