|
1 | 1 | import datajoint as dj
|
| 2 | +import pathlib |
| 3 | + |
2 | 4 |
|
3 | 5 | dj.config['enable_python_native_blobs'] = True
|
| 6 | + |
| 7 | + |
| 8 | +def find_full_path(root_directories, relative_path): |
| 9 | + """ |
| 10 | + Given a relative path, search and return the full-path |
| 11 | + from provided potential root directories (in the given order) |
| 12 | + :param root_directories: potential root directories |
| 13 | + :param relative_path: the relative path to find the valid root directory |
| 14 | + :return: root_directory (pathlib.Path object) |
| 15 | + """ |
| 16 | + relative_path = pathlib.Path(relative_path) |
| 17 | + |
| 18 | + if relative_path.exists(): |
| 19 | + return relative_path |
| 20 | + |
| 21 | + # turn to list if only a single root directory is provided |
| 22 | + if isinstance(root_directories, (str, pathlib.Path)): |
| 23 | + root_directories = [root_directories] |
| 24 | + |
| 25 | + for root_dir in root_directories: |
| 26 | + if (pathlib.Path(root_dir) / relative_path).exists(): |
| 27 | + return pathlib.Path(root_dir) / relative_path |
| 28 | + |
| 29 | + raise FileNotFoundError('No valid full-path found (from {})' |
| 30 | + ' for {}'.format(root_directories, relative_path)) |
| 31 | + |
| 32 | + |
| 33 | +def find_root_directory(root_directories, full_path): |
| 34 | + """ |
| 35 | + Given multiple potential root directories and a full-path, |
| 36 | + search and return one directory that is the parent of the given path |
| 37 | + :param root_directories: potential root directories |
| 38 | + :param full_path: the relative path to search the root directory |
| 39 | + :return: full-path (pathlib.Path object) |
| 40 | + """ |
| 41 | + full_path = pathlib.Path(full_path) |
| 42 | + |
| 43 | + if not full_path.exists(): |
| 44 | + raise FileNotFoundError(f'{full_path} does not exist!') |
| 45 | + |
| 46 | + # turn to list if only a single root directory is provided |
| 47 | + if isinstance(root_directories, (str, pathlib.Path)): |
| 48 | + root_directories = [root_directories] |
| 49 | + |
| 50 | + try: |
| 51 | + return next(pathlib.Path(root_dir) for root_dir in root_directories |
| 52 | + if pathlib.Path(root_dir) in set(full_path.parents)) |
| 53 | + |
| 54 | + except StopIteration: |
| 55 | + raise FileNotFoundError('No valid root directory found (from {})' |
| 56 | + ' for {}'.format(root_directories, full_path)) |
0 commit comments