通用技术 Python3 通过 Gitlab API 获取项目工程、分支、commit 提交记录

xiaoxiao · 2022年03月08日 · 5725 次阅读

前提

在 gitlab 中你的工程创建 Access Token

然后你会得到一个 21 位 access token,代码中需要用到。

代码

'''
说明:
1.登录gitlab的root账号(登录账号根据需要访问的项目而定)
2.gitlab_token是gitlab用户的setting中生成的字符串,使用户可以通过http的形式下载代码
3.在gitlab用户的Settings->Access Tokens,创建你的access token,它会生成一个21位的字符串(只出现一次,注意小心保管)
'''
# -*- coding:utf-8 -*-

import json
import requests

# gitlab地址
git_url = 'https://gitlab.xxx.com'
# gitlab的token
git_token = 'xxxxxxxxxxxxxxxxxxxxx'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
}

session = requests.Session()
headers['PRIVATE-TOKEN'] = git_token
session.headers = headers
git_login = session.get(git_url, headers=headers)


# 获取当前账号有权限的全部工程列表
# 注意:参数per_page最大为100,传入超过100的值时,gitlab的url请求中的per_page默认取100
def gitlab_projects(per_page=100):
    print("正在获取gitlab上工程...")
    projects_api = git_url + '/api/v4/projects?simple=yes&per_page=%s' % per_page
    projects_headers = session.head(projects_api).headers
    projects_num = int(projects_headers['X-Total'])  # 获取工程总数
    projects_pages = int(projects_headers['X-Total-Pages'])  # 获取工程总页数
    print("工程总数:", projects_num)
    result = []
    for i in range(projects_pages):
        page = i + 1
        projects_url = projects_api + '&page=' + str(page)
        projects = session.get(projects_url).text
        projects_json = json.loads(projects)
        if type(projects_json) == list:
            result = result + projects_json
        else:
            print("projects_url: %s" % projects_url)
            print("headers: %s" % session.head(projects_api).headers)
            print("response: %s" % projects_json)
    print("工程获取完成~")
    return result


# 获取工程的分支
# 注意:参数per_page最大为100,传入超过100的值时,gitlab的url请求中的per_page默认取100
def gitlab_project_branches(project_id, project_name, page=1, per_page=100, get_all_branches=False, max_branch_count=200):
    print('工程id是' + str(project_id) + ':', '工程名是' + str(project_name))
    next_page = page
    branch_count = max_branch_count
    branch_names = []
    while next_page > 0 and branch_count > 0:
        project_branches_api = git_url + '/api/v4/projects/%s/repository/branches?page=%s&per_page=%s' % (project_id, next_page, per_page)
        branch_headers = session.head(project_branches_api).headers
        next_page = int(branch_headers['X-Next-Page']) if "X-Next-Page" in branch_headers and branch_headers['X-Next-Page'] != '' else 0
        if not get_all_branches:
            branch_count = branch_count - per_page
        branches_info = session.get(project_branches_api).text
        branches_info = json.loads(branches_info)
        for v in branches_info:
            branch_names.append(v["name"])
    print("分支信息获取完成~")
    if get_all_branches:
        return branch_names
    return branch_names[:max_branch_count]


# 增量获取所有工程所有分支的提交日志
# 注意:参数per_page最大为100,传入超过100的值时,gitlab的url请求中的per_page默认取100
def get_project_commits(project_id, project_branch_name, page=1, per_page=100, get_all_commits=False, max_commit_count=200):
    commit_all = []
    next_page = page
    commit_count = max_commit_count
    while next_page and commit_count > 0:
        if not get_all_commits:
            commit_count = commit_count - per_page
        commit_api = git_url + '/api/v4/projects/%s/repository/commits?ref_name=%s&page=%s&per_page=%s' % (project_id, project_branch_name, next_page, per_page)
        commit_headers = session.head(commit_api).headers
        next_page = commit_headers["X-Next-Page"]
        commit_info = session.get(commit_api).text
        commit_all = commit_all + json.loads(commit_info)
    print("%s分支获取的commit信息获取完成" % project_branch_name)
    if get_all_commits:
        return commit_all
    return commit_all[:max_commit_count]


# 1.获取所有的项目工程
project_result = gitlab_projects()
print(project_result)
print(len(project_result))

# 2.获取指定项目工程的分支名
branch_result = gitlab_project_branches(project_id=12345, project_name='my_project', page=1, per_page=100, get_all_branches=True)
print(branch_result)
print(len(branch_result))

# 3.获取指定项目工程的commit记录
commit_result = get_project_commits(project_id=12345, project_branch_name='master', page=1, per_page=100, get_all_commits=True)
print(commit_result)
print(len(commit_result))
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册