前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >gitpython模块——使用python操作git

gitpython模块——使用python操作git

作者头像
GH
发布于 2020-03-19 01:09:44
发布于 2020-03-19 01:09:44
10.9K00
代码可运行
举报
运行总次数:0
代码可运行

gitpython模块——使用python操作git

安装

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
pip3 install gitpython

基本使用:pull/clone

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from git.repo import Repo
import os

# 从远程仓库下载代码到本地   pull/clone
download_path = os.path.join('test','t1')
# 从远程仓库将代码下载到上面创建的目录中
Repo.clone_from('https://github.com/ylpb/CMDB.git',to_path=download_path,branch='master')

更多操作

pull最新代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# ############## 2. pull最新代码 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('test','t1')
repo = Repo(local_path)
repo.git.pull()

获取所有分支

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# ############## 3. 获取所有分支 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('test','t1')
repo = Repo(local_path)
 
branches = repo.remote().refs
for item in branches:
    print(item.remote_head)

获取所有版本

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# ############## 4. 获取所有版本 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('test','t1')
repo = Repo(local_path)
 
for tag in repo.tags:
    print(tag.name)

获取所有commit

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# ############## 5. 获取所有commit ##############
import os
from git.repo import Repo
 
local_path = os.path.join('test','t1')
repo = Repo(local_path)

将所有提交记录结果格式成json格式字符串

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# 将所有提交记录结果格式成json格式字符串 方便后续反序列化操作
commit_log = 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")
real_log_list = [eval(item) for item in log_list]
print(real_log_list)

切换分支

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# ############## 6. 切换分支 ##############
import os
from git.repo import Repo
 
local_path = os.path.join('test','t1')
repo = Repo(local_path)
 
before = repo.git.branch()
print(before)
repo.git.checkout('master')
after = repo.git.branch()
print(after)
repo.git.reset('--hard', '854ead2e82dc73b634cbd5afcf1414f5b30e94a8')

打包代码

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
# ############## 7. 打包代码 ##############
with open(os.path.join('test','t1'), 'wb') as fp:
    repo.archive(fp)

封装之后的版本

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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', 't1')
    repo = GitRepository(local_path,remote_path)
    branch_list = repo.branches()
    print(branch_list)
    repo.change_to_branch('dev')
    repo.pull()

总结

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
"""
后期你在接触一些模块的时候 也应该想到将该模块所有的方法整合到一起
方便以后的调用
"""
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-03-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
如何使用 Python 操作 Git 代码?GitPython 入门介绍
有时,需要做复杂的 Git 操作,并且有很多中间逻辑。用 Shell 做复杂的逻辑运算与流程控制就是一个灾难。所以,用 Python 来实现是一个愉快的选择。这时,就需要在 Python 中操作 Git 的库。
Python猫
2019/10/14
27.8K1
如何使用 Python 操作 Git 代码?GitPython 入门介绍
监控github项目最新releases
闲着无聊,自己又在自学习python。之前分享过搭建的hugo的过程,因为国内连接github速度有点慢,所以当时就把最新的releases下载了,并上传到coding当作备份,当时写的是每周去下载一次,但是自己太懒不想动,于是。。。更新了好几个版本自己也没动,于是就想着用python帮忙了。
布衣者
2021/09/07
7530
git:指令备忘录
准备工作 生成公钥: ssh-keygen 复制以下SSH公钥到对应地方: cat ~/.ssh/id_rsa.pub 测试连接是否成功: ssh -T git@github.com ---- 日常指令 Command Annotation git 简洁地查看所有指令 git help _command 显示command的help git _command –help 显示command的help touch _file 新建文件 git add _file 将工作文件修改提交到本地暂存区 git
JNingWei
2018/09/28
5180
matinal:python实现FTP文件上传
   通过python web server端上传大文件到FTP服务端,上传文件夹,下载文件等
