git 服务器端钩子

发布于 2024-09-12 08:59:22 字数 2871 浏览 5 评论 0原文

在服务器上运行以下 python 脚本寻找推送的提交信息时遇到问题,确保它遵循特定的语法,我无法从用户那里获取输入,这就是用户名和密码被硬编码的原因。我现在也无法获取此特定推送之前发生的提交消息列表。

#!/usr/bin/python

import SOAPpy 
import getpass 
import datetime
import sys
import re
import logging
import os


def login(x,y):
    try:
        auth = soap.login(x, y)
        return auth
    except:
          sys.exit( "Invalid username or password")

def getIssue(auth,issue):
    try:
        issue = soap.getIssue(auth, issue)
    except:
        sys.exit("No issue of that type found : Make sure all PRs are vaild jira PRs")

def git_get_commit_msg(commit_id):
    return get_shell_cmd_output("git rev-list --pretty --max-count=1 " + commit_id)

def git_get_last_commit_id():
    return get_shell_cmd_output("git log --pretty=format:%H -1")

def getCommitText():
    commit_msg_filename = sys.argv[1]
    try:
        commit_msg_text = open(commit_msg_filename).read()
        return commit_msg_text
    except:
        sys.exit("Could not read commit message")

def git_get_array_of_commit_ids(start_id, end_id):
    output = get_shell_cmd_output("git rev-list " + start_id + ".." + end_id)
    if output == "":
        return None
    commit_id_array = string.split(output, '\n')
    return commit_id_array

def get_shell_cmd_output(cmd):
    try:
        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        return proc.stdout.read().rstrip('\n')
    except KeyboardInterrupt:
        logging.info("... interrupted")

    except Exception, e:
        logging.error("Failed trying to execute '%s'", cmd)

def findpattern(commit_msg):
    pattern = re.compile("\w\w*-\d\d*")
    group = pattern.findall(commit_msg)
    print group
    found = len(group)
    found =0
    issues = 0
    for match in group:
            auth = soap.login(jirauser,passwd)
            getIssue(auth,match)
            issues = issues + 1
            found+=1
    if found ==0:
        sys.exit("No issue patterns found.")

    print "Retrieved issues: " + str(issues)  

def update():
    print sys.argv[2]
    print sys.argv[3]
    old_commit_id = sys.argv[2]
    new_commit_id = sys.argv[3]
    commit_id_array = git_get_array_of_commit_ids(old_commit_id, new_commit_id)
    for commit_id in commit_id_array:
        commit_text = git_get_commit_msg(commit_id)
        findpattern(commit_text)

soap = SOAPpy.WSDL.Proxy('some url')
# this line if for repointing the input from dev/null
#sys.stdin = open('/dev/tty', 'r') # this fails horribly.
#ask user for input
#jirauser = raw_inp
#("Username for jira: ")
jirauser = "username"
passwd = "987654321"
#passwd = getpass.getpass("Password for %s: " % jirauser)
login(jirauser,passwd)
#commit_msg = getCommitText()
#findpattern(commit_msg)
update()

此代码的预期目标是检查本地所做的提交,并解析它们以获取预期的模式,以及检查 jira 中的 PR 是否存在。它是一个服务器端挂钩,在推送到存储库时被激活。

任何关于编写 python hooks 的提示将不胜感激。请并谢谢你。

I am running into a problem when running the follow python script on the server looking for commit information for the push making sure it follows a particular syntax, I am unable to get input from the user which is why the username and password are hard coded. I am now also unable to get the list of commit message that occurred before this particular push.

#!/usr/bin/python

import SOAPpy 
import getpass 
import datetime
import sys
import re
import logging
import os


def login(x,y):
    try:
        auth = soap.login(x, y)
        return auth
    except:
          sys.exit( "Invalid username or password")

def getIssue(auth,issue):
    try:
        issue = soap.getIssue(auth, issue)
    except:
        sys.exit("No issue of that type found : Make sure all PRs are vaild jira PRs")

def git_get_commit_msg(commit_id):
    return get_shell_cmd_output("git rev-list --pretty --max-count=1 " + commit_id)

def git_get_last_commit_id():
    return get_shell_cmd_output("git log --pretty=format:%H -1")

def getCommitText():
    commit_msg_filename = sys.argv[1]
    try:
        commit_msg_text = open(commit_msg_filename).read()
        return commit_msg_text
    except:
        sys.exit("Could not read commit message")

def git_get_array_of_commit_ids(start_id, end_id):
    output = get_shell_cmd_output("git rev-list " + start_id + ".." + end_id)
    if output == "":
        return None
    commit_id_array = string.split(output, '\n')
    return commit_id_array

