Запуск сценариев PowerShell в качестве крючков git

можно ли запускать сценарии PowerShell в качестве крючков git?

Я запускаю git в командной строке PowerShell, что не должно иметь никакого значения, но я не могу заставить их работать, так как крючки называются без расширений, и PowerShell нуждается (AFAIK).расширение ps1. Я не уверен, что это проблема или что-то еще.

спасибо, Эрик!--1-->

6 ответов


из того, что я собираю, единственным вариантом из-за дизайна Git здесь будет сценарий bash, вызывающий PowerShell. К сожалению, но опять же, Git не думал о совместимости с не-Linux.


переименовать зафиксироваться.образец для предварительной фиксации в папке hooks. Затем сделайте pre-commit.файл сценария PS1 powershell в той же папке.

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

Я сам искал это, и я нашел следующее:

git Powershell pre-commit hook (источник)

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

проверка синтаксиса PHP для предварительной фиксации git в PowerShell (Soure)

##############################################################################
#
# PHP Syntax Check for Git pre-commit hook for Windows PowerShell
#
# Author: Vojtech Kusy <wojtha@gmail.com>
#
###############################################################################

### 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

код предназначен для крючка предварительной фиксации, но вы можете изменить его, чтобы сделать почти все. Должно помочь то, что вам нужно сделать!


Kim Ki Wonответ выше не работал для меня, но у него есть upvotes, поэтому я предполагаю, что он работает для некоторых людей.

то, что сработало для меня, это удаление bin/sh и вместо выполнения using-File, выполнение команды напрямую:

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

Это мой крючок git на окнах, расположенных внутри .\ГИТ\крючки.

после обновления

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

сценарий Powershell, расположенный в корневой папке проекта (где вы изначально запускаете git init). Powershell переходит в другой репозиторий и вызывает pull, обновляя этот репозиторий.

после обновления.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

вы можете встроить сценарий 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 <name@acme.com>' to set it correctly."
    exit 1
}

exit 0

этот пример требует ядра PowerShell, но в результате он будет работать кросс-платформенный (предполагая, что этот файл был chmod +x на Linux/macOS).