|
| 1 | +import os |
| 2 | +from datetime import datetime |
| 3 | + |
| 4 | +from PySide6.QtCore import QThread, Signal |
| 5 | +from git import Repo, GitCommandError, InvalidGitRepositoryError, NoSuchPathError |
| 6 | + |
| 7 | + |
| 8 | +# ----------------------- |
| 9 | +# Simple audit logger |
| 10 | +# ----------------------- |
| 11 | +def audit_log(repo_path: str, action: str, detail: str, ok: bool, err: str = ""): |
| 12 | + """ |
| 13 | + Append an audit log entry to 'audit.log' in the repo directory. |
| 14 | + This is useful for compliance and traceability. |
| 15 | + """ |
| 16 | + try: |
| 17 | + path = os.path.join(repo_path if repo_path else ".", "audit.log") |
| 18 | + with open(path, "a", encoding="utf-8") as f: |
| 19 | + ts = datetime.now().isoformat(timespec="seconds") |
| 20 | + f.write(f"{ts}\taction={action}\tok={ok}\tdetail={detail}\terr={err}\n") |
| 21 | + except Exception: |
| 22 | + pass # Never let audit logging failure break the UI |
| 23 | + |
| 24 | + |
| 25 | +# ----------------------- |
| 26 | +# Git service layer |
| 27 | +# ----------------------- |
| 28 | +class GitService: |
| 29 | + """ |
| 30 | + Encapsulates Git operations using GitPython. |
| 31 | + Keeps UI logic separate from Git logic. |
| 32 | + """ |
| 33 | + |
| 34 | + def __init__(self): |
| 35 | + self.repo: Repo | None = None |
| 36 | + self.repo_path: str | None = None |
| 37 | + |
| 38 | + def open_repo(self, path: str): |
| 39 | + try: |
| 40 | + self.repo = Repo(path) |
| 41 | + self.repo_path = path |
| 42 | + audit_log(path, "open_repo", path, True) |
| 43 | + except (InvalidGitRepositoryError, NoSuchPathError) as e: |
| 44 | + audit_log(path, "open_repo", path, False, str(e)) |
| 45 | + raise |
| 46 | + |
| 47 | + def list_branches(self): |
| 48 | + self._ensure_repo() |
| 49 | + branches = [head.name for head in self.repo.heads] |
| 50 | + audit_log(self.repo_path, "list_branches", ",".join(branches), True) |
| 51 | + return branches |
| 52 | + |
| 53 | + def current_branch(self): |
| 54 | + self._ensure_repo() |
| 55 | + try: |
| 56 | + return self.repo.active_branch.name |
| 57 | + except TypeError: |
| 58 | + return "(detached HEAD)" |
| 59 | + |
| 60 | + def checkout(self, branch: str): |
| 61 | + self._ensure_repo() |
| 62 | + try: |
| 63 | + self.repo.git.checkout(branch) |
| 64 | + audit_log(self.repo_path, "checkout", branch, True) |
| 65 | + except GitCommandError as e: |
| 66 | + audit_log(self.repo_path, "checkout", branch, False, str(e)) |
| 67 | + raise |
| 68 | + |
| 69 | + def list_commits(self, branch: str, max_count: int = 100): |
| 70 | + self._ensure_repo() |
| 71 | + commits = list(self.repo.iter_commits(branch, max_count=max_count)) |
| 72 | + data = [ |
| 73 | + { |
| 74 | + "hexsha": c.hexsha, |
| 75 | + "summary": c.summary, |
| 76 | + "author": c.author.name if c.author else "", |
| 77 | + "date": datetime.fromtimestamp(c.committed_date).isoformat(sep=" ", timespec="seconds"), |
| 78 | + } |
| 79 | + for c in commits |
| 80 | + ] |
| 81 | + audit_log(self.repo_path, "list_commits", f"{branch}:{len(data)}", True) |
| 82 | + return data |
| 83 | + |
| 84 | + def show_diff_of_commit(self, commit_sha: str) -> str: |
| 85 | + self._ensure_repo() |
| 86 | + commit = self.repo.commit(commit_sha) |
| 87 | + parent = commit.parents[0] if commit.parents else None |
| 88 | + if parent is None: |
| 89 | + null_tree = self.repo.tree(NULL_TREE) |
| 90 | + diffs = commit.diff(null_tree, create_patch=True) |
| 91 | + else: |
| 92 | + diffs = commit.diff(parent, create_patch=True) |
| 93 | + text = [] |
| 94 | + for d in diffs: |
| 95 | + try: |
| 96 | + text.append(d.diff.decode("utf-8", errors="replace")) |
| 97 | + except Exception: |
| 98 | + pass |
| 99 | + out = "".join(text) if text else "(No patch content)" |
| 100 | + audit_log(self.repo_path, "show_diff", commit_sha, True) |
| 101 | + return out |
| 102 | + |
| 103 | + def stage_all(self): |
| 104 | + self._ensure_repo() |
| 105 | + try: |
| 106 | + self.repo.git.add(all=True) |
| 107 | + audit_log(self.repo_path, "stage_all", "git add -A", True) |
| 108 | + except GitCommandError as e: |
| 109 | + audit_log(self.repo_path, "stage_all", "git add -A", False, str(e)) |
| 110 | + raise |
| 111 | + |
| 112 | + def commit(self, message: str): |
| 113 | + self._ensure_repo() |
| 114 | + if not message.strip(): |
| 115 | + raise ValueError("Commit message is empty.") |
| 116 | + try: |
| 117 | + self.repo.index.commit(message) |
| 118 | + audit_log(self.repo_path, "commit", message, True) |
| 119 | + except Exception as e: |
| 120 | + audit_log(self.repo_path, "commit", message, False, str(e)) |
| 121 | + raise |
| 122 | + |
| 123 | + def pull(self, remote: str = "origin", branch: str | None = None): |
| 124 | + self._ensure_repo() |
| 125 | + if branch is None: |
| 126 | + branch = self.current_branch() |
| 127 | + try: |
| 128 | + res = self.repo.git.pull(remote, branch) |
| 129 | + audit_log(self.repo_path, "pull", f"{remote}/{branch}", True) |
| 130 | + return res |
| 131 | + except GitCommandError as e: |
| 132 | + audit_log(self.repo_path, "pull", f"{remote}/{branch}", False, str(e)) |
| 133 | + raise |
| 134 | + |
| 135 | + def push(self, remote: str = "origin", branch: str | None = None): |
| 136 | + self._ensure_repo() |
| 137 | + if branch is None: |
| 138 | + branch = self.current_branch() |
| 139 | + try: |
| 140 | + res = self.repo.git.push(remote, branch) |
| 141 | + audit_log(self.repo_path, "push", f"{remote}/{branch}", True) |
| 142 | + return res |
| 143 | + except GitCommandError as e: |
| 144 | + audit_log(self.repo_path, "push", f"{remote}/{branch}", False, str(e)) |
| 145 | + raise |
| 146 | + |
| 147 | + def remotes(self): |
| 148 | + self._ensure_repo() |
| 149 | + return [r.name for r in self.repo.remotes] |
| 150 | + |
| 151 | + def _ensure_repo(self): |
| 152 | + if self.repo is None: |
| 153 | + raise RuntimeError("Repository not opened.") |
| 154 | + |
| 155 | + |
| 156 | +# Null tree constant for initial commit diff |
| 157 | +NULL_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904" |
| 158 | + |
| 159 | + |
| 160 | +# ----------------------- |
| 161 | +# Worker thread wrapper |
| 162 | +# ----------------------- |
| 163 | +class Worker(QThread): |
| 164 | + """ |
| 165 | + Runs a function in a separate thread to avoid blocking the UI. |
| 166 | + Emits (result, error) when done. |
| 167 | + """ |
| 168 | + done = Signal(object, object) |
| 169 | + |
| 170 | + def __init__(self, fn, *args, **kwargs): |
| 171 | + super().__init__() |
| 172 | + self.fn = fn |
| 173 | + self.args = args |
| 174 | + self.kwargs = kwargs |
| 175 | + |
| 176 | + def run(self): |
| 177 | + try: |
| 178 | + res = self.fn(*self.args, **self.kwargs) |
| 179 | + self.done.emit(res, None) |
| 180 | + except Exception as e: |
| 181 | + self.done.emit(None, e) |
0 commit comments