python调用git

目录

模块安装

基本用法

1. 初始化

2. 添加与提交

3. 回滚

4.分支

5. tag

6. 拉取远程仓库

7. 使用原生命令

 简单的封装

 关于gitpython的使用网址


模块安装

pip install gitpython

基本用法

1. 初始化

from git import Repo
Repo.init('/data/test2') # 创建一个git文件夹

2. 添加与提交

repo.index.add(['a.txt']) #将文件提交到缓存区
repo.inex.commit('update new') # 将缓存区文件提交到版本库

3. 回滚

repo.index.checkout(['a.txt']) # 回滚缓存区文件
repo.index.reset(commit='486a9565e07ad291756159dd015eab6acda47e25',head=True) #回滚版本库文件

4.分支

repo.create_head('debug') # 创建分支

5. tag

repo.create_tag('v1.0') # 创建tag

6. 拉取远程仓库

clone_repo=git.Repo.clone_from('https://github.com/wangfeng7399/syncmysql.git','/data/test3') #拉取远程代码
remote = repo.remote()
# 从远程版本库拉取分支
remote.pull('master') #后面跟需要拉取的分支名称
# 推送本地分支到远程版本库
remote.push('master') #后面跟需要提交的分支名称

7. 使用原生命令

repo=git.Git('/data/test4')
repo.checkout('debug')
print(repo.status())
#所有git支持的命令这里都支持

 简单的封装

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=10,
                                       date='format:%Y-%m-%d %H:%M')
        log_list = commit_log.split("\n")
        # print(self.repo.heads.master.commit,type(self.repo.heads.master.commit),type(str(self.repo.heads.master.commit)))
        return [eval(item) for item in log_list]

    def new_master_commits(self):
        """获取主分支的最后一次提交记录"""
        return str(self.repo.heads.master.commit)[:7]

    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)

    def get_log_1(self):
        """获取当前版本信息"""
        commit_hash = self.repo.head.object.hexsha
        commit_message = self.repo.head.object.message
        commit_author = self.repo.head.object.author.name
        commit_time = self.repo.head.object.authored_datetime

        print(f"Commit hash: {commit_hash}")
        print(f"Commit message: {commit_message}")
        print(f"Commit author: {commit_author}")
        print(f"Commit time: {commit_time}")


# 本地仓库位置
local_path = "D:\git\\auto_test"
# 远程仓库位置
remote_path = 'https://gitee.com/auto_test.git'
git = GitRepository(local_path, remote_path)

 关于gitpython的使用网址

官网:Overview / Install — GitPython 3.1.30 documentation

 其他:

python操作git

用GitPython操作Git库

Python使用GitPython操作Git版本库

猜你喜欢

转载自blog.csdn.net/dreams_dream/article/details/128524357