当前位置: 首页 > 工具软件 > GitPython > 使用案例 >

使用gitpython和python-gitlab操作git

邢献
2023-12-01

python有三个git相关的库,分别是gitpython、python-gitlab、gitlab库。

  • gitpython:是一个与Git库交互的Python库,可以实现绝大部分的Git读写操作。主要是取代shell的命令操作,通过这个进行本地仓库的一些拉取代码、创建分支、push代码等操作。
  • python-gitlab:是一个用来连接git,进行git信息查询的库。比如查询git的项目、users、提交到mr等。可以参考文档:https://python-gitlab.readthedocs.io/en/master/install.html
  • gitlab:没有仔细了解过。

这篇博文主要讲两个库的用法。

 

Gitpython

安装:

仍然要先安装python专门用来操作git的库,使用pip即可

pip install gitpython

连接:

from git import Repo
repo =Repo("/Users/alice/practice") # git文件的路径

操作Git:

repo提供了一些方法可以调用,如下:

from git import Repo
repo =Repo("/Users/alice/practice") #git文件的路径

# 克隆 git clone
repo.clone_from('url','to_path')

# 拉取代码
repo.remote().pull()

# 获取当前所在的分支 git branch
print(repo.active_branch)
# 获取所有分支
print (repo.branches)       # 也可以直接缩写print(r.branches)
print([str(b) for b in repo.branches])
print (repo.tags)
print([str(b) for b in repo.tags])


# 创建分支 git branch
repo.create_head("分支名")
# 添加版本号  git tag -a
repo.create_tag("tag号")


# 添加到缓存区 git add命令
# repo.index.add(["文件名"])

# 提交到版本库 git commit -m
repo.index.commit("message")

# 回退到某个版本 git reset --hard hash
repo.index.reset(commit="哈希地址",head=True)

# 推送代码到远程分支
repo.remote().push('远程分支名')

# 查看git log
repo.iter_commits()
print([str(i.message) for i in r.iter_commits()]) # 获取提交信息
print([str(i.message) for i in r.iter_commits()]) # 查看提交的hash值

 

python-gitlab

安装:

仍然要先安装库,使用pip即可

pip install python-gitlab

# 如果权限问题失败可以使用
sudo pip install python-gitlab

#如果是本地已安装要升级可以采用
sudo pip install --upgrade python-gitlab

连接:

import gitlab

git_url = 'https://gitlab.com/sweet'    #gitlab服务端地址
private_token = 'xxxxxx'        #获取git的token

# private token or personal token authentication
gl = gitlab.Gitlab(git_url, private_token, api_version='4')  #api_version默认是4,具体看自己公司的版本

操作Git:

python-gitlab提供了一些方法可以调用,如下:


## 获取project列表
projects = git.projects.list()
print (projects)
## 获取所有project
projects = git.projects.all()
projects = git.projects.list(all=True)
for project in projects:
    print (project.name,project.id,projects.http_url_to_repo)

groups = gl.groups.list(all=True)
for group in all_groups:
    print (group.name,group.id)


project = git.projects.get(24664833)    #项目的id
group = gl.groups.get(2)
commit = project.commits.list()[0]  #获取最新的提交人信息,这里我取的第一个人的
git_name =commit.committer_name   #可以直接提取用户信息里的name,也可以获取提交的id,created_at,message


members = group.members.list(all=True)
for me in members:
    print (me.username,me.id)

# 获取git所有的user
users = gl.users.list(all=True)
for user in users:
    print (user.username,user.id,user.name,user.state)

# 创建一个新用户
user_data = {'email': 'jen@foo.com', 'username': 'jen', 'name': 'Jen'}
user = gl.users.create(user_data)
print(user)


# 示例:获取gitlab指定组内所有user以及project名称以及ID信息,本例中组ID为58
gid = int(raw_input('Input the group ID: '))
group = gl.groups.get(gid)
print (gid, group.name)

 

使用Requests查询Git信息

了解了git的连接方式,如果希望获取Git上MR的信息,也可以实现了:

  • 使用python-gitlab来连接Git
  • 使用Requets库来访问接口和拿到返回数据
  • 使用json库提供的方法来解析返回的json
import requests
import json

