将 PowerShell 脚本作为 git hooks 运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5629261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 05:20:19  来源:igfitidea点击:

Running PowerShell scripts as git hooks

gitpowershellgithooks

提问by Erick T

Is it possible to run PowerShell scripts as git hooks?

是否可以将 PowerShell 脚本作为 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.

我在 PowerShell 提示符下运行 git,这应该没有任何区别,但我似乎无法让它们工作,因为钩子的名称没有扩展名,而 PowerShell 需要(AFAIK).ps1 扩展名。我不确定这是问题所在,还是其他问题。

Thanks, Erick

谢谢,埃里克

采纳答案by Joey

From what I gather the only option due to Git's design here would be a bash script calling PowerShell. Unfortunate, but then again, Git didn't place any thought on non-Linux compatibility.

由于 Git 的设计,我收集到的唯一选项是调用 PowerShell 的 bash 脚本。不幸的是,但话说回来,Git 没有考虑非 Linux 兼容性。

回答by Kim Ki Won

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

在 hooks 文件夹中将 pre-commit.sample 重命名为 pre-commit。然后在同一文件夹中制作 pre-commit.ps1 powershell 脚本文件。

#!/bin/sh
c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -Command -File '.git\hooks\pre-commit.ps1'

回答by Keith Hill

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

您可以将 PowerShell 脚本直接嵌入到钩子文件中。这是pre-commit我使用的钩子示例:

#!/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).

此示例需要 PowerShell Core,但因此它将跨平台运行(假设此文件在 Linux/macOS 上为 chmod +x)。

回答by Taran

Kim Ki Won's answer above didn't work for me, but it has upvotes so I'll assume it works for some people.

Kim Ki Won上面的答案对我不起作用,但它有赞成票,所以我假设它适用于某些人。

What worked for me was dropping the bin/sh and instead of executing using -File, executing the command directly:

对我有用的是删除 bin/sh,而不是使用 -File 执行,直接执行命令:

c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -Command .\.git\hooks\pre-commit.ps1

回答by TiernanO

I have been looking for this myself, and i found the following:

我自己一直在寻找这个,我发现了以下内容:

Git Powershell pre-commit hook(Source)

Git Powershell 预提交钩子源代码

## Editor's note: Link is dead as of 2014-5-2.  If you have a copy, please add it.

PHP Syntax check for git pre-commit in PowerShell(Soure)

PowerShell 中 git pre-commit 的 PHP 语法检查Soure

##############################################################################
#
# PHP Syntax Check for Git pre-commit hook for Windows PowerShell
#
# Author: Vojtech Kusy <[email protected]>
#
###############################################################################

### INSTRUCTIONS ###

# Place the code to file "pre-commit" (no extension) and add it to the one of 
# the following locations:
# 1) Repository hooks folder - C:\Path\To\Repository\.git\hooks
# 2) User profile template   - C:\Users\<USER>\.git\templates\hooks 
# 3) Global shared templates - C:\Program Files (x86)\Git\share\git-core\templates\hooks
# 
# The hooks from user profile or from shared templates are copied from there
# each time you create or clone new repository.

### SETTINGS ###

# Path to the php.exe
$php_exe = "C:\Program Files (x86)\Zend\ZendServer\bin\php.exe";
# Extensions of the PHP files 
$php_ext = "php|engine|theme|install|inc|module|test"
# Flag, if set to 1 git will unstage all files with errors, se to 0 to disable
$unstage_on_error = 0;

### FUNCTIONS ###

function php_syntax_check {
    param([string]$php_bin, [string]$extensions, [int]$reset) 

    $err_counter = 0;

    write-host "Pre-commit PHP syntax check:" -foregroundcolor "white"

    git diff-index --name-only --cached HEAD -- | foreach {             
        if ($_ -match ".*\.($extensions)$") {
            $file = $matches[0];
            $errors = & $php_bin -l $file           
            if ($errors -match "No syntax errors detected in $file") {
                write-host $file ": OK" -foregroundcolor "green"
            }
            else {              
                write-host $file ":" $errors -foregroundcolor "red"
                if ($reset) {
                    git reset -q HEAD $file
                    write-host "Unstaging" $file "..." -foregroundcolor "magenta"
                }
                $err_counter++
            }
        }
    }

    if ($err_counter -gt 0) {
       exit 1
    }    
}

