Skip to content

Instantly share code, notes, and snippets.

@PatrickChoDev
Created December 13, 2024 18:02
Show Gist options
  • Save PatrickChoDev/ad5cf5d1b455084b72bff24a0a453059 to your computer and use it in GitHub Desktop.
Save PatrickChoDev/ad5cf5d1b455084b72bff24a0a453059 to your computer and use it in GitHub Desktop.
gitprofile is the manager of git profile for switching quickly between config
#!/bin/zsh
# This script is used to switch between different git profiles
# Read the profile name from the command line argument
profile_name=$1
if [ "$profile_name" = "-h" ] || [ "$profile_name" = "--help" ]; then
echo "Usage: gitprofile <profile_name> [-c|--config <config_file>]"
echo "Switch between different git profiles"
echo "Options:"
echo " -c, --config <config_file> Override the default config file path"
exit 0
fi
if [ "$profile_name" = "-v" ] || [ "$profile_name" = "--version" ]; then
echo "gitprofile 1.0.0"
exit 0
fi
if [ "$profile_name" = "" ]; then
echo "Profile name not provided. Please provide a profile name."
exit 1
fi
# Check if --file option is provided to override the config file path
if [ "$2" = "-c" ] || [ "$2" = "--config" ]; then
config_file=$3
else
config_file="$HOME/.config/gitprofile.toml"
fi
# Check if the config file exists, if not then create it
if [ ! -f "$config_file" ]; then
touch "$config_file"
fi
echo -e "\033[90mLoading profile $profile_name from $config_file\033[0m"
# Read the config from the TOML template file using gsed if available, otherwise use sed
if command -v gsed >/dev/null 2>&1; then
config=$(gsed -n "/^\[$profile_name\]/,/^\[/p" $config_file | gsed '/^\[/d')
else
config=$(sed -n "/^\[$profile_name\]/,/^\[/p" $config_file | sed '/^\[/d')
fi
# Check if the profile exists
if [ -z "$config" ]; then
echo "Profile not found. Please add the profile to $config_file"
exit 1
fi
# Set the config for the local directory
while IFS= read -r line; do
# Skip empty lines
[ -z "$line" ] && continue
# Extract and clean up key/value
key=$(echo "${line%%=*}" | xargs)
value=$(echo "${line#*=}" | xargs | sed 's/^"\(.*\)"$/\1/')
git config --local "$key" "$value"
echo -e "Set \033[34m$key\033[0m as \033[91m$value\033[0m"
done <<< "$config"
# save this file to ~/.config/gitprofile.toml
# this is example of toml config, other modules than user is working fine!
[profile1_name]
user.name = Name ishere
user.email = [email protected]
user.signingkey = <your gpgsign>
user.gpgsign = true
[profile2_name]
# Replacing
user.name = Name2 isthere
user.email = [email protected]
# Leave blank for removal
user.signingkey =
# No key defined is no replace (user.gpgsign will still true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment