Python Gitlab Api 使用方法

目录

运用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')



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Python可以使用GitLab APIGitLab进行交互。你可以使用`python-gitlab`库来简化API调用。 首先,你需要安装`python-gitlab`库。可以使用以下命令安装: ``` pip install python-gitlab ``` 接下来,你需要通过提供GitLab实例的URL和访问令牌来创建一个GitLab对象。访问令牌可以在GitLab账户的设置中生成。以下是一个示例代码: ```python import gitlab # 设置GitLab实例的URL和访问令牌 gitlab_url = 'https://gitlab.example.com' access_token = 'your_access_token' # 创建GitLab对象 gl = gitlab.Gitlab(gitlab_url, private_token=access_token) # 连接到GitLab实例 gl.auth() # 现在你可以使用GitLab对象调用API方法了 ``` 接下来,你可以使用GitLab对象调用各种API方法。例如,获取项目列表、创建分支、提交代码等。以下是一些示例代码: ```python # 获取项目列表 projects = gl.projects.list() for project in projects: print(project.name) # 创建分支 project_id = 1234 # 项目的ID branch_name = 'my-branch' project = gl.projects.get(project_id) branch = project.branches.create({'branch': branch_name, 'ref': 'master'}) # 提交代码 file_path = 'path/to/file.txt' commit_message = 'My commit message' file_content = 'Hello, GitLab!' project.files.create({'file_path': file_path, 'branch': branch_name, 'content': file_content, 'commit_message': commit_message}) ``` 这只是一些示例代码,你可以根据自己的需求来调用其他API方法。你可以查阅`python-gitlab`库的文档以获取更多详细信息和示例代码。 注意,为了使用GitLab API,你需要对GitLab实例具有相应的访问权限。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值