Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I delete a temp directory on Windows after using gitpython?

I have the following Python function, which I am running on Windows 7:

def update():
    temp_dir = tempfile.mkdtemp()
    git.Git().clone('my_repo', temp_dir)
    try:
        repo = git.Repo(temp_dir)
        repo.index.add('*')
        repo.index.commit('Empty commit')
    finally:
        from git.util import rmtree
        rmtree(temp_dir)

Unfortunately, on the rmtree line, I get:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'c:\\users\\myaccount\\appdata\\local\\temp\\tmpdega8h\\.git\\objects\\pack\\pack-0ea07d13498ab92388dc33fbabaadf37511623c1.idx'

What should I be doing to remove the temp directory in Windows?

like image 547
Chris B. Avatar asked Apr 02 '26 21:04

Chris B.


1 Answers

A lot of effort has been spend to fix this behavior in Windows, where file-locking is the default behavior of the filesystem, but as explained in the Limitations:

[GitPython] was written in a time where destructors (as implemented in the __del__ method) still ran deterministically."

In case you still want to use it in such a context, you will want to search the codebase for __del__ implementations and call these yourself when you see fit.

In any case, this the trick employed by the test-cases of the project may help:

repo_dir = tempfile.mktemp()
repo = Repo.init(repo_dir)
try:
    ## use the repo

finally:
    repo.git.clear_cache()    # kill deamon-procs responding to hashes with objects
    repo = None
    if repo_dir is not None:
        gc.collect()
        gitdb.util.mman.collect()  # kept open over git-object files
        gc.collect()
        rmtree(repo_dir)

NOTE: this is what repo.close() does since 2.1.1 (Dec 2016).

like image 166
ankostis Avatar answered Apr 04 '26 11:04

ankostis