使用git-python的裸仓库

时间:2016-03-14 22:34:05

标签: python git gitpython

当我尝试将文件添加到裸仓库时:

import git
r = git.Repo("./bare-repo")
r.working_dir("/tmp/f")
print(r.bare) # True
r.index.add(["/tmp/f/foo"]) # Exception, can't use bare repo <...>

我只知道我只能通过Repo.index.add添加文件。

是否可以使用带有git-python模块的裸仓库?或者我需要将subprocess.callgit --work-tree=... --git-dir=... add一起使用?

1 个答案:

答案 0 :(得分:1)

您无法将文件添加到裸存储库中。他们是为了分享,而不是为了工作。您应该克隆裸存储库以使用它。有一篇很好的文章:www.saintsjd.com/2011/01/what-is-a-bare-git-repository /

更新(16.06.2016)

请求的代码示例:

    import git
    import os, shutil
    test_folder = "temp_folder"
    # This is your bare repository
    bare_repo_folder = os.path.join(test_folder, "bare-repo")
    repo = git.Repo.init(bare_repo_folder, bare=True)
    assert repo.bare
    del repo

    # This is non-bare repository where you can make your commits
    non_bare_repo_folder = os.path.join(test_folder, "non-bare-repo")
    # Clone bare repo into non-bare
    cloned_repo = git.Repo.clone_from(bare_repo_folder, non_bare_repo_folder)
    assert not cloned_repo.bare

    # Make changes (e.g. create .gitignore file)
    tmp_file = os.path.join(non_bare_repo_folder, ".gitignore")
    with open(tmp_file, 'w') as f:
        f.write("*.pyc")

    # Run git regular operations (I use cmd commands, but you could use wrappers from git module)
    cmd = cloned_repo.git
    cmd.add(all=True)
    cmd.commit(m=".gitignore was added")

    # Push changes to bare repo
    cmd.push("origin", "master", u=True)

    del cloned_repo  # Close Repo object and cmd associated with it
    # Remove non-bare cloned repo
    shutil.rmtree(non_bare_repo_folder)