|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import os.path |
| 4 | +from .config import GlobalConfig |
| 5 | +from .fs import FileSystem |
| 6 | +from shutil import rmtree |
| 7 | + |
| 8 | +log = logging.getLogger(__name__) |
| 9 | + |
| 10 | + |
| 11 | +class CloneWorkspace: |
| 12 | + |
| 13 | + def __init__(self, fs: FileSystem, project_root: str, |
| 14 | + original_root_path: str= ""): |
| 15 | + |
| 16 | + self.PROJECT_ROOT = project_root |
| 17 | + self.repo = None |
| 18 | + self.hash = None |
| 19 | + |
| 20 | + if original_root_path.startswith( |
| 21 | + "git://") and "?" in original_root_path: |
| 22 | + repo_and_hash = original_root_path.split("?") |
| 23 | + self.repo = repo_and_hash[0] |
| 24 | + original_root_path = self.repo |
| 25 | + self.hash = repo_and_hash[1] |
| 26 | + |
| 27 | + if original_root_path.startswith("git://"): |
| 28 | + original_root_path = original_root_path[6:] |
| 29 | + |
| 30 | + # turn the original root path into something that can be used as a |
| 31 | + # file/path name or cache key |
| 32 | + self.key = original_root_path.replace("/", ".").replace("\\", ".") |
| 33 | + if self.hash: |
| 34 | + self.key = ".".join((self.key, self.hash)) |
| 35 | + |
| 36 | + # TODO: allow different Python versions per project/workspace |
| 37 | + self.PYTHON_PATH = GlobalConfig.PYTHON_PATH |
| 38 | + self.CLONED_PROJECT_PATH = os.path.join( |
| 39 | + GlobalConfig.CLONED_PROJECT_PATH, self.key) |
| 40 | + log.debug("Setting Python path to %s", self.PYTHON_PATH) |
| 41 | + log.debug("Setting Cloned Project path to %s", |
| 42 | + self.CLONED_PROJECT_PATH) |
| 43 | + |
| 44 | + self.fs = fs |
| 45 | + |
| 46 | + def clone_project(self): |
| 47 | + """ |
| 48 | + Clones the project from the provided filesystem into the local |
| 49 | + cache |
| 50 | + """ |
| 51 | + all_files = self.fs.walk(self.PROJECT_ROOT) |
| 52 | + for file_path, file_contents in self.fs.batch_open(all_files, parent_span=None): |
| 53 | + # strip the leading '/' so that we can join it properly |
| 54 | + file_path = os.path.relpath(file_path, "/") |
| 55 | + |
| 56 | + cache_file_path = os.path.join(self.CLONED_PROJECT_PATH, file_path) |
| 57 | + |
| 58 | + os.makedirs(os.path.dirname(cache_file_path), exist_ok=True) |
| 59 | + |
| 60 | + with open(cache_file_path, "w") as f: |
| 61 | + f.write(file_contents) |
| 62 | + |
| 63 | + def cleanup(self): |
| 64 | + log.info("Removing cloned project cache %s", self.CLONED_PROJECT_PATH) |
| 65 | + rmtree(self.CLONED_PROJECT_PATH, ignore_errors=True) |
0 commit comments