袁绍成的个人博客
Gitblit创建钩子并对接webhook(钉钉群机器人)

当我们自主搭建好git服务器后,多人使用和团队协作后想要实时的了解到项目的变更情况。
比如谁谁什么时候提交了版本,主要有那些内容。
当然我们可以通过直接访问管理图形页面(web,域名+端口号)选择版本库查看详情,但是很明显访问网页去查看还是稍稍的有一丁点麻烦(强迫症)。
这里我介绍一种方法,配置好后对接钉钉的群机器人(只此一家!),这样每次Create版本库/Push等操作时会直接推送到对应的钉钉群中去。

效果图见正文

groovyxiaoguo.png

下面我们开始教程

一、定义脚本

首先我们先编写如下代码(桌面新建txt文件,把下面的代码放入后修改文件后缀groovy)

import com.gitblit.GitBlit
import com.gitblit.Keys
import com.gitblit.models.RepositoryModel
import com.gitblit.models.TeamModel
import com.gitblit.models.UserModel
import com.gitblit.utils.JGitUtils
import java.text.SimpleDateFormat
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.lib.Config
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.transport.ReceiveCommand
import org.eclipse.jgit.transport.ReceiveCommand.Result
import org.slf4j.Logger

logger.info("sendmail hook triggered by ${user.username} for ${repository.name}")


Repository r = gitblit.getRepository(repository.name)

Config config = r.getConfig()
def mailinglist = config.getString('hooks', null, 'mailinglist')
def emailprefix = config.getString('hooks', null, 'emailprefix')

// set default values
def toAddresses = []
if (emailprefix == null)
emailprefix = '[YasinYuan]'

if (mailinglist != null) {
    def addrs = mailinglist.split(/(,|\s)/)
    toAddresses.addAll(addrs)
}

toAddresses.addAll(gitblit.getStrings(Keys.mail.mailingLists))

def teams = gitblit.getRepositoryTeams(repository)
for (team in teams) {
    TeamModel model = gitblit.getTeamModel(team)
    if (model.mailingLists) {
        toAddresses.addAll(model.mailingLists)
    }
}

toAddresses.addAll(repository.mailingLists)

def repo = repository.name
def summaryUrl
def commitUrl
if (gitblit.getBoolean(Keys.web.mountParameters, true)) {
    repo = repo.replace('/', gitblit.getString(Keys.web.forwardSlashCharacter, '/')).replace('/', '%2F')
    summaryUrl = url + "/summary/$repo"
    commitUrl = url + "/commit/$repo/"
} else {
    summaryUrl = url + "/summary?r=$repo"
    commitUrl = url + "/commit?r=$repo&h="
}

def branchBreak = '>---------------------------------------------------------------\n'
def commitBreak = '\n\n ----\n'
def commitCount = 0
def changes = ''
SimpleDateFormat df = new SimpleDateFormat(gitblit.getString(Keys.web.datetimestampLongFormat, 'EEEE, MMMM d, yyyy h:mm a z'))
def table = { "\n ${JGitUtils.getDisplayName(it.authorIdent)}\n ${df.format(JGitUtils.getCommitDate(it))}\n\n $it.shortMessage\n\n $commitUrl$it.id.name" }
for (command in commands) {
    def ref = command.refName
    def refType = 'branch'
    if (ref.startsWith('refs/heads/')) {
        ref  = command.refName.substring('refs/heads/'.length())
    } else if (ref.startsWith('refs/tags/')) {
        ref  = command.refName.substring('refs/tags/'.length())
        refType = 'tag'
    }
        
    switch (command.type) {
        case ReceiveCommand.Type.CREATE:
            def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name).reverse()
            commitCount += commits.size()
            // new branch
            changes += "\n$branchBreak new $refType $ref created ($commits.size commits)\n$branchBreak"
            changes += commits.collect(table).join(commitBreak)
            changes += '\n'
            break
        case ReceiveCommand.Type.UPDATE:
            def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name).reverse()
            commitCount += commits.size()
            // fast-forward branch commits table
            changes += "\n$branchBreak $ref $refType updated ($commits.size commits)\n$branchBreak"
            changes += commits.collect(table).join(commitBreak)
            changes += '\n'
            break
        case ReceiveCommand.Type.UPDATE_NONFASTFORWARD:
            def commits = JGitUtils.getRevLog(r, command.oldId.name, command.newId.name).reverse()
            commitCount += commits.size()
            // non-fast-forward branch commits table
            changes += "\n$branchBreak $ref $refType updated [NON fast-forward] ($commits.size commits)\n$branchBreak"
            changes += commits.collect(table).join(commitBreak)
            changes += '\n'
            break
        case ReceiveCommand.Type.DELETE:
            // deleted branch/tag
            changes += "\n$branchBreak $ref $refType deleted\n$branchBreak"
            break
        default:
            break
    }
}
// close the repository reference
r.close()

def connection = new URL("https://oapi.dingtalk.com/robot/send?access_token=*******").openConnection()
        connection.setRequestMethod('POST')
        connection.doOutput = true
        connection.setRequestProperty("Content-Type", "application/json")
        //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
        def writer = new OutputStreamWriter(connection.outputStream,"utf-8")
        def content ="{\"msgtype\": \"text\",\"text\": {\"content\": \""+"$emailprefix $user.username pushed $commitCount commits => $repository.name\n"+"$summaryUrl\n$changes"+" \"},\"at\": {\"atMobiles\": [],\"isAtAll\": false}}"
        //println content.toString()
        writer.write(content.toString())
        writer.flush()
        writer.close()
        connection.connect()

        def respText = connection.content.text
        println respText

上述代码使用groovy语言编写,Groovy是一种基于JVM(Java虚拟机)的敏捷开发语言,所以代码与Java有些相似,如果看不太懂就直接复制。其中“https://oapi.dingtalk.com/robot/send?access_token=*”需要替换成钉钉群中对应的机器人连接的webhook地址,这部分代码就是查询本次接收到的git库操作的所有信息,然后拼接起来,再作为参数调用hook地址进行发送。

二、放入Gitblit配置文件中

打开服务器,进入到gitblit服务端的根目录中,进入到路径/data/groovy中,将上述脚本放入到该目录下,然后重启gitblit服务器。

三、对项目启用脚本

上篇文章已经教大家搭建gitblit服务器了,我们通过浏览器地址栏访问gitblit的图形客户端,创建项目。。。这些操作都完成后点击页面上的编辑进入到项目配置。左侧菜单选择receive,在出现的页面中找到post-receive脚本,这时候就可以查看到第二步操作后放入的脚本文件的名称了,选中后点击→箭头,最后保存即完成所有操作。
setting.png

评论

评论已关闭


Title - Artist
0:00
    我的个人主页苏ICP备18010375号-1
    本博客由DigitalOcean提供主机服务
    © 2018 - 2019 袁绍成的个人博客
    博客已经运行了