Search code examples
pythonworking-directory

How can you loop through python directories and stop once at root


In Python, I'm using a while loop to test whether the CWD is a git repository. If it's not, the CWD is changed (..) and tested again.

If a git repository is found then the function works as expected. However, if no git repository is found, the while loop keeps going because os.chdir('..') doesn't generate an error, even if the CWD is at /.

def get_git_repo():
    path = os.getcwd()
    original_path = path
    is_git_repo = False
    while not is_git_repo:
        try:
            repo = git.Repo(path).git_dir
            is_git_repo = True
        except git.exc.InvalidGitRepositoryError:
            is_git_repo = False
            path = os.chdir('..')
    os.chdir(original_path)
    return repo

To try and fix this, I added a test to check if the CWD is /, but that doesn't work and the while loop still carries on forever.

How can I bail out of the function once the CWD is /, and is not a git repository?

def get_git_repo():
    ...
        except git.exc.InvalidGitRepositoryError:
            is_git_repo = False
            if not path == '/':
                path = os.chdir('..')
            else:
                raise Exception("Unable to discover path to git repository.")
    ...

Solution

  • the problem of your code is that os.chdir('..') return None, not the current path.

    You need to get the current dir after the change:

    os.chdir('..')
    path = os.getcwd()