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版本库

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值