-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.py
More file actions
280 lines (239 loc) · 8.74 KB
/
command.py
File metadata and controls
280 lines (239 loc) · 8.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import os
import subprocess
import traceback
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Tuple
from PyQt5.QtCore import pyqtSignal, QThreadPool, QObject, QRunnable
from src.callback import CallbackScriptBuilder
class Command(ABC):
def __init__(self, repo_path: str):
super().__init__()
self.repo_path = repo_path
@abstractmethod
def execute(self, ):
"""执行命令"""
pass
class WorkerSignals(QObject):
finished = pyqtSignal(bool, str) # success, output
class CommandWorker(QRunnable):
def __init__(self, command, callback=None):
super().__init__()
self.command = command
self.callback = callback
self.signals = WorkerSignals()
if callback:
self.signals.finished.connect(callback)
def run(self):
"""在工作线程中执行"""
try:
print(f"执行命令: {self.command.__class__.__name__}")
success, output = self.command.execute()
self.signals.finished.emit(success, output)
except Exception as e:
error_msg = f"命令执行异常: {str(e)}\n{traceback.format_exc()}"
print(error_msg)
self.signals.finished.emit(False, error_msg)
# 获取指定分支的提交信息
class GetBranchCommitsCommand(Command):
def __init__(self, repo_path: str, branch_name: str):
"""
:param repo_path:仓库路径
:param branch_name:分支名称
"""
super().__init__(repo_path)
self.branch_name = branch_name
def execute(self):
try:
print("获取指定分支的提交信息")
result = subprocess.run([
"git",
"log",
"--pretty=format:%h %an <%ae> %ad %s %d",
"--date=iso",
self.branch_name
], cwd=self.repo_path, encoding='utf-8', errors='replace', capture_output=True, text=True)
if result.returncode == 0:
return True, result.stdout
else:
return False, result.stderr
except Exception as e:
return False, str(e)
# 编辑单条提交信息
class EditSingleCommitCommand(Command):
def __init__(self, repo_path: str, commit_id: str, new_author: str, new_email: str,
new_commit_message: str, new_commit_time: datetime):
"""
:param repo_path:仓库路径
:param commit_id:提交ID
:param new_author:新的作者
:param new_email:新的邮箱
:param new_commit_message:新的提交信息
:param new_commit_time:新的提交时间
"""
super().__init__(repo_path)
self.commit_id = commit_id
self.new_commit_message = new_commit_message
self.new_commit_time = new_commit_time
self.new_author = new_author
self.new_email = new_email
def execute(self):
# 创建文件
file_name = "edit_commit_callback.py"
target_file_path = os.path.join(self.repo_path, file_name)
try:
ok = CallbackScriptBuilder.build_single_commit_callback(
filepath=target_file_path,
target_hash=self.commit_id,
author_name=self.new_author,
author_email=self.new_email,
commit_message=self.new_commit_message,
commit_time=self.new_commit_time # 格式:2024-01-01T10:00:00
)
if not ok:
return False, "生成文件失败"
result = subprocess.run([
"git-filter-repo",
"--commit-callback", file_name
, "--force"
], cwd=self.repo_path, encoding='utf-8',
errors='replace', capture_output=True, text=True)
if result.returncode == 0:
return True, "提交信息修改成功"
else:
return False, result.stderr
except Exception as e:
return False, str(e)
finally:
if os.path.exists(target_file_path):
os.remove(target_file_path)
# 编辑单条提交信息
class EditBulkCommitCommand(Command):
def __init__(self, repo_path: str, commit_changes: dict):
"""
:param repo_path:仓库路径
:param commit_changes:提交信息
"""
super().__init__(repo_path)
self.commit_changes = commit_changes
def execute(self):
# 创建文件
file_name = "rewrite_callback.py"
target_file_path = os.path.join(self.repo_path, file_name)
try:
ok = CallbackScriptBuilder.build_bulk_commit_callback(target_file_path, self.commit_changes)
if not ok:
return False, "生成文件失败"
result = subprocess.run([
"git-filter-repo",
"--commit-callback", file_name
, "--force"
], cwd=self.repo_path, encoding='utf-8',
errors='replace', capture_output=True, text=True)
if result.returncode == 0:
return True, "批量修改作者、邮箱及时间信息成功"
else:
return False, result.stderr
except Exception as e:
return False, str(e)
finally:
if os.path.exists(target_file_path):
os.remove(target_file_path)
# 切换分支
class CheckoutCommand(Command):
def __init__(self, repo_path: str, branch_name: str):
"""
:param repo_path:仓库路径
:param branch_name:分支名称
"""
super().__init__(repo_path)
self.branch_name = branch_name
def execute(self):
try:
result = subprocess.run([
"git",
"checkout",
self.branch_name
], cwd=self.repo_path, encoding='utf-8',
errors='replace', capture_output=True, text=True)
if result.returncode == 0:
return True, "切换分支成功"
else:
return False, result.stderr
except Exception as e:
return False, str(e)
# 获取所有分支
class GetAllBranchesCommand(Command):
def __init__(self, repo_path: str):
"""
:param repo_path:仓库路径
"""
super().__init__(repo_path)
def execute(self):
try:
result = subprocess.run([
"git",
"branch"
, "-a"
], cwd=self.repo_path, encoding='utf-8',
errors='replace', capture_output=True, text=True)
if result.returncode == 0:
branches = [line.strip() for line in result.stdout.split("\n") if line.strip() != '']
return True, branches
else:
return False, result.stderr
except Exception as e:
return False, str(e)
# 获取远程仓库地址
class GetRemoteRepoUrlCommand(Command):
def __init__(self, repo_path: str):
"""
:param repo_path:仓库路径
"""
super().__init__(repo_path)
def execute(self):
try:
result = subprocess.run([
"git",
"remote",
"get-url",
"origin"
], cwd=self.repo_path, encoding='utf-8',
errors='replace', capture_output=True, text=True)
if result.returncode == 0:
return True, result.stdout.strip()
else:
return False, result.stderr
except Exception as e:
return False, str(e)
# 设置远程仓库
class SetRemoteUrlCommand(Command):
def __init__(self, repo_path: str, remote_url: str):
super().__init__(repo_path)
self.remote_url = remote_url
def execute(self) -> Tuple[bool, str]:
try:
result = subprocess.run(["git", "remote", "add", "origin", self.remote_url], cwd=self.repo_path,
capture_output=True, text=True)
if result.returncode == 0:
return True, result.stdout.strip()
else:
return False, result.stderr
except Exception as e:
return False, str(e)
class Executor:
@staticmethod
def executeAsync(command: Command, callback=None):
try:
worker = CommandWorker(command, callback)
# 设置自动删除
worker.setAutoDelete(True)
# 使用全局线程池
QThreadPool.globalInstance().start(worker)
except Exception as e:
print(f"提交异步任务失败: {e}")
if callback:
callback(False, str(e))
@staticmethod
def execute(command: Command):
return command.execute()