标签归档:golang gitlab api

Golang操作Gitlab实现MR自动合并


2021年3月26日 17:26:22   4,250 次浏览

通过gitlab api实现merge requests的自动合并,在使用api前我们需要先安装依赖及需要在gitlab配置帐户的token, 因为接下来需要用到token

go get -u github.com/xanzy/go-gitlab

package main

import (
	"fmt"
	"github.com/xanzy/go-gitlab"
	"log"
	"time"
)
var (
	// Your gitlab token
	token = ""
	// Your gitlab url
	url = "http://"
	// Name of your GITLAB project team
	groupName = "ops"
)
func main() {

	for {
		git, err := gitlab.NewClient(token, gitlab.WithBaseURL(url))

		if err != nil {
			log.Fatalf("Failed to create client: %v", err)
		}

		log.Println("开始获取所有组信息")

		u := &gitlab.ListGroupsOptions{
			Search: gitlab.String(groupName),
		}
		group, _, err := git.Groups.ListGroups(u)

		if err != nil {
			fmt.Printf("获取组信息异常:%v", err)
			panic(err)
		}

		for _, group := range group {
			log.Println("组名:",group.Name, "创建时间:", group.CreatedAt.Format("2006-01-02"))
			if group.Name == groupName {
				// Get Merge Requests List
				log.Printf("获取:%v项目Merge Requests开始...", groupName)
				ListMergeOps := &gitlab.ListGroupMergeRequestsOptions{
					OrderBy: gitlab.String("updated_at"),
					State: gitlab.String("opened"),
					Scope: gitlab.String("all"),
				}
				// List Group Merge
				mr, _, err := git.MergeRequests.ListGroupMergeRequests(group.ID, ListMergeOps)
				// List All Merge Requests
				//mr, _, err := git.MergeRequests.ListMergeRequests(ListMergeOps)
				if err != nil {
					panic(err)
				}
				for _, mr := range mr {
					log.Printf("用户:%v发起了一个MR请求,描述信息:%v, MR_ID: %v, 项目ID: %v", mr.Author.Name, mr.Title, mr.IID, mr.ProjectID)
					// Auto merge request
					MergeSave := &gitlab.AcceptMergeRequestOptions{}
					merge, code, err := git.MergeRequests.AcceptMergeRequest(mr.ProjectID, mr.IID, MergeSave)
					if err != nil {
						fmt.Println(err)
					}
					switch code.StatusCode{
					case 405:
						log.Println("当前Merge Requests存在草稿,暂时不能合并")
					case 406:
						log.Println("Merge Requests合并失败,当前代码存在冲突请解决后再试!")
					case 200:
						log.Println("恭喜你,Merge Requests合并成功.")
					default:
						log.Println("等待下一次检查中.")
					}
					log.Println(merge)
				}
			}
		}
		time.Sleep(time.Duration(30)*time.Second)
	}
}

接下来我们向gitlab发起一个merge requests,等待30s秒将会自动合并。

2021/03/26 16:34:12 开始获取所有组信息
2021/03/26 16:34:12 组名: ops 创建时间: 2021-03-08
2021/03/26 16:34:12 获取:ops项目Merge Requests开始...
2021/03/26 16:34:12 用户:张三发起了一个MR请求,描述信息:新增ibe配置, MR_ID: 6, 项目ID: 77
2021/03/26 16:34:14 恭喜你,Merge Requests合并成功.

基于Python 版本的gitlab requests 自动合并脚本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @File  : GitLab-API.py
# @Author: 风哥
# @Email: gujiwork@outlook.com
# @Date  : 2021/3/25
# @Desc  : gitlab自动合并请求
import gitlab
from gitlab.exceptions import GitlabMRClosedError
import time


url = 'http://'  # gitlab安装地址
private_token = ''  # gitlab 登录密钥 需自己设置


while True:
    # 登录 获取gitlab操作对象gl
    gl = gitlab.Gitlab(url, private_token)
    group = gl.groups.get('ops')
    mrs = group.mergerequests.list(state='opened', order_by='updated_at')
    for i in mrs:
        msg = "用户:{0}发起了一个MR请求, 描述信息:{1}, MR_ID: {2}, 项目ID:{3}".format(i.author['name'], i.title, str(i.iid), str(i.project_id))
        project = gl.projects.get(i.project_id, lazy=True)
        mr = project.mergerequests.get(i.iid, lazy=True)
        try:
            print("开始自动合并代码")
            mr.merge()
            print("自动合并MR成功!")
        except GitlabMRClosedError as e:
            if e.response_code == 405:
                print("MR存在Draft草稿, Closed关闭, Pipline状态, 返回状态码405不允许操作")
            elif e.response_code == 406:
                print("自动合并失败, 当前存在冲突,请手动解决后再试!")
            else:
                print("出现异常,暂时无法自动合并!")

        # print(mr)
    time.sleep(30)