mikroskeem
mikroskeem

Reputation: 47

Use bare repo with git-python

When I'm trying to add files to bare repo:

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 <...>

I only understood that I can add files only by Repo.index.add.

Is using bare repo with git-python module even possible? Or I need to use subprocess.call with git --work-tree=... --git-dir=... add ?

Upvotes: 1

Views: 3568

Answers (1)

galarius
galarius

Reputation: 118

You can not add files into bare repositories. They are for sharing, not for working. You should clone bare repository to work with it. There is a nice post about it: www.saintsjd.com/2011/01/what-is-a-bare-git-repository/

UPDATE (16.06.2016)

Code sample as requested:

    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)

Upvotes: 3

Related Questions