当前位置: 首页 > 后端技术 > Python

如何使用Python操作Git代码?GitPython简介

时间:2023-03-26 11:37:54 Python

有时候,需要做复杂的Git操作,中间逻辑很多。使用Shell做复杂的逻辑运算和流程控制是一场灾难。所以,用Python来做是一个愉快的选择。这时候就需要一个库来在Python中操作Git。GitPython简介GitPython是一个与Git库交互的Python库,包括低级命令(Plumbing)和高级命令(Porcelain)。它可以实现大部分的Git读写操作,避免了频繁与Shell交互的畸形代码。它不是纯Python实现,而是部分依赖直接执行git命令,部分依赖GitDB。GitDB也是一个Python库。它为.git/objects构建了一个可以直接读写的数据库模型。由于采用流式(stream)读写,运行效率高,内存占用低。GitPython安装pipinstallGitPython依赖于GitDB,会自动安装,但需要额外安装可执行的git命令。基本用法initimportgitrepo=git.Repo.init(path='.')这会在当前目录中创建一个Git存储库。当然,路径可以自定义。由于git.Repo实现了__enter__和__exit__,所以它可以与with结合使用。withgit.Repo.init(path='.')asrepo:#dosthwithrepo但是由于只实现了一些清理操作,关闭后仍然可以读写,所以使用这种形式的必要性是不高。详见附件。有两种类型的克隆克隆。一种是从当前库克隆到另一个位置:new_repo=repo.clone(path='../new')另一种是从URL克隆到本地位置:new_repo=git.Repo.clone_from(url='git@github.com:USER/REPO.git',to_path='../new')commitwithopen('test.file','w')asfobj:fobj.write('第一行\n')repo.index.add(items=['test.file'])repo.index.commit('writealineintotest.file')withopen('test.file','aw')asfobj:fobj.write('2ndline\n')repo.index.add(items=['test.file'])repo.index.commit('writeanotherlineintotest.file')statusGitPython没有实现原来的git状态,并提供一些信息。>>>repo.is_dirty()False>>>withopen('test.file','aw')作为fobj:>>>fobj.write('dirtyline\n')>>>repo.is_dirty()True>>>repo.untracked_files[]>>>withopen('untracked.file','w')asfobj:>>>fobj.write('')>>>repo.untracked_files['untracked.file']checkout(清除所有修改)>>>repo.is_dirty()True>>>repo.index.checkout(force=True)at0x7f2bf35e6b40>>>>repo.is_dirty()Falsebranchgetcurrentbranch:head=repo.head创建新分支:new_head=repo.create_head('new_head','HEAD^')切换分支:new_head.checkout()head.checkout()删除分支:git.Head.delete(repo,new_head)#orgit.Head.delete(repo,'new_head')merge下面演示如何将另一个分支(master)合并到一个分支(other)中。master=repo.heads.masterother=repo.create_head('other','HEAD^')other.checkout()repo.index.merge_tree(master)repo.index.commit('Mergefrommastertoother')remote,fetch,pull,push创建远程:remote=repo.create_remote(name='gitlab',url='git@gitlab.com:USER/REPO.git')远程交互操作:remote=repo.remote()remote。fetch()remote.pull()remote.push()删除remote:repo.delete_remote(remote)#orrepo.delete_remote('gitlab')还有其他相关操作比如Tag和Submodule,不是很常用,所以我不会在这里介绍它们。GitPython的优点是在做读操作的时候可以方便的获取内部信息。缺点是在做写操作的时候感觉很不爽。当然也支持直接执行git操作。git=repo.gitgit.status()git.checkout('HEAD',b="my_new_branch")git.branch('another-new-one')git.branch('-D','another-new-one')这……感觉又回到了老样子,而且还是觉得怪怪的。其他操作Git子进程的方法这就是所谓的“老办法”。在另一个进程中执行Shell命令,通过stdio解析返回结果。importsubprocesssubprocess.call(['git','status'])dulwichdulwich是一个纯Python实现的Git交互库,以后有时间再研究一下。官网:https://www.dulwich.io/pygit2pygit2是一个基于libgit2的Python库。底层是C,而上层Python只是一个接口,运行效率应该是最高的,但顾还是放弃了。缺点是需要在环境中预装libgit2。相比之下,GitPython只需要环境预置Git,就简单多了。官网:http://www.pygit2.org/以上就是本次分享的全部内容。想了解更多python知识,请前往公众号:Python编程学习圈,发“J”免费领取,每日干货分享