matinal
2023/10/14
3390
你会在命令行下高效管理 Github 上的项目吗,用上这个神器后助你秒实现!
对于大多数使用 Git 作为版本管理的技术人员来说,应该都接触过 GitHub。GitHub 就像技术人员的淘宝一样,里面充满了好东西,时时刻刻都可能给你惊喜!
iMike
2020/04/15
5330
git 入门教程之备忘录[译] 转
提交应该是相关更改的包装,例如,修复两个不同的 bug 应该产生两个单独的提交. 小的提交让其他开发者更容易理解此次更改,并且万一出错方便回滚. 在暂存区这类工具以及暂存部分文件的能力下,git 很容易创建细粒度的提交.
雪之梦技术驿站
2019/04/03
5190
git常用命令
start a working area (see also: git help tutorial)
RP道貌不岸然
2019/01/29
3730
git常用命令
Python 基于Python实现Ftp文件上传,下载
支持FTP文件上传、下载,可以上传目录(分区除外),也可以上传单个文件;可以下载整个目录(/根目录除外),也可以下载单个文件
授客
2019/09/11
5.5K0
Python 基于Python实现Ftp文件上传,下载
【Git】Common Git Command Line Operation
Common Git Command Line Operation | Chanvin's Blog (chanvinxiao.com)
阿东
2024/03/05
1500
【Git】Common Git Command Line Operation
pygit:足够的Git客户端创建一个repo,commit,并将自己推送到GitHub
Git因其非常简单的对象模型而闻名(其中包括) - 并且有充分的理由。学习时git我发现本地对象数据库只是目录中的一堆普通文件.git。除了index(.git/index)和pack文件(它们是可选的)之外,这些文件的布局和格式非常简单。
iOSDevLog
2018/07/25
2.3K0
Git命令集之一——配置参数 原
这个命令用于修改git命令执行的目录,例如在桌面执行如下命令和进入到IBox文件夹中执行status是一样的:
珲少
2018/08/15
3890
Git 和 GitHub:从入门到实践2 Git 和 GitHub 基础配置
原文地址:https://www.ibm.com/developerworks/cn/opensource/os-cn-git-and-github-2/index.html
mafeifan
2019/01/28
6940
Git使用教程
官网下载:https://git-scm.com/downloads 下载完成后使用默认进行安装。
张小驰出没
2021/12/06
6480
Git 速查表(速查大全)
原文链接:http://blog.kesixin.xin/article/61 今天查git命令的时候看到这篇文章,总结的很好,转载一发 Git命令大致分为这几个模块: 序号 模块 功能 1 CREATE 关于创建的 2 LOCAL CHANGES 关于本地改动方面的 3 COMMIT HISTORY 关于提交历史的 4 BRANCHES & TAGS 关于分支和标签类的 5 UPDATE & PUBLISH 关于更新和发布的 6 MERGE & REBASE 关于分支合并类的 7 UNDO
一个淡定的打工菜鸟
2018/09/06
5590
Git 的奇技淫巧
Git是一个 “分布式版本管理工具”,简单的理解版本管理工具:大家在写东西的时候都用过 “回撤” 这个功能,但是回撤只能回撤几步,假如想要找回我三天之前的修改,光用 “回撤” 是找不回来的。而 “版本管理工具” 能记录每次的修改,只要提交到版本仓库,你就可以找到之前任何时刻的状态(文本状态)。
iMike
2019/07/29
1.2K0
python的github3模块详解
python的github3的模块,提供了程序里实现与github交互的功能。附上官方文档:
horan1
2023/07/25
2570
Git 中文参考(三)
使用git mergetool运行多个合并实用程序之一来解决合并冲突。它通常在 git merge 之后运行。
ApacheCN_飞龙
2024/06/26
3090
从9G到0.3G,腾讯会议对他们的git库做了什么?
过去三年在线会议需求井喷,腾讯会议用户量骤增到3亿。快速迭代的背后,腾讯会议团队发现:业务保留了长达5年的历史数据,大量未进行 lfs 转换,新 clone 仓库本地空间占17.7G+。本地磁盘面临严重告急,强烈影响团队 clone 效率。当务之急是将仓库进行瘦身。本栏目特邀腾讯会议的智子研发团队成员李双君,回顾腾讯会议客户端的瘦身历程和经验,欢迎阅读。
腾讯云开发者
2023/08/03
1K0
从9G到0.3G,腾讯会议对他们的git库做了什么?
pytestx容器化执行引擎
前端、后端、pytest均以Docker容器运行服务,单独的容器化执行引擎,项目环境隔离,即用即取,用完即齐,简单,高效。
dongfanger
2023/08/26
1970
pytestx容器化执行引擎
Git 奇技淫巧,快拿去用吧~
Git 是一个 “分布式版本管理工具”,简单的理解版本管理工具:大家在写东西的时候都用过 “回撤” 这个功能,但是回撤只能回撤几步,假如想要找回我三天之前的修改,光用 “回撤” 是找不回来的。而 “版本管理工具” 能记录每次的修改,只要提交到版本仓库,你就可以找到之前任何时刻的状态(文本状态)。
架构师修炼
2020/11/23
5100
Git 奇技淫巧,快拿去用吧~
相关推荐
如何使用 Python 操作 Git 代码?GitPython 入门介绍
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验