Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running PowerShell scripts as git hooks

Is it possible to run PowerShell scripts as git hooks?

I am running git in a PowerShell prompt, which shouldn't make any difference, but I can't seem to get them to work, as the hooks are named without extensions, and PowerShell needs (AFAIK) the .ps1 extension. I am not sure if that is the issue, or something else.

like image 537
Erick T Avatar asked Apr 12 '11 01:04

Erick T


People also ask

Can I use PowerShell for git?

The "common" recommendation for command-line git on Windows is to use the "git-bash" shell. However, git works nicely from the Windows PowerShell with one small addition...

Are PowerShell scripts cross platform?

Version 6 of PowerShell has gone cross-platform! That means you can run PowerShell on both Windows and Linux. Commonly referred to as PowerShell Core, version 6 is built on top of the . NET Core Runtime 2.0 and is completely open-source.

Do git hooks need EXE?

It turns out all you need to make a Git hook is an executable script in the Git hooks directory. By default (assuming you are in a Git repo) this is . git/hooks .


2 Answers

You can embed PowerShell script directly inside the hook file. Here is an example of a pre-commit hook I've used:

#!/usr/bin/env pwsh  # Verify user's Git config has appropriate email address if ($env:GIT_AUTHOR_EMAIL -notmatch '@(non\.)?acme\.com$') {     Write-Warning "Your Git email address '$env:GIT_AUTHOR_EMAIL' is not configured correctly."     Write-Warning "It should end with '@acme.com' or '@non.acme.com'."     Write-Warning "Use the command: 'git config --global user.email <[email protected]>' to set it correctly."     exit 1 }  exit 0 

This example requires PowerShell Core but as a result it will run cross-platform (assuming this file has been chmod +x on Linux/macOS).

like image 82
Keith Hill Avatar answered Oct 02 '22 22:10

Keith Hill


Rename pre-commit.sample to pre-commit in hooks folder. Then make pre-commit.ps1 powershell script file in same folder.

#!/bin/sh c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -File '.git\hooks\pre-commit.ps1' 
like image 22
Kim Ki Won Avatar answered Oct 03 '22 00:10

Kim Ki Won