将裸仓库与 git-python 一起使用

Use bare repo with git-python

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

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 ?

您不能将文件添加到裸存储库中。他们是为了分享,而不是为了工作。您应该克隆裸存储库以使用它。有一个很好的 post 关于它: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)