【发布时间】:2021-11-12 11:51:35
【问题描述】:
在 Python 中,我使用 while 循环来测试 CWD 是否是 git 存储库。如果不是,则更改 CWD (..) 并再次测试。
如果找到 git 存储库,则该功能按预期工作。但是,如果没有找到 git 存储库,while 循环将继续进行,因为 os.chdir('..') 不会产生错误,即使 CWD 位于 /。
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
为了尝试解决这个问题,我添加了一个测试来检查 CWD 是否为 /,但这不起作用,while 循环仍然会一直持续下去。
一旦 CWD 是 / 并且不是 git 存储库,我该如何退出该功能?
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.")
...
【问题讨论】: