在 python/bash 脚本中编写 Git 钩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3311869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing Git hooks in python/bash scripts
提问by myusuf3
I have recently needed to write git hooks, for all commits to reference a particular ticket.
我最近需要编写 git hooks,以便所有提交都引用特定的票证。
I was hoping for a place to start learning. All the stuff in the pro git book is written in Ruby. Since Ruby is not my strong suit, can anybody share tutorials about git hooks written in other languages? (I'd particularly prefer Python or Bash scripts.)
我希望有一个地方开始学习。pro git 书中的所有内容都是用 Ruby 编写的。由于 Ruby 不是我的强项,有人可以分享有关用其他语言编写的 git hooks 的教程吗?(我特别喜欢 Python 或 Bash 脚本。)
采纳答案by Peter Loron
回答by intuited
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
.
git自带的例子都是用shell脚本写的;.git/hooks
每个 repo 中都有一些基本的,而更高级的则安装到/usr/share/doc/git-core/contrib/hooks
.
There's also more info on the various hooks available via $ man githooks
.
还有更多关于各种钩子的信息,可以通过$ man githooks
.
回答by Roman Podlinov
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)
我发现在 python 上编写 git hook 很容易。这是python上的post-receive hook的一个例子。提供的示例将 master 和 develop分支部署在不同的文件夹中(master 中的更改将推送到生产网站,而 develop 分支中的更改将推送到 qa 站点)
#!/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)