如何在推前拉力

时间:2016-09-13 08:28:23

标签: git git-push git-pull

每次我想推送我的提交(git commit -m "message"git push origin <branch>),我都会拉(git pull origin <branch>)。 有没有办法让git在执行推送之前做一下拉? (在同一分支上)

4 个答案:

答案 0 :(得分:12)

执行此操作的Git方法是使用customize Git hooks

在您的情况下,您需要转到存储库中的.git/hooks目录,并添加名为pre-push的文件,这是您选择的脚本,例如: (本例中为bash)

#!/bin/bash

echo "pulling ..."
git pull

当您执行git push时和实际推送之前,将调用此脚本。

显然,这只是一个非常天真的样本,但我希望你能得到这个想法。此目录中已有样本。评论是否还有不清楚的地方。

答案 1 :(得分:5)

在推送之前你实际上不需要拉:如果远程端提交你没有本地提交,git push将失败并显示消息:

Pushing to git@yourserver:<user>/<repo>.git
To git@yourserver:<user>/<repo>.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/BigMeanCat/CMDA'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.

hint: See the 'Note about fast-forwards' in 'git push --help' for details.

如果您可以控制远程服务器,可以在那里设置:

git config --system receive.denyNonFastForwards true

更一般地说,您可以easily define an alias combining both commands

git config alias.pullpush '!git pull && git push'

如果拉动失败,则不会执行推送。

最后,您可以在名为

的bash脚本中组合任何命令序列
git-pullpush

(没有扩展名,可执行文件,存储在$PATH引用的文件夹中)

这将是一个常规的bash脚本(甚至可以在Windows上运行,因为它将由msys bash解释)

#!/bin/bash
# you can add any command you want
git pull && git push

你可以用git pullpush(就像别名)

来称呼它

答案 2 :(得分:5)

根据OP的评论,他们似乎试图避免他们最近的提交和远程提交之间的合并提交,这通常是由git pull在本地和远程时生成的历史已经分歧。

执行此操作的明确方法是首先获取和重新绑定,然后再推送。

git fetch
git rebase origin/master
git push

执行此操作的第二种方法是在调用--rebase时传递git pull

git pull --rebase

最后,可以通过设置配置使其成为git pull的默认行为。

git config --global pull.rebase true

答案 3 :(得分:3)

当您希望command2仅在command1成功(基本上返回0 )时运行时,请使用双&符号&&运行,夹在它们之间:

command1 && command2 

并且,要在command2成功之后运行command1,或者即使失败,请使用分号;运行:

command1 ; command2 

我使用前一个用于git pull && git push,后来用于git pull ; date

相关问题