美文网首页Git
Python使用GitPython操作Git版本库

Python使用GitPython操作Git版本库

作者: Ethandyp | 来源:发表于2018-11-12 16:23 被阅读142次

1、导包
from git import *
2、初始化git仓库

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
empty_repo = Repo.init(os.path.join(CURRENT_DIR, 'bbs'))    # bbs目录不存在则新建

3、如果git仓库已存在,直接获取
repo = Repo(os.path.join(CURRENT_DIR, 'bbs'))
4、获取当前远程库
repo.remotes # 获取当前有哪些远程库 = git remote -v命令,返回一个repo列表
5、新建远程库

 # 新建远程库 = git remote add origin git_url, 返回Remote对象(<class 'git.remote.Remote'>)
origin = repo.create_remote('origin', git_url)   

6、fetch
origin.fetch()
7、建立一个关联远程分支的本地分支,分三步

empty_repo.create_head('master', origin.refs.master) # create local branch "master" from remote "master"
empty_repo.heads.master.set_tracking_branch(origin.refs.master) # set local "master" to track remote "master
empty_repo.heads.master.checkout() # checkout local "master" to working tree

# 以上三步可以简化为一行代码
repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()    # 建立本地master分支,关联远程master分支,checkout

8、获取所有远程分支

origin.refs    # 返回所有远程分支列表
 [<git.RemoteReference "refs/remotes/new_origin/develop">, <git.RemoteReference "refs/remotes/new_origin/master">]

9、获取所有本地分支(git.HEAD)和远程分支(git.RemoteReference)
repo.refs # 返回所有本地分支列表
10、获取本地heads
repo.heads # 返回Head列表
11、获取当前head指向
repo.head.reference
12、切换分支

a、本地存在此分支
repo.head.reference = repo.heads.develop
b、本地不存在,需要从远程拉去
repo.create_head('master', origin.refs.master).set_tracking_branch(origin.refs.master).checkout()

相关文章

  • Python使用GitPython操作Git版本库

    1、导包from git import *2、初始化git仓库 3、如果git仓库已存在,直接获取repo = R...

  • Python_GitPython的使用

    GitPython 是一个用于操作 Git 版本库的 python 包,它提供了一系列的对象模型(库 - Repo...

  • Python 中的 Git 开发包 GitPython

    前言 GitPython 是一个 Python 库用来和 Git 资料库进行交互,提供各种级别的操作,例如高级的 ...

  • Python操作Git库 `GitPython`

    参考文章参考文章复杂点的参考 试了一圈发现,git库的用法设置非常符合原生git命令,只不过之间加了个.而已。比如...

  • Python-gitpython模块(git操作)

    gitpython模块官网

  • PyMySQL in Django

    使用PyMySQL操作mysql数据库 适用环境 python版本 >=2.6或3.3 mysql版本>=4.1 ...

  • Python多线程

    Python内置库:threading(多线程操作) Python的线程操作在旧版本中使用的是thread模块,在...

  • git常用命令

    git版本库操作 初始化一个Git仓库,使用git init命令。 添加文件到Git仓库,分两步: 第一步:使用命...

  • git 常用指令

    如何使用git管理代码 git 常用命令速查 创建版本库 git clone (url) #克隆远程版本库 git...

  • Git 常用命令

    1、创建版本库 git init: 创建版本库之后,使用 git init 命令把这个目录变成Git可管...

网友评论

    本文标题:Python使用GitPython操作Git版本库

    本文链接:https://www.haomeiwen.com/subject/obecfqtx.html