打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
使用 Python 操作 Git 版本库

GitPython 是一个用于操作 Git 版本库的 python 包,

它提供了一系列的对象模型(库 - Repo、树 - Tree、提交 - Commit等)
用于操作版本库中的相应对象。

版本库对象 - Repo

首先,使用包含 .git 文件夹的版本库路径创建 git.Repo 对象

from git import Repo# 创建版本库对象repo = git.Repo(r'E:\Notes')

然后便可以使用这个 Repo 对象对版本库进行操作,如:

# 版本库是否为空版本库repo.bare# 当前工作区是否干净repo.is_dirty()# 版本库中未跟踪的文件列表repo.untracked_files# 克隆版本库repo.clone('clone_path')# 压缩版本库到 tar 文件with open('repo.tar', 'wb') as fp:    repo.archive(fp)# 新建分支repo.create_head('branchname')# 查看当前分支repo.active_branch

索引/暂存区对象 - Index

Git 术语中,index 表示暂存区,为下次将要提交到版本库里的文件,
GitPython 提供 Repo.Index 来操作暂存区,如添加、提交操作

index = repo.indexindex.add(['new.txt'])index.remove(['old.txt'])index.commit('this is a test')

远程版本库操作 - Remotes

Remotes 用于操作远程版本库,可以通过 Repo.remote 方法获取远程版本库,
Repo.Remotes 属性获取远程版本库列表

# 获取默认版本库 originremote = repo.remote()# 从远程版本库拉取分支remote.pull()# 推送本地分支到远程版本库remote.push()# 重命名远程分支# remote.rename('new_origin')

直接执行 Git 命令

一般我们在工作目录做了改变之后,就会调用 git add 命令添加文件到暂存区,
然后调用 git commit 命令提交更改,Repo 虽然没有添加、提交方法,
但取而代之提供了一个 git.cmd.Git 对象实现对 Git 命令的调用,
通过 Repo.git 来进行 Git 命令操作。

git = repo.gitgit.add('test1.txt') # git add test1.txtgit.commit('-m', 'this is a test') # git commit -m 'this is a test'

Repo.git.[command] 即相当于调用对应的 git 命令,而调用对应命令方法所用的参数,
会被转换成跟在命令后的参数。

而调用命令方法所用的命名参数会被转换成对应的完整参数,如:git.command(flag=True)
会被转换成 git command --flag 命令执行

总结

基本的 Git 操作可以概括如下:

# 新建版本库对象repo = Repo(r'E:\Notes')# 进行文件修改操作# 获取版本库暂存区index = repo.index# 添加修改文件index.add(['new.txt'])# 提交修改到本地仓库index.commit('this is a test')# 获取远程仓库remote = repo.remote()# 推送本地修改到远程仓库remote.push()
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Repo和Git 版本管理常用命令
Git 常用命令速查表(三)
Git与Repo入门
Git远程操作详解
Git使用基础篇
推荐!手把手教你使用Git | 互联网的那点事
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服