gitpython使用简介

gitpython使用简介

  • 从远程仓库clone代码
  • 执行git常用命令
    • 我的示例

从远程仓库clone代码

repo = Repo.clone_from(r'https://gitlab-ci-token:{0}@{1}'.format(git_token, git_host), r'./ldap-backup')

该方式使用personal token来拉取代码。拉取到ldap-backup目录。

执行git常用命令

You can’t commit against a bare repository. You can only push/pull to them. By parallel think about how you would do this locally. Try cloning a bare repo and doing the actions, they won’t work.

I’m not intimately familiar with the pythonic git bindings, but would imagine that you would need to clone a working repository, optionally checkout a given branch instead of master, do your work, call git add against just that stuff, and then commit.

Also, repo.untracked_files is a no op that simply lists them, it doesn’t add them.

Honestly it looks like you blindly copy pasted from https://pythonhosted.org/GitPython/0.3.1/tutorial.html without actually reading what it had to say.

you’ll need to manipulate the Index Object for example

index = repo.index
for ( path, stage ), entry in index.entries.iteritems: pass
index.add(['SOMEFILE'])
new_commit = index.commit("YOUR COMMIT MESSAGE")
#do somethign with new commit

Another example I found

import git
repo = git.Repo( '/home/me/repodir' )
print repo.git.status()
# checkout and track a remote branch
print repo.git.checkout( 'origin/somebranch', b='somebranch' )
# add a file
print repo.git.add( 'somefile' )
# commit
print repo.git.commit( m='my commit message' )
# now we are one commit ahead
print repo.git.status()
# now push

来源:https://stackoverflow.com/questions/22670765/how-to-pull-push-with-remote-branch

我的示例

repo = Repo(r"./ldap-backup") #如果本地仓库已建立,则使用Repo('local_reposity'),使用Repo.clone_from()则从远程仓库拉取到本地。
index = repo.index
changes = [ item.a_path for item in repo.index.diff(None) ] #将modified的文件组成list对象,元素为修改文件的文件名。
repo.git.add(changes)
rq = time.strftime('%Y-%m-%d', time.localtime(time.time()))
repo.git.commit(m="backup at {0}".format(rq)) #提交commit命令,实际git命令为:git commit -m "backup at time"
repo.git.push() #push代码到远程仓库,可指定本地分支和远程分支名。

你可能感兴趣的:(gitpython使用简介)