bash - 如何实时从远程 git 仓库获取推送通知?

标签 bash cron bitbucket githooks

我有一个远程存储库 (bitbucket)、一个服务器存储库 (linux) 和许多本地存储库(开发人员)。

我希望服务器在某些开发人员更改远程分支时得到通知。

直到现在,我尝试使用在服务器的 cron 中声明的 bash 脚本,但最小分辨率为 1 分钟,因此使其适应实时似乎非常棘手。但是,我的方法是这样的:

path=/some/dir/

# something new in remote
if git fetch origin && [ `git rev-list HEAD...origin/master --count` != 0 ]
then
    echo 'Remote repository has changed. Pull needed' &>>$path/git-backup.log
    echo $d >> $path/git-backup.log
    git merge origin/master &>>$path/git-backup.log
fi

最佳答案

终于解决了

在 bitbucket 端

您只需声明一个指向服务器的 Webhook。

enter image description here

在服务器端

您需要一种机制来一直监听某个端口。这是一直在运行的 celery_listengit.py 的内容:

import subprocess
import threading
from tasks import git_pull
from flask import *

app = Flask(__name__)


@app.route("/", methods=['GET', 'POST'])
def listen_git4pull():

    # Range of bitbucket IP Addresses that we know.
    trusted = ['131.103.20', '165.254.145', '04.192.143']

    incoming = '.'.join(str(request.remote_addr).split('.')[:-1])
    if incoming in trusted:
        git_pull.delay()
        # OK
        resp = Response(status=200, mimetype='application/json')
    else:
        # HTTP not authorized
        resp = Response(status=403, mimetype='application/json')

    return resp


class CeleryThread(threading.Thread):
    def run(self):
        error_message = ('Something went wrong when trying to '
                         'start celery. Make sure it is '
                         'accessible to this script')
        command = ['celery',
                   '-A',
                   'tasks',
                   'worker',
                   '--loglevel=info']
        try:
            _ = subprocess.check_output(command)
        except Exception:
            raise Exception(error_message)


if __name__ == '__main__':
    celery_thread = CeleryThread()
    celery_thread.start()
    app.run(host='0.0.0.0')

这是任务的内容,其中声明了 git_pull() 函数。这必须延迟,因为 git.pull() 可能需要很多时间,所以它必须在服务器响应 HTTP OK 状态后运行:

from git import *
from celery.app.base import Celery


app = Celery('tasks',
             backend='amqp://guest@localhost//',
             broker='amqp://guest@localhost//')

app.conf.update(
    CELERY_ACCEPT_CONTENT=['json'],
    CELERY_TASK_SERIALIZER='json',
    CELERY_RESULT_SERIALIZER='json',)

@app.task
def git_pull():
    repo = Repo('.')
    o = repo.remotes.origin
    o.fetch()
    o.pull()

关于bash - 如何实时从远程 git 仓库获取推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683497/

相关文章:

java - 无法使用 Java 运行 bash shell

bash - 64 位 Ubuntu 上的脚本问题

swift - Cron 作业与安全规则

git - bitbucket git 无法锁定 ref

jenkins - 如何使用 Jenkins 中的 Bitbucket Team/Project 插件扫描项目中的存储库

bash - 有没有办法中断 shell 命令但继续包含它的管道?

git - 从 Git bash 调用 Notepad++

spring - 应用程序启动时的 Quartz 一次性作业

ruby - 无法让 Cron 处理这个 Ruby 脚本

php - Bitbucket 管道部署忽略带有 ftp 上传的供应商文件夹