預推

適用於 Git 1.8.2 及更高版本。

Version >= 1.8

可以使用預推鉤來防止推動。這有用的原因包括:阻止意外手動推送到特定分支,或者如果已建立的檢查失敗則阻止推送(單元測試,語法)。

只需在 .git/hooks/下建立一個名為 pre-push 的檔案和(gotcha alert ) 建立一個預推鉤,確保該檔案是可執行的:chmod +x ./git/hooks/pre-push

以下是漢娜·沃爾夫Hannah Wolfe)阻止推動掌握的一個例子 :

#!/bin/bash

protected_branch='master'  
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [ $protected_branch = $current_branch ]  
then  
    read -p "You're about to push master, is that what you intended? [y|n] " -n 1 -r < /dev/tty
    echo
    if echo $REPLY | grep -E '^[Yy]$' > /dev/null
    then
        exit 0 # push will execute
    fi
    exit 1 # push will not execute
else  
    exit 0 # push will execute
fi  

這是 Volkan Unsal 的一個例子,它確保 RSpec 測試在允許推送之前通過:

#!/usr/bin/env ruby
require 'pty'
html_path = "rspec_results.html"
begin
  PTY.spawn( "rspec spec --format h > rspec_results.html" ) do |stdin, stdout, pid|
  begin
    stdin.each { |line| print line }
  rescue Errno::EIO
  end
end
rescue PTY::ChildExited
  puts "Child process exit!"
end

# find out if there were any errors  
html = open(html_path).read
examples = html.match(/(\d+) examples/)[0].to_i rescue 0
errors = html.match(/(\d+) errors/)[0].to_i rescue 0
if errors == 0 then
  errors = html.match(/(\d+) failure/)[0].to_i rescue 0
end
pending = html.match(/(\d+) pending/)[0].to_i rescue 0

if errors.zero?
  puts "0 failed! #{examples} run, #{pending} pending"
  # HTML Output when tests ran successfully:
  # puts "View spec results at #{File.expand_path(html_path)}"
  sleep 1
  exit 0
else
  puts "\aCOMMIT FAILED!!"
  puts "View your rspec results at #{File.expand_path(html_path)}"
  puts
  puts "#{errors} failed! #{examples} run, #{pending} pending"
  # Open HTML Ooutput when tests failed
  # `open #{html_path}`
  exit 1
end

正如你所看到的,有很多可能性,但核心部分是如果好事發生的話,那就是發生了壞事。任何時候你都可以防止推送,你的程式碼將處於執行 git push... 之前的狀態。

使用客戶端掛鉤時,請記住,使用者可以通過在推送時使用選項“–no-verify”來跳過所有客戶端掛鉤。如果你依賴鉤子來強制執行流程,那麼你可能會被燒燬。

文件: https//git-scm.com/docs/githooks#_pre_push
官方樣本: https//github.com/git/git/blob/87c86dd14abe8db7d00b0df5661ef8cf147a72a3/templates/hooks–pre-push.sample