def work():
    mrs_url = 'https://gitlab.com/api/v4/projects/2466000000/merge_requests'

    headers = {
        "Accept": "application/json, text/plain, */*",
        "PRIVATE-TOKEN": "xxxxxxx",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
    }

    params = {
        "page_size": 20
    }

    response = requests.get(mrs_url, headers=headers, params=params)
    result = json.loads(response.text)
    for mr in result:
        print (mr['iid'], mr['state'], mr['merge_status'], mr['author']['name'], mr['title'])

work()

运行结果为:

2 opened can_be_merged Alice Practice2 merge to master
1 opened can_be_merged Alice Practice1 to master

附gitlab的MR返回json信息参考:

[
    {
        "id":9014000000xx,
        "iid":2,
        "project_id":2466400000xx,
        "title":"Practice2 merge to master",
        "description":"",
        "state":"opened",
        "created_at":"2020-02-27T13:19:07.992Z",
        "updated_at":"2020-02-27T13:19:07.992Z",
        "merged_by":null,
        "merged_at":null,
        "closed_by":null,
        "closed_at":null,
        "target_branch":"master",
        "source_branch":"practice2",
        "user_notes_count":0,
        "upvotes":0,
        "downvotes":0,
        "author":{
            "id":8269000000xx,
            "name":"Alice",
            "username":"sweet",
            "state":"active",
            "avatar_url":"https://assets.gitlab-static.net/uploads/-/system/user/avatar/826900000xx/xx.png",
            "web_url":"https://gitlab.com/sweet"
        },
        "assignees":[

        ],
        "assignee":null,
        "reviewers":[

        ],
        "source_project_id":2466400000xx,
        "target_project_id":2466400000xx,
        "labels":[

        ],
        "work_in_progress":false,
        "milestone":null,
        "merge_when_pipeline_succeeds":false,
        "merge_status":"can_be_merged",
        "sha":"b9f4599858c76a0ccfxx",
        "merge_commit_sha":null,
        "squash_commit_sha":null,
        "discussion_locked":null,
        "should_remove_source_branch":null,
        "force_remove_source_branch":true,
        "reference":"!2",
        "references":{
            "short":"!2",
            "relative":"!2",
            "full":"sweet/practice!2"
        },
        "web_url":"https://gitlab.com/sweet/practice/-/merge_requests/2",
        "time_stats":{
            "time_estimate":0,
            "total_time_spent":0,
            "human_time_estimate":null,
            "human_total_time_spent":null
        },
        "squash":false,
        "task_completion_status":{
            "count":0,
            "completed_count":0
        },
        "has_conflicts":false,
        "blocking_discussions_resolved":true,
        "approvals_before_merge":null
    },
    {
        "id":901400000xx,
        "iid":1,
        "project_id":246600000xx,
        "title":"Practice1 to master",
        "description":"",
        "state":"opened",
        "created_at":"2020-02-27T12:58:55.990Z",
        "updated_at":"2020-02-27T12:58:55.990Z",
        "merged_by":null,
        "merged_at":null,
        "closed_by":null,
        "closed_at":null,
        "target_branch":"master",
        "source_branch":"practice1",
        "user_notes_count":0,
        "upvotes":0,
        "downvotes":0,
        "author":{
            "id":826000000xx,
            "name":"Alice",
            "username":"sweet",
            "state":"active",
            "avatar_url":"https://assets.gitlab-static.net/uploads/-/system/user/avatar/8269000000xx/xx.png",
            "web_url":"https://gitlab.com/sweet"
        },
        "assignees":[

        ],
        "assignee":null,
        "reviewers":[

        ],
        "source_project_id":2466400000xx,
        "target_project_id":2466400000xx,
        "labels":[

        ],
        "work_in_progress":false,
        "milestone":null,
        "merge_when_pipeline_succeeds":false,
        "merge_status":"can_be_merged",
        "sha":"b9f4599858c76axx",
        "merge_commit_sha":null,
        "squash_commit_sha":null,
        "discussion_locked":null,
        "should_remove_source_branch":null,
        "force_remove_source_branch":true,
        "reference":"!1",
        "references":{
            "short":"!1",
            "relative":"!1",
            "full":"sweet/practice!1"
        },
        "web_url":"https://gitlab.com/sweet/practice/-/merge_requests/1",
        "time_stats":{
            "time_estimate":0,
            "total_time_spent":0,
            "human_time_estimate":null,
            "human_total_time_spent":null
        },
        "squash":false,
        "task_completion_status":{
            "count":0,
            "completed_count":0
        },
        "has_conflicts":false,
        "blocking_discussions_resolved":true,
        "approvals_before_merge":null
    }
]

 

 类似资料: