Python Gitlab Api 使用方法

  • Post author:
  • Post category:python



目录


运用python管理Gitlab


获取private token


统计代码仓库各分支代码量


运用python管理Gitlab


获取private token

1.登录gitlab

2.点击帐户,点击【settings】

3.点击【Access Tokens】

统计代码仓库各分支代码量


import gitlab
import xlwt

'''
gitlab 经常使用到的api以及统计代码仓库各分支代码量
'''

# 用户git账户的token
private_token = ''  
# git地址
private_host = ''



def getAllProjects():
    client = gitlab.Gitlab('这里填URL', private_token='这里填private_token', timeout=500, api_version='4',
                  ssl_verify=False)
    projects = client.projects.list(membership=True, all=True) #gitlab的接口是默认分页取得,要取得所有数据,记得要加 all=True
    print(projects)
    #[<Project id:885>, <Project id:144>, <Project id:143>, <Project id:142>, <Project id:140>, <Project id:139>]
    return projects


def getAllBranchByProject(project):
    branches = project.branches.list()
    return branches


def getCommitByBranch(project, branch):
    author_commits = []
    commits = project.commits.list(all=True, ref_name=branch.name)
    for commit in commits:
        title = commit.title
        message = commit.message
        # print(commit.created_at, "-----------00-----------------")
        # print(title,message)
        if ('Merge' in message) or ('Merge' in title):
            # print('Merge跳过')
            continue
        else:
            if str(commit.created_at).split("-")[0] == "2021" and str(commit.created_at).split("-")[1] in ["01", "02", '03']:# and str(commit.created_at).split("-")[1] in ["05", "04"]:
                print(commit.created_at, "------time--------------")
                author_commits.append(commit)
    # print(author_commits)
    return author_commits


def getCodeByCommit(commit, project):
    commit_info = project.commits.get(commit.id)
    code = commit_info.stats
    return code


def getAuthorCode():
    maxdata=[]
    projects = getAllProjects()
    # print(projects)
    for project in projects:
        print(project.name,"正在获取")
        branches = getAllBranchByProject(project)
        # print(project.name, type(project.name))
        # print(branches)
        # if project.name == "a" or project.name == "b" or project.name == "c":
        data = []
        for branch in branches:
            # print('获取工程', project.name, '分支', branch.name, "的提交记录")
            branchdata = {}
            branchdata['projectname'] = project.name
            branchdata['branchename'] = branch.name
            if branch.name =='master' or branch.name =='develop'or branch.name =='other':
                author_commits = getCommitByBranch(project, branch)
                # print(author_commits)    #[<ProjectCommit id:39cd9ad50f8de6450556a4171b23eaea67b745e2>]
                codes = []
                for commit in author_commits:
                    try:
                        # print('获取提交', commit.id, "的代码量")
                        code = getCodeByCommit(commit, project)
                        codes.append(code)
                    except gitlab.exceptions.GitlabGetError:
                        print(project.name,'的',commit.id, "的代码量统计失败*************")
                        continue
                record = calculate(codes)
                # print(record)
                branchdata['commitcount'] = len(author_commits)
                branchdata['codecount'] = record
                data.append(branchdata)
            else:
                continue

        if len(data)>=1:
            maxdata.append(data)
            print(maxdata)
            print(project.name, "获取完毕")

    # print(data)
    return maxdata

def writeExcel(data,Numberrows):
    addcount = 0
    delcount = 0
    totalcount = 0
    commitcount = 0     
    for i in range(Numberrows, Numberrows+len(data)):
        recode = data[i-Numberrows]
        j = 0
        sheet.write(i + 1, j, recode['projectname'])
        sheet.write(i + 1, j + 1, recode['branchename'])
        commitcount += (int)(recode['commitcount'])
        sheet.write(i + 1, j + 2, recode['commitcount'])
        addcount += (int)(recode['codecount']['additions'])
        sheet.write(i + 1, j + 3, recode['codecount']['additions'])
        delcount += (int)(recode['codecount']['deletions'])
        sheet.write(i + 1, j + 4, recode['codecount']['deletions'])
        totalcount += (int)(recode['codecount']['total'])
        sheet.write(i + 1, j + 5, recode['codecount']['total'])
    # sheet.write(Numberrows+len(data) + 1, 2, commitcount)   #统计
    # sheet.write(Numberrows+len(data) + 1, 3, addcount)
    # sheet.write(Numberrows+len(data) + 1, 4, delcount)
    # sheet.write(Numberrows+len(data) + 1, 5, totalcount)


def calculate(data):
    record = {}
    addacount = 0
    deletecount = 0
    totaolcount = 0
    for i in data:
        addacount += int(i['additions'])
        deletecount += int(i['deletions'])
        totaolcount += int(i['total'])
    record['additions'] = addacount
    record['deletions'] = deletecount
    record['total'] = totaolcount
    return record


if __name__ == '__main__':
    workbook = xlwt.Workbook()     #这里拿出来是为了循环写入Excel
    # 获取第一个sheet页
    sheet = workbook.add_sheet('git')
    row0 = ['工程名称', '分支名称', '提交次数', '新增代码', '删除代码', '总计代码']
    for i in range(0, len(row0)):
        sheet.write(0, i, row0[i])

    maxdata = getAuthorCode()   #maxdata是每个项目组成的列表
    print(maxdata)
    Numberrows=0
    for data in maxdata:        #这里为了计算写入位置
        writeExcel(data,Numberrows)
        Numberrows=int(len(data))+Numberrows+1


    workbook.save('test.xls')





版权声明:本文为weixin_48704094原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。