首页 > 编程语言 > 详细

python 操作git

时间:2020-09-26 22:53:46      阅读:45      评论:0      收藏:0      [点我收藏+]

-- coding: utf-8 --

!/usr/bin/env python

Software: PyCharm

time: 2020/9/26 20:57

noqa

""" pip install gitpython """

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:
    """
    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:
    """
    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)
    return self.repo.git.reset(‘--hard‘, commit)

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

python 操作git

原文:https://www.cnblogs.com/yuhaipeng/p/13737029.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!