Skip to content

Instantly share code, notes, and snippets.

@takase1121
Last active March 3, 2021 12:23
Show Gist options
  • Save takase1121/d6b4bb85b5b184736b05fb9c3e7b9653 to your computer and use it in GitHub Desktop.
Save takase1121/d6b4bb85b5b184736b05fb9c3e7b9653 to your computer and use it in GitHub Desktop.
Make sure you always has GitHub email setup correctly
#!/usr/bin/env sh
if [ ! -d "./.git" ]; then
echo "Not a git repository"
exit 1
fi
STORE_PATH="$HOME/.config/github_emails"
USER_PATH="$STORE_PATH/$1"
GH_USERNAME=$(git config --get user.name)
if [ $? -eq 1 ] || [ "$GH_USERNAME" != "$1" ]; then
git config user.name "$1"
echo "Set username to $1"
fi
if [ ! -d "$STORE_PATH" ]; then
echo "Creating emails store"
mkdir -p "$STORE_PATH"
fi
if [ -f "$USER_PATH" ]; then
REAL_EMAIL=$(cat "$USER_PATH")
else
JSON=$(curl -sSL "https://api.github.com/users/$1")
if [ $? -ne 0 ]; then
echo "Unable to fetch user info. Aborting."
exit 1
fi
REAL_EMAIL="$(echo "$JSON" | jq .id)+$1@users.noreply.github.com"
echo "$REAL_EMAIL" > "$USER_PATH"
chmod 600 "$USER_PATH"
fi
GH_EMAIL=$(git config --get user.email)
if [ $? -eq 1 ] || [ "$GH_EMAIL" != "$REAL_EMAIL" ]; then
git config user.email "$REAL_EMAIL"
echo "Set email to $REAL_EMAIL"
fi
function Invoke-Git() {
function Get-Email() {
# try finding email from file
$cachedir = "$(Split-Path -Parent $PROFILE)/.github_users"
New-Item -Path $cachedir -ItemType "directory" -Force | Out-Null
$usercache = "$($cachedir)/user_$($env:GITHUB_USER)"
if (Test-Path -Path $usercache) {
Get-Content -Path $usercache
} else {
$req = Invoke-WebRequest -UseBasicParsing -URI "https://api.github.com/users/$($env:GITHUB_USER)" | ConvertFrom-Json
$email = "$($req.id)+$($req.login)@users.noreply.github.com"
Out-File -FilePath $usercache -InputObject $email -NoNewline | Out-Null
$email
}
}
# we only do stuff if user wants to commit
if ($args[0] -eq "commit") {
# check if remote is github
$remote = (&git remote -v)
if ($remote -match 'https://github.com') {
Write-Host "Not so fast, we'll make sure you set up your GitHub email first."
$setemail = (&git config user.email)
$setname = (&git config user.name)
$ghemail = Get-Email
if ($setemail -ne $ghemail -or $setname -ne $env:GITHUB_USER) {
Write-Output "Username or email is different than expected. Changing it for you :)"
&git config user.email $ghemail
&git config user.name $env:GITHUB_USER
Write-Output "Got you covered. Now let's move on, shall we?"
}
}
}
git_old @args
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment