Last active
August 29, 2015 14:03
-
-
Save genba/94b208595e6a6562ba37 to your computer and use it in GitHub Desktop.
Get all parent directories of a given path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def iter_parent_dirs(endpath): | |
previous = '' | |
basepath = endpath | |
while previous != '/': | |
yield basepath | |
previous = basepath | |
basepath, _ = os.path.split(basepath) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import os | |
from iter_parent_dirs import iter_parent_dirs | |
for dirpath in iter_parent_dirs(os.getcwd()): | |
if os.path.isdir(os.path.join(dirpath, '.git')): | |
print('Found git repository at {path}'.format(path=dirpath)) | |
else: | |
print('No git repository at {path}'.format(path=dirpath)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_git_repo(dirpath): | |
for dirpath in iter_parent_dirs(dirpath): | |
repo_path = os.path.join(dirpath, '.git') | |
if os.path.isdir(repo_path): | |
return repo_path | |
return None | |
REPODIRS = ('.cvs', '.svn', '.git', '.hg', '.bzr') | |
def find_repo(dirpath): | |
for dirpath in iter_parent_dirs(dirpath): | |
for repo_dir in REPODIRS: | |
repo_path = os.path.join(dirpath, repo_dir) | |
if os.path.isdir(repo_path): | |
return repo_path | |
return None | |
def find_all_repos(dirpath, return_dict=False): | |
if return_dict: | |
repos = {} | |
else: | |
repos = [] | |
for dirpath in iter_parent_dirs(dirpath): | |
for repo_dir in REPODIRS: | |
repo_path = os.path.join(dirpath, repo_dir) | |
if os.path.isdir(repo_path): | |
if return_dict: | |
key = repo_dir.lstrip('.') | |
try: | |
repos[key].append(repo_path) | |
except KeyError: | |
repos[key] = [repo_path] | |
else: | |
repos.append(repo_path) | |
return repos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment