python-use-gitlab-api(已验证)

本文转自:http://blog.54im.com/2016/10/12/python-use-gitlab-api/

gitlab 页面操作比较方便,但是当项目多的时候,运维每次界面上合并分支的操作比较繁琐,该脚本持续更新

[[email protected]:/data/ops]$ python gitlab.py
**************************************************
*COMMAND:	python gitlab.py args
*HELP:	python gitlab.py --help
*VERSION:	V0.0.1
**************************************************
eg: python gitlab.py -t project_list
eg: python gitlab.py -t create_branch -p <project_id> -b <newbranch_name> -f <from_branch>
eg: python gitlab.py -t create_mr --project_id=<project_id> --source_branch=<source-branch> --target_branch=<target_branch> --title=<title>
eg: python gitlab.py -t accept_mr --project_id=<project_id> --merge_request_id=<merge_request_id>
eg: python gitlab.py -t merge --project_id=<project_id> --source_branch=<source-branch> --target_branch=<target_branch> --title=<title>
 -t command type
 -p gitlab project id
 -b create new branch name
 -f new branch from branch
 --source_branch gitlab source branch
 --target_branch gitlab target branch
 --title gitlab create merge request title
 --merge_request_id gitlab merge  request id

脚本目前支持查看gitlab上项目对应id,创建merge request, 接受merge request操作,后续操作持续完善中

#!/usr/bin/env python
# coding:utf-8
'''
Author : diantian li
Email : [email protected]
'''
import sys,getopt
import requests
import time
import logging
from prettytable import PrettyTable
logging.basicConfig(filename='gitlab.log', level=logging.INFO)
GITLAB_URL = 'http://gitlab.54im.com/api/v3/'
GITLAB_PRIVATE_TOKEN = 'xxxxxx'
NOW=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def project_list():
    url = GITLAB_URL + '/projects?private_token=' + GITLAB_PRIVATE_TOKEN + '&per_page=200'
    r = requests.get(url)
    data = r.json()
    x = PrettyTable(["project_id","project_name" ])
    x.padding_width = 1
    for i in data:
        a = i[u'id']
        b = i[u'name']
        x.add_row([a,b])
        #print i[u'id'],i[u'name']
    print x
def create_branch(project_id,newbranch_name,from_branch):
    #curl -X POST -H "PRIVATE-TOKEN: 9koXpg98eAheJpvBs5tK" "https://gitlab.example.com/api/v3/projects/5/repository/branches?branch_name=newbranch&ref=master"
    url = GITLAB_URL + 'projects/' + project_id + '/repository/branches?branch_name=' + newbranch_name + '&ref=' + from_branch
    print url
    headers = {'PRIVATE-TOKEN': GITLAB_PRIVATE_TOKEN}
    r = requests.post(url,headers = headers)
    print(r.text)
def create_mr(project_id,source_branch,target_branch,title):
    url = GITLAB_URL + 'projects/' + project_id + '/merge_requests?source_branch=' + source_branch + '&target_branch=' + target_branch +'&title=' + title
    logging.info('%s - %s'%(NOW,url))
    headers = {'PRIVATE-TOKEN': GITLAB_PRIVATE_TOKEN}
    payload = {'source_branch': source_branch, 'target_branch': target_branch,'title':title}
    r = requests.post(url,headers = headers,params=payload)
    merge_request_id = r.json()['id']
    logging.info('%s - %s'%(NOW,r.text))
    logging.info('%s - create merge request,merge_request_id= %s'%(NOW,merge_request_id))
    return merge_request_id
def accept_mr(project_id,merge_request_id):
    url = GITLAB_URL + 'projects/' + project_id + '/merge_request/' + merge_request_id + '/merge'
    print url
    headers = {'PRIVATE-TOKEN': GITLAB_PRIVATE_TOKEN}
    r = requests.put(url,headers = headers)
    result = r.json()['merge_when_build_succeeds"']
    logging.info('%s - accept merge request result %s'%(NOW,r.text))
    if result == "true":
        logging.info('%s - accept merge request result is %s ,project_id= % ,merge_request_id=%'%(NOW,result,project_id,merge_request_id))
        return r.json()['id']
    else:
        print 'accept merge_requit_id fail'
