python calls git

Table of contents

module installation

basic usage

1. Initialization

2. Add and Submit

3. Rollback

4. branch

5. tag

6. Pull remote warehouse

7. Use native commands

 simple package

 About the use URL of gitpython


module installation

pip install gitpython

basic usage

1. Initialization

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

2. Add and Submit

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

3. Rollback

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

4. branch

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

5. tag

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

6. Pull remote warehouse

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

7. Use native commands

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

 simple package

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)

 About the use URL of gitpython

Official website: Overview / Install — GitPython 3.1.30 documentation

 other:

Python operation git

Use GitPython to operate Git libraries

Python uses GitPython to operate the Git repository

Guess you like

Origin blog.csdn.net/dreams_dream/article/details/128524357