有时候,需要做复杂的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)
