Feature image

通过Git Pre-Commit Hook执行MSBuild和MSTest

Git的pre-commit hook会在commit之前执行,当脚本的返回值不为0的时候,终止commit过程,因此可以把编译、测试、lint等workflow放到这一hook中,减少引入到版本库中的bug。

以下脚本用于调用MSBuild和MSTest对C#工程在commit前进行build和test。

1
#!/bin/sh
 
# Helper
safeRunCommand() {
    typeset cmd="$*"
    typeset ret_code
 
    echo cmd=$cmd
    eval $cmd
    ret_code=$?
    if [ $ret_code != 0 ]; then
        printf "Error : [%d] when executing command: '$cmd'" $ret_code
        exit $ret_code
    fi
}
 
# Path To MSBuild.exe
MSBuild="/c/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe"
# Path To MSTest.exe
MSTest="/d/Program\ Files\ \(x86\)/Microsoft\ Visual\ Studio\ 11.0/Common7/IDE/MSTest.exe"
# Get Project root path (without tailing /)
ProjectRoot="$(git rev-parse --show-toplevel)"
 
# Test Containers (without leading /)
Tests=(
    "ConsoleSharp.Tests/bin/Debug/ConsoleSharp.Tests.dll" 
    "Mirror.Test/bin/Debug/Mirror.Test.dll"
)
 
 
# Build
safeRunCommand $MSBuild $ProjectRoot/ConsoleSharp.sln
 
# Test
Args=("${Tests[@]/#//testcontainer:$ProjectRoot/}")
safeRunCommand $MSTest $(eval 'echo "${Args[*]}"')