Writing Git hooks in python/bash scripts [closed]

杀马特。学长 韩版系。学妹 提交于 2019-12-02 18:59:41

Here is an example of using Python for a hook. In general the hooks are language agnostic. You use the script to do some work or to exit with a 0/other return code to alter the flow of a git process.

The examples that come with git are written in shell script; there are some basic ones in .git/hooks of each repo and more advanced ones installed to /usr/share/doc/git-core/contrib/hooks.

There's also more info on the various hooks available via $ man githooks.

I found out that it's easy to write git hook on python. It's an example of post-receive hook on python. Provided example deploys master and develop branches in different folders (changes in master will be pushed to production website and changes in develop branch will be pushed to qa site)

#!/usr/bin/env python                                                                    
# -*- coding: UTF-8 -*-                                                                  
#post-receive                                                                            

import sys                                                                               
import subprocess                                                                        

# 1. Read STDIN (Format: "from_commit to_commit branch_name")                            
(old, new, branch) = sys.stdin.read().split()                                            

# 2. Only deploy if master branch was pushed                                             
if branch == 'refs/heads/master':                                                        
    subprocess.call('date >> ~/prod-deployment.log', shell=True)                         
    subprocess.call('GIT_WORK_TREE=/home/ft/app.prod git checkout master -f', shell=True)
    subprocess.call('cd ../../app.prod;bower update', shell=True)                        

#3. Only deploy if develop branch was pushed                                             
if branch == 'refs/heads/develop':                                                       
    subprocess.call('date >> ~/dev-deployment.log', shell=True)                          
    subprocess.call('GIT_WORK_TREE=/home/ft/app.dev git checkout develop -f', shell=True)
    subprocess.call('cd ../../app.dev;bower update', shell=True)                         
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!