-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit_interactive_rebase.py
More file actions
executable file
·307 lines (277 loc) · 13.9 KB
/
Copy pathgit_interactive_rebase.py
File metadata and controls
executable file
·307 lines (277 loc) · 13.9 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python3
"""
Project: git-interactive-rebase-gui-tool
Description: A premium PySide6 GUI for interactive git rebasing, squashing, and rephrasing.
Author: shyjun(n.shyju@gmail.com)
Version: 1.0.0
Date: Feb 2026
"""
import argparse
# Copyright (c) 2026 shyjun
# This project is licensed under the MIT License - see the LICENSE file for details.
import sys
import os
from datetime import datetime
from PySide6.QtWidgets import (
QApplication,
QMessageBox,
)
from PySide6.QtGui import QIcon
from PySide6.QtCore import (
QSettings,
QTimer,
)
from lib.utils import get_assets_path
from lib.git_helpers import (
get_recent_history_start,
get_branch_base_info,
stash_changes,
get_unstaged_files,
commit_file,
bulk_commit_all,
amend_with_head,
stash_pop,
stash_pop_can_apply,
get_full_head_sha,
get_head_sha,
discard_changes,
get_stash_status,
STASH_NOTHING_STASHED,
)
from lib.app_window import (
GitInteractiveRebaseApp,
get_theme_stylesheet,
)
from lib.dialogs import (
UnstagedChangesDialog,
ProgressDialog,
StashNoticeDialog,
)
import shutil
def main():
# 1. Runtime check for Git CLI
if not shutil.which("git"):
raise RuntimeError("Git CLI not found. Please install Git and ensure it is in PATH.")
parser = argparse.ArgumentParser(description="git-interactive-rebase-gui-tool: A premium PySide6 GUI for interactive git rebasing.")
parser.add_argument("-C", "--location", type=str, default=os.getcwd())
parser.add_argument("--viewer-mode", action="store_true", help="Run in read-only viewer mode.")
parser.add_argument("commit_sha", type=str, nargs="?", help="Starting commit SHA (optional, defaults to root)")
args = parser.parse_args()
repo_path = os.path.abspath(os.path.expanduser(args.location))
now = datetime.now()
app_start_time = f"{now.strftime('%I.%M%p').lower()} {now.day}-{now.strftime('%b-%Y')}"
head_sha = get_full_head_sha(repo_path)
print(f"App started at {app_start_time} | HEAD commit: {head_sha}")
app = QApplication(sys.argv)
# Set global application icon
try:
assets_dir = get_assets_path()
icon_path = os.path.join(assets_dir, "app_icon.png")
if os.path.exists(icon_path):
app.setWindowIcon(QIcon(icon_path))
except Exception as e:
print(f"Warning: Could not load application icon: {e}")
# Check if we are inside a git repository
import subprocess
try:
subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], cwd=repo_path, check=True, capture_output=True, encoding='utf-8', errors='replace')
root_res = subprocess.run(["git", "rev-parse", "--show-toplevel"], cwd=repo_path, check=True, capture_output=True, encoding='utf-8', errors='replace')
if root_res.stdout.strip():
repo_path = root_res.stdout.strip()
except Exception:
QMessageBox.critical(None, "Not a Git Repository",
f"The directory '{repo_path}' is not a valid git repository.\n\n"
"Please run this tool inside a git repository.")
sys.exit(1)
commit_sha = args.commit_sha
base_branch = None # only set when auto-detected from branch base
if not commit_sha:
try:
print("No commit SHA provided. Detecting branch base...")
base_sha, base_branch = get_branch_base_info(repo_path)
if base_sha:
commit_sha = base_sha
print(f"Detected branch base: {commit_sha} (looks like it branched out from '{base_branch}', showing commits since that point)")
else:
print("Could not detect branch base. Falling back to recent history limit (HEAD~200)...")
commit_sha = get_recent_history_start(repo_path, count=200)
print(f"Defaulting to recent history: {commit_sha}")
except Exception as e:
QMessageBox.critical(None, "Error", f"Could not find start commit: {e}")
sys.exit(1)
else:
# Resolve the provided SHA/ref (like HEAD^^^^) to a concrete static SHA-1 hash.
# This is critical so the base doesn't drift when the rebase rewrites HEAD!
try:
res = subprocess.run(["git", "rev-parse", commit_sha], cwd=repo_path, check=True, capture_output=True, encoding='utf-8', errors='replace')
resolved_sha = res.stdout.strip()
print(f"Commit SHA provided: {commit_sha} -> resolved to {resolved_sha}")
commit_sha = resolved_sha
except Exception:
QMessageBox.critical(None, "Error", f"Invalid commit reference: {commit_sha}")
sys.exit(1)
# Apply global stylesheet before any dialog, so the startup unstaged-changes
# dialog matches the themed look of the rest of the app.
theme_name = QSettings("git-interactive-rebase-gui-tool", "settings").value("theme", "light", type=str)
QApplication.instance().setStyleSheet(get_theme_stylesheet(theme_name))
# Check for unstaged changes (ignoring submodules as per design)
created_stash_sha = None
ack_messages = [] # (kind, title, text) shown after the main window appears
deferred_selective_commit = False
unstaged_files = get_unstaged_files(repo_path, ignore_submodules=True)
if unstaged_files and not args.viewer_mode:
dialog = UnstagedChangesDialog(len(unstaged_files), repo_path=repo_path, unstaged_files=unstaged_files)
result = dialog.exec()
if result == UnstagedChangesDialog.SelectiveCommitResult:
# Defer until the main window exists so the dialog gets the app's
# font/theme; runs through the shared handler.
deferred_selective_commit = True
elif result == UnstagedChangesDialog.Accepted:
created_stash_sha, stash_err = stash_changes(repo_path)
if created_stash_sha is not None and created_stash_sha is not STASH_NOTHING_STASHED:
print(f"Changes stashed successfully (SHA: {created_stash_sha}).")
ack_messages.append(("info", "Stash Successful", f"Changes stashed successfully (SHA: {created_stash_sha[:8]})."))
elif created_stash_sha is STASH_NOTHING_STASHED:
ack_messages.append(("info", "No Changes Stashed",
"There was nothing to stash (e.g. changes are in untracked files). "
"Please handle them manually."))
else:
detail = f"\n\n{stash_err}" if stash_err else ""
QMessageBox.critical(None, "Error", f"Failed to stash changes. Please stash or commit manually.{detail}")
sys.exit(1)
elif result == UnstagedChangesDialog.CommitEachResult:
# We already have the files list
progress = ProgressDialog("Committing Changes", f"Committing {len(unstaged_files)} files individually...", None)
progress.show()
QApplication.processEvents()
success_count = 0
committed_shas = []
failed_files = []
for i, f in enumerate(unstaged_files):
progress.label.setText(f"Committing ({i+1}/{len(unstaged_files)}): {f}")
QApplication.processEvents()
ok, err = commit_file(repo_path, f, f"changes in {f}")
if ok:
committed_shas.append(get_head_sha(repo_path)[:8])
success_count += 1
else:
print(f"Failed to commit {f}")
failed_files.append((f, err))
progress.close()
if committed_shas:
ids = "\n".join(committed_shas)
ack_messages.append(("info", "Commit Successful",
f"Done. Successfully committed {success_count} file(s) individually.\n\nCommit IDs:\n{ids}"))
if failed_files:
fail_lines = "\n".join(f" {name}: {err}".rstrip() for name, err in failed_files)
ack_messages.append(("critical", "Some Commits Failed",
f"Failed to commit {len(failed_files)} of {len(unstaged_files)} file(s):\n\n{fail_lines}"))
print(f"Successfully committed {success_count} files.")
elif result == UnstagedChangesDialog.BulkCommitResult:
msg = f"bulk commit (Number of modified files: {len(unstaged_files)})"
ok, detail = bulk_commit_all(repo_path, msg)
if ok:
print("Bulk commit successful.")
ack_messages.append(("info", "Bulk Commit Successful",
f"Done. Bulk commit successful.\n\nCommit ID:\n{get_head_sha(repo_path)[:8]}"))
else:
print("Bulk commit failed.")
ack_messages.append(("critical", "Error", f"Bulk commit failed.\n\n{detail}"))
elif result == UnstagedChangesDialog.AmendResult:
old_head = get_head_sha(repo_path)
ok, detail = amend_with_head(repo_path)
if ok:
new_head = get_head_sha(repo_path)
print("Amend successful.")
ack_messages.append(("info", "Amend Successful",
f"Done. Changes amended into HEAD commit.\n\nOLD COMMIT: {old_head[:8]}\nNEW COMMIT: {new_head[:8]}"))
else:
print("Amend failed.")
ack_messages.append(("critical", "Error", f"Amend failed.\n\n{detail}"))
elif result == UnstagedChangesDialog.DiscardResult:
ok, detail = discard_changes(repo_path)
if ok:
print("Unstaged changes discarded.")
ack_messages.append(("info", "Discard Successful", "Done. Unstaged changes discarded (git checkout .)."))
else:
print("Discard failed.")
ack_messages.append(("critical", "Error", f"Discard failed.\n\n{detail}"))
elif result == UnstagedChangesDialog.ViewerModeResult:
args.viewer_mode = True
else:
print("Exiting as requested by the user.")
sys.exit(0)
window = GitInteractiveRebaseApp(repo_path, commit_sha, app_start_time, base_branch=base_branch, viewer_mode=args.viewer_mode)
window.show()
if created_stash_sha:
window.app_managed_stash_sha = created_stash_sha
window._update_stash_btn_visibility()
window._flash_pop_stash_btn()
# Deferred 'Commit Selectively' chosen at startup - run once the window is up.
if deferred_selective_commit:
QTimer.singleShot(0, window._commit_selectively_from_dialog)
# Show any acknowledgment/error boxes only after the main window is up.
if ack_messages:
def _show_deferred_acks():
for kind, title, text in ack_messages:
if kind == "critical":
QMessageBox.critical(None, title, text)
else:
QMessageBox.information(None, title, text)
QTimer.singleShot(0, _show_deferred_acks)
exit_code = app.exec()
stash_sha = getattr(window, "app_managed_stash_sha", None)
if stash_sha:
status, _ = get_stash_status(repo_path, stash_sha)
short_sha = stash_sha[:8]
def show_missing_box(not_at_head):
if not_at_head:
text = (f"The stash created by app ({short_sha}) is found in stash list, but not at HEAD position. "
f"Please investigate and stash pop manually.\n\n"
f"Please note down the sha: {short_sha}")
else:
text = (f"The stash created during app start is missing. "
f"{short_sha} not found in stash list. "
f"Please investigate and stash pop manually.\n\n"
f"Please note down the sha: {short_sha}")
StashNoticeDialog(text, stash_sha).exec()
if status == "ERROR":
QMessageBox.critical(
None, "Error",
f"Could not verify the status of the app-created stash ({short_sha}). "
f"Please investigate and stash pop manually.\n\n"
f"Please note down the sha: {short_sha}"
)
elif status == "NOT_FOUND":
show_missing_box(not_at_head=False)
elif status == "NOT_HEAD":
show_missing_box(not_at_head=True)
else:
# Final reminder before exiting the process completely
msg_box = QMessageBox(None)
msg_box.setWindowTitle("Stash Reminder")
msg_box.setText("A stash was created during this session. Do you want to stash pop it ??")
yes_button = msg_box.addButton("Yes, stash pop now.", QMessageBox.YesRole)
no_button = msg_box.addButton("No, i will do manually.", QMessageBox.NoRole)
msg_box.exec()
if msg_box.clickedButton() == yes_button:
can_apply, conflict_detail = stash_pop_can_apply(repo_path, stash_sha)
if not can_apply:
QMessageBox.warning(
None,
"Cannot Pop Stash",
f"Popping this stash would create a merge conflict (HEAD has moved since it was created), "
f"so it was not applied.\n\n"
f"{conflict_detail}\n\nThe stash (SHA: {short_sha}) was left untouched."
)
else:
success, msg = stash_pop(repo_path, stash_sha)
if success:
print(f"Stash {stash_sha[:8]}({msg}) popped successfully.")
QMessageBox.information(None, "Success", f"Stash {stash_sha[:8]}({msg}) popped successfully.")
else:
detail = f"\n\n{msg}" if msg else ""
QMessageBox.critical(None, "Error", "Failed to pop stash. You may need to do it manually." + detail)
sys.exit(exit_code)
if __name__ == "__main__":
main()