def merge(project_id,source_branch,target_branch,title):
    merge_request_id = create_mr(project_id,source_branch,target_branch,title)
    logging.info('% merge all-in-one merge_request_id %r, project_id %d'%(NOW,merge_request_id,project_id))
    if merge_request_id is not None:
        result = accept_mr(project_id,merge_request_id)
        if result == merge_request_id:
            print 'merge sucess'
    else:
        print 'get merge_request_id fail'
def usage():
    print '\033[1;32;40m'
    print '*' * 50
    print '*COMMAND:\t', 'python gitlab.py args'
    print '*HELP:\t', 'python gitlab.py --help'
    print '*VERSION:\t', 'V0.0.1'
    print '*' * 50
    print '\033[0m'
    print '\n' \
          'eg: python gitlab.py -t project_list \n' \
          'eg: python gitlab.py -t create_branch -p <project_id> -b <newbranch_name> -f <from_branch> \n' \
          'eg: python gitlab.py -t create_mr --project_id=<project_id> --source_branch=<source-branch> --target_branch=<target_branch> --title=<title>\n' \
          'eg: python gitlab.py -t accept_mr --project_id=<project_id> --merge_request_id=<merge_request_id> \n'\
          'eg: python gitlab.py -t merge --project_id=<project_id> --source_branch=<source-branch> --target_branch=<target_branch> --title=<title>\n' \
          '\n' \
          ' -t command type\n' \
          ' -p gitlab project id\n' \
          ' -b create new branch name\n' \
          ' -f new branch from branch\n' \
          ' --source_branch gitlab source branch\n' \
          ' --target_branch gitlab target branch\n' \
          ' --title gitlab create merge request title\n' \
          ' --merge_request_id gitlab merge  request id\n' \
          ''
def main():
    command_type = ''
    project_id = ''
    newbranch_name = ''
    from_branch = ''
    source_branch = ''
    target_branch = ''
    title = ''
    merge_request_id  = ''
    if len(sys.argv) < 2:
        usage()
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ht:p:b:f:s:t:t:m:", ["help", "type=","project_id=","branch=","from=","source_branch=","target_branch=","title=","merge_request_id="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for name, value in opts:
        if name in ('-h','--help'):
            usage()
        elif name in ("-t", "--type"):
            command_type = value
        elif name in ("-p", "--project_id"):
            project_id = value
        elif name in ("-b", "--branch_name"):
            newbranch_name = value
        elif name in ("-f", "--from_branch"):
            from_branch = value
        elif name in ("--source_branch"):
            source_branch = value
        elif name in ("--target_branch"):
            target_branch = value
        elif name in ("--title"):
            title = value
        elif name in ("--merge_request_id"):
            merge_request_id = value
        else:
            assert False, "unhandled option"
    if command_type == "project_list":
        project_list()
    elif command_type == "create_branch":
        if project_id != "" and newbranch_name != "" and from_branch != "":
            create_branch(project_id,newbranch_name,from_branch)
        else:
            print "please input -p project_id -b newbranch_name -f from_branch"
    elif command_type == "create_mr":
        if project_id != "" and source_branch != "" and target_branch != "" and title != "":
            create_mr(project_id,source_branch,target_branch,title)
        else:
            print "please input --type=create_mr --project_id=<project_id> --source=<source_name> --target=<target_branch> --title=<title>"
    elif command_type == "accept_mr":
        if project_id != "" and merge_request_id != "":
            accept_mr(project_id,merge_request_id)
        else:
            print "please input --type=accept_mr --project_id=<project_id> --merge_request_id=<merge_request_id>"
    elif command_type == "merge":
        if project_id != "" and source_branch != "" and target_branch != "" and title != "":
            merge(project_id,source_branch,target_branch,title)
        else:
            print "please input --type=accept_mr --project_id=<project_id> --merge_request_id=<merge_request_id>"
if __name__ == "__main__":
    main()

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This blog is kept spam free by WP-SpamFree.