def get_shell_cmd_output(cmd):
    try:
        proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        return proc.stdout.read().rstrip('\n')
    except KeyboardInterrupt:
        logging.info("... interrupted")

    except Exception, e:
        logging.error("Failed trying to execute '%s'", cmd)

def findpattern(commit_msg):
    pattern = re.compile("\w\w*-\d\d*")
    group = pattern.findall(commit_msg)
    print group
    found = len(group)
    found =0
    issues = 0
    for match in group:
            auth = soap.login(jirauser,passwd)
            getIssue(auth,match)
            issues = issues + 1
            found+=1
    if found ==0:
        sys.exit("No issue patterns found.")

    print "Retrieved issues: " + str(issues)  

def update():
    print sys.argv[2]
    print sys.argv[3]
    old_commit_id = sys.argv[2]
    new_commit_id = sys.argv[3]
    commit_id_array = git_get_array_of_commit_ids(old_commit_id, new_commit_id)
    for commit_id in commit_id_array:
        commit_text = git_get_commit_msg(commit_id)
        findpattern(commit_text)

soap = SOAPpy.WSDL.Proxy('some url')
# this line if for repointing the input from dev/null
#sys.stdin = open('/dev/tty', 'r') # this fails horribly.
#ask user for input
#jirauser = raw_inp
#("Username for jira: ")
jirauser = "username"
passwd = "987654321"
#passwd = getpass.getpass("Password for %s: " % jirauser)
login(jirauser,passwd)
#commit_msg = getCommitText()
#findpattern(commit_msg)
update()

The intended goal of this code is to check the commits made locally, and to parse through them for the intended pattern, as well as checking the in jira if that PR exists. it is a server side hook that get activated on a push to the repository.

Any tips on writing python hooks would be appreciated. Please and thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赏烟花じ飞满天 2024-09-19 08:59:22

我建议你看看 gitorious (http://gitorious.org/gitorious)。
他们使用 ssh 来处理身份验证和权限管理(获取 ssh 给出的用户名)。
他们在 git 存储库上也有一些钩子。我想这可以帮助了解他们如何使用 ruby​​ 处理 git hooks。

I suggest that you have a look at gitorious (http://gitorious.org/gitorious).
They use ssh to handle authentication and rights management (getting the username given by ssh).
They also have some hooks on git repositories. I guess it could help to see how they are processing git hooks using ruby.

深白境迁sunset 2024-09-19 08:59:22

当你的更新钩子触发时,服务器已经有了新的提交:问题是你的钩子是否允许有问题的引用移动。您想要本地(发送)存储库中的哪些信息?

对于凭据问题,请通过单个用户将每个人集中起来。例如,GitHub 使用 git 用户执行此操作,这就是为什么他们的 SSH URL 以 [电子邮件受保护]:...。然后在 ~git/.ssh/authorized_keys 中,将用户名与每个密钥相关联。请注意,以下内容应位于一行中,但出于演示目的而被换行。

no-agent-forwarding,no-port-forwarding,no-pty,no-X11-forwarding,
command="env myuser=gbgcoll /usr/bin/git-shell -c \"${SSH_ORIGINAL_COMMAND:-}\""
ssh-rsa AAAAB...

现在,为了查看谁正在尝试进行更新,您的钩子会检查 $myuser 环境变量。

这不会为您提供每个用户的 Jira 凭据。要解决该问题,请创建一个对所有内容具有只读访问权限的虚拟 Jira 帐户,并在挂钩中对该 Jira 帐户的凭据进行硬编码。这允许您验证给定的 PR 是否存在。

By the time your update hook fires, the server has the new commits: the question is whether your hook will allow the ref in question to move. What information from the local (sending) repository do you want?

For the credentials issue, funnel everyone through a single user. For example, GitHub does it with the git user, which is why their SSH URLs begin with [email protected]:.... Then in ~git/.ssh/authorized_keys, associate a username with each key. Note that the following should be on a single line but is wrapped for presentation purposes.

no-agent-forwarding,no-port-forwarding,no-pty,no-X11-forwarding,
command="env myuser=gbgcoll /usr/bin/git-shell -c \"${SSH_ORIGINAL_COMMAND:-}\""
ssh-rsa AAAAB...

Now to see who's trying to do the update, your hook examines the $myuser environment variable.

This doesn't give you each user's Jira credentials. To solve that issue, create a dummy Jira account that has read-only access to everything, and hardcode that Jira account's credentials in your hook. This allows you to verify that a given PR exists.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文