Gitpython 简单使用

python操作git仓库,类似于gtibash中的命令,使用之前我们需要安装gitpython模块:

 pip3 install gitpython

克隆代码仓库

import os
from git.repo import Repo

download_path = os.path.join('code', 'blog')  # 下载到code目录下的blog文件夹
Repo.clone_from('https://gitee.com/andy963/blog.git', to_path=download_path, branch='master')  # branch指定分支

拉取远程仓库的最新代码

import os
from git.repo import Repo

local_path = os.path.join('code', 'blog') # 拉到到本地的目录
repo = Repo(local_path) # 实例化对象
repo.git.pull() 

获取远程仓库的所有分支:

import os
from git.repo import Repo

local_path = os.path.join('code', 'blog')
repo = Repo(local_path)

branches = repo.remote().refs # 获取远程仓库的所有分支
for item in branches:
    print(item.remote_head) 

获取所有版本:

import os
from git.repo import Repo

local_path = os.path.join('code', 'blog')
repo = Repo(local_path)

for tag in repo.tags:
    print(tag.name) 

获取commit信息

import os
from git.repo import Repo

local_path = os.path.join('..', 'blog')
repo = Repo(local_path)

commit_log = repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}', max_count=50,
                          date='format:%Y-%m-%d %H:%M')
# %h 指定 head, commit提交时的字符串, an指定作者, s指定summary, cd指定日期, max_count指定获取最近的50条
# 获取的结果是字符串,看起来像字典的字符串
log_list = commit_log.split("\n")
real_log_list = [eval(item) for item in log_list]
print(real_log_list)

切换分支

import os
from git.repo import Repo

local_path = os.path.join('code', 'blog')
repo = Repo(local_path)

before = repo.git.branch() # 当前在master分支
print(before)
repo.git.checkout('dev')
after = repo.git.branch()
print(after) # 切换到了dev分支
repo.git.reset('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8') 

打包代码:

with open(os.path.join('code', 'blog.tar'), 'wb') as fp:
    repo.archive(fp) 

将这些功能封装到类中:

import os
from git.repo import Repo
from git.repo.fun import is_git_dir

class GitRepository(object):
    """
    git仓库管理
    """

    def __init__(self, local_path, repo_url, branch='master'):
        self.local_path = local_path
        self.repo_url = repo_url
        self.repo = None
        self.initial(repo_url, branch)

    def initial(self, repo_url, branch):
        """
        初始化git仓库
        :param repo_url:
        :param branch:
        :return:
        """
        if not os.path.exists(self.local_path):
            os.makedirs(self.local_path)

        git_local_path = os.path.join(self.local_path, '.git')
        if not is_git_dir(git_local_path):
            self.repo = Repo.clone_from(repo_url, to_path=self.local_path, branch=branch)
        else:
            self.repo = Repo(self.local_path)

    def pull(self):
        """
        从线上拉最新代码
        :return:
        """
        self.repo.git.pull()

    def branches(self):
        """
        获取所有分支
        :return:
        """
        branches = self.repo.remote().refs
        return [item.remote_head for item in branches if item.remote_head not in ['HEAD', ]]

    def commits(self):
        """
        获取所有提交记录
        :return:
        """
        commit_log = self.repo.git.log('--pretty={"commit":"%h","author":"%an","summary":"%s","date":"%cd"}',
                                       max_count=50,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        return [eval(item) for item in log_list]

    def tags(self):
        """
        获取所有tag
        :return:
        """
        return [tag.name for tag in self.repo.tags]

    def change_to_branch(self, branch):
        """
        切换分值
        :param branch:
        :return:
        """
        self.repo.git.checkout(branch)

    def change_to_commit(self, branch, commit):
        """
        切换commit
        :param branch:
        :param commit:
        :return:
        """
        self.change_to_branch(branch=branch)
        self.repo.git.reset('--hard', commit)

    def change_to_tag(self, tag):
        """
        切换tag
        :param tag:
        :return:
        """
        self.repo.git.checkout(tag)


if __name__ == '__main__':
    local_path = os.path.join('codes', 'blog')
    repo = GitRepository(local_path, 'https://gitee.com/andy963/blog.git')
    branch_list = repo.branches()
    print(branch_list)
    repo.change_to_branch('dev')
    repo.pull()

-b参数既可以用来切换分支branch, 又可以用来切换tag

上一篇:Flask信号

下一篇:Python 解压缩