如何检查远程存储库是否已更改,是否需要进行拉取?

现在我使用这个简单的脚本:

git pull --dry-run | grep -q -v 'Already up-to-date.' && changed=1

但它相当重。

有没有更好的办法?理想的解决方案是检查所有远程分支,并返回已更改分支的名称以及每个分支中新提交的数量。


当前回答

现在你也可以找到一个Phing脚本。

我需要一个解决方案来自动更新我的生产环境,我们非常高兴感谢我分享的这个脚本。

脚本是用XML编写的,需要Phing。

其他回答

下面是我的Bash脚本版本,它可以检查预定义文件夹中的所有存储库:

https://gist.github.com/henryiii/5841984

它可以区分常见的情况,比如需要拉和需要推,而且它是多线程的,所以取回是一次性发生的。它有几个命令,比如pull和status。

把一个符号链接(或脚本)放在你路径下的文件夹中,然后它就像git all status(等)一样工作。它只支持origin/master,但可以编辑或与其他方法组合。

运行git fetch (remote)来更新你的远程引用,它会告诉你什么是新的。然后,当您签出本地分支时,它将显示它是否落后于上游。

如果你运行这个脚本,它将测试当前分支是否需要git拉:

#!/bin/bash

git fetch -v --dry-run 2>&1 |
    grep -qE "\[up\s+to\s+date\]\s+$(
        git branch 2>/dev/null |
           sed -n '/^\*/s/^\* //p' |
                sed -r 's:(\+|\*|\$):\\\1:g'
    )\s+" || {
        echo >&2 "Current branch need a 'git pull' before commit"
        exit 1
}

将它作为Git钩子预提交来避免非常方便

Merge branch 'foobar' of url:/path/to/git/foobar into foobar

当你承诺之前拉。

要将此代码用作钩子,只需复制/粘贴脚本即可

.git/hooks/pre-commit

and

chmod +x .git/hooks/pre-commit

如果你想把task添加为crontab:

#!/bin/bash
dir="/path/to/root"
lock=/tmp/update.lock
msglog="/var/log/update.log"

log()
{
        echo "$(date) ${1:-missing}" >> $msglog
}

if [ -f $lock ]; then
        log "Already run, exiting..."
else
        > $lock
        git -C ~/$dir remote update &> /dev/null
        checkgit=`git -C ~/$dir status`
        if [[ ! "$checkgit" =~ "Your branch is up-to-date" ]]; then
                log "-------------- Update ---------------"
                git -C ~/$dir pull &>> $msglog
                log "-------------------------------------"
        fi
        rm $lock

fi
exit 0

使用简单的regexp:

str=$(git status) 
if [[ $str =~ .*Your\ branch\ is\ behind.*by.*commits,\ and\ can\ be\ fast-forwarded ]]; then
    echo `date "+%Y-%m-%d %H:%M:%S"` "Needs pull"
else
    echo "Code is up to date"
fi