Skip to content

Instantly share code, notes, and snippets.

@SimonWahlin
Created March 27, 2018 12:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SimonWahlin/91e974c9128f164ea840b6a8e09e7bd8 to your computer and use it in GitHub Desktop.
Save SimonWahlin/91e974c9128f164ea840b6a8e09e7bd8 to your computer and use it in GitHub Desktop.
Pre-Commit hook for git that will fix my user.email setting for me
#!C:\Program\ Files\PowerShell\6.0.0\pwsh.exe -File
$Pattern = '^origin\s+https://(\S+)\s\(push\)'
$Origin = (& 'git' 'remote' '-v') -match $Pattern | Where-Object -FilterScript {$_ -is [string]}
$RemoteDomain = if($Origin -match $Pattern) {$Matches[1]}
$Email = & 'git' 'config' '--get' 'user.email' | Where-Object -FilterScript {$_ -is [string]}
$DesiredEmail = switch -Wildcard ($RemoteDomain) {
'simonwahlin.visualstudio.com*' {
'simon@simonw.se'
break
}
'advaniase.visualstudio.com*' {
'simon.wahlin@knowledgefactory.se'
break
}
'github.com*' {
'simon.wahlin@gmail.com'
break
}
}
if($Email -ne $DesiredEmail) {
Write-Warning -Message 'WRONG EMAIL!'
Write-Warning -Message "Changing to: $DesiredEmail"
& 'git' 'config' 'user.email' $DesiredEmail
}
@rkeithhill
Copy link

@SimonWahlin I can't get the shebang to work as you've specified it. The PowerShell script is ignored until after the commit and then i get a prompt to open a text file. When I select notepad, the pre-commit script opens in it.

I have been able to get this to work:

#!/bin/sh
pwsh.exe -NoProfile -ExecutionPolicy Bypass -File .git/hooks/pre-commit.ps1

But it would be nice not to have to invoke sh just to launch PowerShell.

@rkeithhill
Copy link

Hmm, just tried this again with your approach and it works. Go figure.

@rkeithhill
Copy link

BTW I settled on this approach because I didn't like the brittleness of specifying the path to pwsh.exe on Windows:

#!/usr/bin/env pwsh

The only downside is that this still runs your profile scripts which in my case can really slow down processing of commits. I ended up putting this in my profile script for now:

# If run as part of a pre-commit hook do not run rest of profile
if (Test-Path Env:\GIT_INDEX_FILE) { return }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment