GitNotes.24-1.md
본 문서는 Git Notes for Professionals (라이센스:CC-BY-SA) 를 한글로 번역한 문서입니다. 번역상 오류가 있을 수 있으므로 정확한 내용은 원본 문서를 참고하세요.

Section 24.1: Pre-push hook

Git 1.8.2 혹은 그 이후 버전에서 사용 가능하다.

Pre-push hook 은 push 작업이 곧바로 진행되는 것을 (going through) 방지한다. 이러한 작업이 필요한 경우의 예는: 특정 브랜치로의 의도치 않은 수동 push 를 방지하거나, 미리 설정된 검사 (단위테스트나 문법 검사 등) 들이 실패한 경우 push 를 막는 경우 등이 있을 수 있다

pre-push hook 은 간단하게 'pre-push' 라는 이름을 갖는 파일을 .git/hooks/ 디렉토리 아래에 생성하고 이 파일이 실행 가능한 권한을 부여하는 것만으로 설정할 수 있다: chmod +x ./git/hooks/pre-push.

Hannah Wolfe 의 master 로의 push 를 방지하는 예제가 아래 나와있다:

#!/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 의 push 하기 전 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

보다시피, pre-push hook 의 활용 가능성은 무궁 무진하나, 그 핵심은 바로 바람직한 일이 일어났을 때는 0 으로 exit 하고, 바람직하지 않은 일이 일어났을 때는 1로 exit 하는 것이다. 어떠한 상황이건 1로 exit 하게 되면 push 작업은 수행이 가로막힐 것이며 사용자의 코드는 git push.... 명령어 수행 직전의 상태로 유지될 것이다.

클라이언트 측 hook (client side hook) 사용시 유의할 점은, 사용자가 push 수행시에 "--no-verify" 옵션을 주는 것만으로도 모든 클라이언트 측 hook 들을 건너뛸 수 있다는 점이다. 만약 특정 처리 (process)를 강제하기 위해 클라이언트 측 hook 에만 의존하고 있다면, 예기치 못한 문제에 직면할 수 있다.

문서: https://git-scm.com/docs/githooks#_pre_push

공식 샘플:

https://github.com/git/git/blob/87c86dd14abe8db7d00b0df5661ef8cf147a72a3/templates/hooks--pre-push.sample

[출처] https://books.goalkicker.com/GitBook/ (CC BY-SA)

반응형

+ Recent posts