|
| 1 | +import os |
| 2 | +import subprocess |
| 3 | +import shutil |
| 4 | +import tempfile |
| 5 | +import git |
| 6 | + |
| 7 | +def invoke_git_extras_command(name): |
| 8 | + current_dir = os.path.dirname(os.path.abspath(__file__)) |
| 9 | + git_extras_bin = os.path.join(current_dir, "..", "bin") |
| 10 | + return subprocess.run(os.path.join(git_extras_bin, name), capture_output=True) |
| 11 | + |
| 12 | +class TempRepository: |
| 13 | + def __init__(self, repo_work_dir = None): |
| 14 | + if repo_work_dir == None: |
| 15 | + repo_work_dir = tempfile.mkdtemp() |
| 16 | + self._cwd = repo_work_dir |
| 17 | + self._git_repo = git.Repo.init(repo_work_dir) |
| 18 | + self._files = [] |
| 19 | + |
| 20 | + def switch_cwd_under_repo(self): |
| 21 | + os.chdir(self._cwd) |
| 22 | + print(f"The current work directory has switched to {self._cwd}") |
| 23 | + |
| 24 | + def get_cwd(self): |
| 25 | + return self._cwd |
| 26 | + |
| 27 | + def get_repo_git(self): |
| 28 | + return self._git_repo.git |
| 29 | + |
| 30 | + def get_file(self, index): |
| 31 | + return self._files[index] |
| 32 | + |
| 33 | + def get_files(self): |
| 34 | + return self._files |
| 35 | + |
| 36 | + def create_tmp_dir(self): |
| 37 | + tmp_dir = tempfile.mkdtemp() |
| 38 | + return tmp_dir |
| 39 | + |
| 40 | + def create_tmp_file(self, temp_dir = None): |
| 41 | + if temp_dir == None: |
| 42 | + temp_dir = self._cwd |
| 43 | + |
| 44 | + tmp_file = tempfile.mkstemp(dir=temp_dir) |
| 45 | + self._files.append(tmp_file[1]) |
| 46 | + return tmp_file |
| 47 | + |
| 48 | + def remove_tmp_file(self, file_path): |
| 49 | + os.remove(file_path) |
| 50 | + print(f"File {file_path} has been removed") |
| 51 | + |
| 52 | + def writefile(self, temp_file, data): |
| 53 | + if data == None: |
| 54 | + return |
| 55 | + |
| 56 | + with open(temp_file, "w", encoding="utf-8") as f: |
| 57 | + f.write(data) |
| 58 | + |
| 59 | + def teardown(self): |
| 60 | + shutil.rmtree(self._cwd, ignore_errors=True) |
| 61 | + print(f"The temp directory {self._cwd} has been removed") |
| 62 | + |
| 63 | + def invoke_extras_command(self, name): |
| 64 | + command = "git-" + name |
| 65 | + print(f"Invoke the git-extras command - {command}") |
| 66 | + return invoke_git_extras_command(command) |
0 commit comments