### MAIN ###

php_syntax_check $php_exe $php_ext $unstage_on_error

The code is for a pre-commit hook, but you could modify it to do pretty much anything. Should help what you need to do!

该代码用于预提交挂钩,但您可以对其进行修改以执行几乎任何操作。应该帮助你需要做什么!

回答by Tudor Morar

This is my git hook on Windows located in .\git\hooks.

这是我在 Windows 上的 git hook,位于 .\git\hooks。

post-update

更新后

#!/bin/sh
c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy Bypass -Command '.\post-update.ps1'

Powershell script located in the project root folder (where you initially run git init). Powershell goes to another repository and calls pull, updating that repository.

位于项目根文件夹(您最初运行 git init 的位置)中的 Powershell 脚本。Powershell 转到另一个存储库并调用 pull,更新该存储库。

post-update.ps1

更新后.ps1

Set-Location "E:\Websites\my_site_test"
$env:GIT_DIR = 'E:\Websites\my_site_test\.git';
$env:GIT_EXEC_PATH= 'C:\Program Files (x86)\Git/libexec/git-core';
git pull

回答by No Refunds No Returns

Here's a starting PWSH script that I've been using for my PowerShell Git Hookssince reading Keith Hill's answer. Very nice.

这是PowerShell Git Hooks自阅读 Keith Hill 的答案以来我一直在使用的起始 PWSH 脚本。非常好。

#!/usr/bin/env pwsh

Process {
    Write-Information -MessageData "I Ran" -InformationAction Continue
}
Begin {
    Write-Information -MessageData "Beginning" -InformationAction Continue
}
End {
    Write-Information -MessageData "Ending" -InformationAction Continue

    Exit 0
}

I should also mention I share a single copy of hooks across all my repos. My repos all live in R:\Git and I created R:\Git\Hooks and used https://git-scm.com/docs/githooksto git config core.hooksPath=R:\Git\Hooksglobally. Life is good.

我还应该提到我在我的所有存储库中共享一个钩子副本。我的存储库都位于 R:\Git 中,我创建了 R:\Git\Hooks 并在全球范围内使用了https://git-scm.com/docs/githooksgit config core.hooksPath=R:\Git\Hooks。生活很好。

回答by Simon Tewsi

For the sake of completeness:

为了完整起见:

If you only have Windows PowerShell and not PowerShell Core installed then Keith Hill's neat answer doesn't work. The various answers that use a bash script to run PowerShell, passing in the path to the PowerShell script to run, are straight-forward and the way I chose to go in the end. However, I discovered there is another way:

如果您只安装了 Windows PowerShell 而没有安装 PowerShell Core,那么 Keith Hill 的简洁回答将不起作用。使用 bash 脚本运行 PowerShell 的各种答案,传入要运行的 PowerShell 脚本的路径,很简单,也是我最终选择的方式。但是,我发现还有另一种方法:

Create two files for the git hook, say pre-commit and pre-commit.ps1. The pre-commit.ps1 file is the file that PowerShell will run. The other pre-commit file (without a file extension) is empty apart from a PowerShell interpreter directive on the first line:

为 git hook 创建两个文件,比如 pre-commit 和 pre-commit.ps1。pre-commit.ps1 文件是 PowerShell 将运行的文件。除了第一行的 PowerShell 解释器指令外,另一个预提交文件(没有文件扩展名)是空的:

#!/usr/bin/env powershell

Git will run the pre-commit file, parse the PowerShell interpreter directive and run up PowerShell, passing in the path to the pre-commit file. PowerShell will assume the file passed in should have a ".ps1" extension. It will search for pre-commit.ps1 and, since you created a file with that name and extension, PowerShell will find it and run it.

Git 将运行预提交文件,解析 PowerShell 解释器指令并运行 PowerShell,传入预提交文件的路径。PowerShell 将假定传入的文件应具有“.ps1”扩展名。它将搜索 pre-commit.ps1,并且由于您创建了具有该名称和扩展名的文件,PowerShell 将找到它并运行它。

This approach is nice and simple but, in the end, I decided against it because it seemed a little "magical" and might have maintainers scratching their heads about how it works.

这种方法既好又简单,但最终我决定反对它,因为它看起来有点“神奇”,可能会让维护者对其工作原理感到挠头。