如何使用 Python 完成 Git 管理?-

如何使用 Python 完成 Git 管理?- 作者:匿蟒链接:https://note.qido

如何使用 Python 完成 Git 管理?-

作者:匿蟒

链接:https://note.qidong.name/2018/01/gitPython

有时,需要做复杂的 Git 操作,并且有很多中间逻辑。用 Shell 做复杂的逻辑运算与流程控制就是一个灾难。所以,用 Python 来实现是一个愉快的选择。这时,就需要在 Python 中操作 Git 的库。

0. GitPython 简介

GitPython是一个与Git库交互的Python库,包括底层命令(Plumbing)与高层命令(Porcelain)。它可以实现绝大部分的Git读写操作,避免了频繁与Shell交互的畸形代码。它并非是一个纯粹的Python实现,而是有一部分依赖于直接执行 git 命令,另一部分依赖于GitDB。

GitDB也是一个Python库。它为 .git/objects 建立了一个数据库模型,可以实现直接的读写。由于采用流式(stream)读写,所以运行高效、内存占用低。

1. GitPython安装pipinstall GitPython

其依赖GitDB会自动安装,不过可执行的 git 命令需要额外安装。

2. 基本用法initimportgit

repo = git.Repo.init(path='.')

这样就在当前目录创建了一个Git库。当然,路径可以自定义。

由于 git.Repo 实现了 __enter__ 与 __exit__ ,所以可以与 with 联合使用。

withgit.Repo.init(path='.')asrepo:

#dosthwithrepo

不过,由于只是实现了一些清理操作,关闭后仍然可以读写,所以使用这种形式的必要性不高。详见附录。

clone

clone分两种。一是从当前库clone到另一个位置:

new_repo= repo.clone(path='../new')

二是从某个URL那里clone到本地某个位置:

new_repo= git.Repo.clone_from(url='git@github.com:USER/REPO.git', to_path='../new')

commitwithopen('test.file','w')asfobj:

fobj.write('1st linen')

repo.index.add(items=['test.file'])

repo.index.commit('write a line into test.file')

withopen('test.file','aw')asfobj:

fobj.write('2nd linen')

repo.index.add(items=['test.file'])

repo.index.commit('write another line into test.file')

status

GitPython并未实现原版 git status ,而是给出了部分的信息。

>>> repo.is_dirty

False

>>> with open('test.file','aw') asfobj:

>>> fobj.write('dirty linen')

>>> repo.is_dirty

True

>>> repo.untracked_files

[]

>>> with open('untracked.file','w') asfobj:

>>> fobj.write('')

>>> repo.untracked_files

['untracked.file']

checkout(清理所有修改)>>> repo.is_dirty

True

>>> repo.index.checkout(force=True)

<generator object <genexpr> at0x7f2bf35e6b40>

>>> repo.is_dirty

False

branch

获取当前分支:

head= repo.head

新建分支:

new_head= repo.create_head('new_head','HEAD^')

切换分支:

new_head.checkout

head.checkout

删除分支:

git.Head.delete(repo, new_head)

# or

git.Head.delete(repo,'new_head')

merge

以下演示如何在一个分支( other ),merge另一个分支( master )。

master = repo.heads.master

other = repo.create_head('other','HEAD^')

other.checkout

repo.index.merge_tree(master)

repo.index.commit('Merge from master to other')

remote, fetch, pull, push

创建remote:

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)

# or

repo.delete_remote('gitlab')

其它

其它还有Tag、Submodule等相关操作,不是很常用,这里就不介绍了。

GitPython的优点是在做读操作时可以方便地获取内部信息,缺点是在做写操作时感觉很不顺手,隔靴搔痒。当然,它还支持直接执行 git 操作。

git= repo.git

git.status

git.checkout('HEAD', b="my_new_branch")

作者: 雨林木风

为您推荐

返回顶部