-
Notifications
You must be signed in to change notification settings - Fork 3
/
buffer.py
2591 lines (2048 loc) · 97.1 KB
/
buffer.py
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2018 Andy Stewart
#
# Author: Andy Stewart <[email protected]>
# Maintainer: Andy Stewart <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
import os
import shutil
from copy import copy
from io import StringIO
import pygit2
from app.git.utils import get_git_https_url
from charset_normalizer import from_bytes, from_path
from core.utils import PostGui, eval_in_emacs, get_emacs_func_result, get_emacs_var, get_emacs_vars, interactive, message_to_emacs
from core.webengine import BrowserBuffer
from pygit2 import GIT_BRANCH_REMOTE, GIT_CHECKOUT_FORCE, GIT_STATUS_CONFLICTED, GIT_STATUS_CURRENT, GIT_STATUS_IGNORED, GIT_STATUS_INDEX_DELETED, GIT_STATUS_INDEX_MODIFIED, GIT_STATUS_INDEX_NEW, GIT_STATUS_INDEX_RENAMED, GIT_STATUS_INDEX_TYPECHANGE, GIT_STATUS_WT_DELETED, GIT_STATUS_WT_MODIFIED, GIT_STATUS_WT_NEW, GIT_STATUS_WT_RENAMED, GIT_STATUS_WT_TYPECHANGE, GIT_STATUS_WT_UNREADABLE, IndexEntry, Oid, Repository
from pygit2._pygit2 import GitError
from PyQt6 import QtCore
from PyQt6.QtCore import QMimeDatabase, QThread, QTimer
from PyQt6.QtGui import QColor
from unidiff import LINE_TYPE_ADDED, LINE_TYPE_CONTEXT, LINE_TYPE_REMOVED, Hunk, PatchSet
GIT_STATUS_DICT = {
GIT_STATUS_CURRENT: "Current",
GIT_STATUS_INDEX_NEW: "New",
GIT_STATUS_INDEX_MODIFIED: "Modified",
GIT_STATUS_INDEX_DELETED: "Deleted",
GIT_STATUS_INDEX_RENAMED: "Renamed",
GIT_STATUS_INDEX_TYPECHANGE: "Typechange",
GIT_STATUS_WT_NEW: "New",
GIT_STATUS_WT_MODIFIED: "Modified",
GIT_STATUS_WT_DELETED: "Deleted",
GIT_STATUS_WT_TYPECHANGE: "Typechange",
GIT_STATUS_WT_RENAMED: "Renamed",
GIT_STATUS_WT_UNREADABLE: "Unreadable",
GIT_STATUS_IGNORED: "Ignored",
GIT_STATUS_CONFLICTED: "Conflicted"
}
GIT_STATUS_INDEX_CHANGES = [
GIT_STATUS_INDEX_NEW,
GIT_STATUS_INDEX_MODIFIED,
GIT_STATUS_INDEX_DELETED,
GIT_STATUS_INDEX_RENAMED,
GIT_STATUS_INDEX_TYPECHANGE,
]
NO_PREVIEW = "Previewing binary data is not supported now. \n"
def pretty_date(time):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
from datetime import datetime
now = datetime.now()
diff = 0
if isinstance(time, int):
diff = now - datetime.fromtimestamp(time)
elif isinstance(time, datetime):
diff = now - time
else:
return ""
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff // 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff // 3600) + " hours ago"
if day_diff == 1:
return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 31:
return str(day_diff // 7) + " weeks ago"
if day_diff < 365:
return str(day_diff // 30) + " months ago"
return str(day_diff // 365) + " years ago"
def bytes_decode(str_encode_bytes):
return str(from_bytes(str_encode_bytes).best())
def is_binary(filename_or_bytes):
"""
Return true if the given file or content appears to be binary.
File is considered to be binary if it contains a NULL byte.
FIXME: This approach incorrectly reports UTF-16 as binary.
"""
if isinstance(filename_or_bytes, str):
with open(filename_or_bytes, 'rb') as f:
for block in f:
if b'\0' in block:
return True
return False
else:
for b in filename_or_bytes:
if b == 0:
return True
return False
def get_command_result(command_string, input_text=None):
import subprocess
process = subprocess.Popen(command_string, shell=True, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if input_text:
out, err = process.communicate(input=input_text)
ret = process.returncode
return out if ret == 0 else err
else:
ret = process.wait()
return "".join((process.stdout if ret == 0 else process.stderr).readlines())
def patch_stream(instream, hunks):
hunks = iter(hunks)
srclineno = 1
lineends = {"\n":0, "\r\n":0, "\r":0}
def get_line():
line = instream.readline()
if line.endswith("\r\n"):
lineends["\r\n"] += 1
elif line.endswith("\n"):
lineends["\n"] += 1
elif line.endswith("\r"):
lineends["\r"] += 1
return line
for hno, h in enumerate(hunks):
while srclineno < h.source_start:
yield get_line()
srclineno += 1
for hline in h:
# TODO: check \ No newline at the end of file
hline = str(hline)
if hline.startswith("-") or hline.startswith("\\"):
get_line()
srclineno += 1
continue
else:
if not hline.startswith("+"):
get_line()
srclineno += 1
line2write = hline[1:]
# Detect if line ends are consistent in source file
if sum([bool(lineends[x]) for x in lineends]) == 1:
newline = [x for x in lineends if lineends[x] != 0][0]
yield line2write.rstrip("\r\n") + newline
else: # Newlines are mixed
yield line2write
for line in instream:
yield line
def parse_patch(patches, highlight):
patch_set = []
for patch in patches:
patch_set.append({
"path": patch.path,
"patch_info": "".join(patch.patch_info),
"diff_hunks": [highlight(str(hunk)) for hunk in patch]
})
return patch_set
def status_is_include(status, file_info):
"Check if status1 has file_info"
for stat in status:
if stat["file"] == file_info["file"]:
return True
return False
class AppBuffer(BrowserBuffer):
def __init__(self, buffer_id, url, arguments):
BrowserBuffer.__init__(self, buffer_id, url, arguments, False)
self.stage_status = []
self.unstage_status = []
self.untrack_status = []
self.branch_status = []
self.raw_patch_set = []
self.nav_current_item = "Dashboard"
self.mime_db = QMimeDatabase()
self.search_log_cache_path = ""
self.search_submodule_cache_path = ""
self.temp_files = []
self.thread_reference_list = []
self.log_compare_branch = ""
self.url = os.path.expanduser(self.url)
self.repo = Repository(self.url)
self.repo_root = self.url
eval_in_emacs('eaf--change-default-directory', [self.buffer_id, self.url])
self.repo_path = os.path.sep.join(list(filter(lambda x: x != '', self.repo_root.split(os.path.sep)))[-2:])
self.change_title("Git [{}]".format(self.repo_path))
self.last_commit = None
self.last_commit_id = ""
self.last_commit_message = ""
if self.repo.head_is_unborn:
message_to_emacs("There is no commit yet")
else:
self.last_commit_id = str(self.repo.head.target)
self.last_commit = self.repo.revparse_single(str(self.repo.head.target))
try:
self.last_commit_message = bytes_decode(self.last_commit.raw_message).splitlines()[0]
except:
pass
self.highlight_style = "monokai"
self.load_index_html(__file__)
def init_app(self):
self.init_vars()
self.update_git_info()
def update_git_info(self):
self.fetch_unpush_info()
self.fetch_status_info()
self.fetch_log_info()
self.fetch_stash_info()
self.fetch_submodule_info()
self.fetch_branch_info()
def init_vars(self):
(layout, statusState, untrackState, unstageState, stageState, stashState, unpushState) = get_emacs_vars([
"eaf-git-layout",
"eaf-git-status-initial-state",
"eaf-git-untracked-initial-state",
"eaf-git-unstaged-initial-state",
"eaf-git-staged-initial-state",
"eaf-git-stash-initial-state",
"eaf-git-unpushed-initial-state"
])
if self.theme_mode == "dark":
if self.theme_background_color == "#000000":
select_color = "#333333"
else:
select_color = QColor(self.theme_background_color).darker(120).name()
self.highlight_style = get_emacs_var("eaf-git-dark-highlight-style")
else:
if self.theme_background_color == "#FFFFFF":
select_color = "#EEEEEE"
else:
select_color = QColor(self.theme_background_color).darker(110).name()
self.highlight_style = get_emacs_var("eaf-git-light-highlight-style")
(text_color, nav_item_color, info_color, date_color, id_color, match_color, author_color) = get_emacs_func_result(
"get-emacs-face-foregrounds",
["default",
"font-lock-function-name-face",
"font-lock-keyword-face",
"font-lock-builtin-face",
"font-lock-comment-face",
"font-lock-string-face",
"font-lock-negation-char-face"])
self.buffer_widget.eval_js_function("init",
layout,
{
"status": statusState,
"untrack": untrackState,
"unstage": unstageState,
"stage": stageState,
"stash": stashState,
"unpush": unpushState
},
self.theme_background_color, self.theme_foreground_color, select_color, QColor(self.theme_background_color).darker(110).name(),
text_color, nav_item_color, info_color,
date_color, id_color, author_color, match_color,
self.repo_path, self.last_commit_id,
{"lastCommit": self.last_commit_message},
self.get_keybinding_info())
def some_view_show(self):
# Automatically refresh the Git status when the interface is displayed.
self.update_git_info()
@interactive
def update_theme(self):
super().update_theme()
self.init_vars()
def fetch_status_info(self, adjust_selection=False):
thread = FetchStatusThread(self.repo, self.repo_root, self.mime_db)
# If adjust_selection is True, update both status_info and the selection of status.
if adjust_selection:
thread.fetch_result.connect(self.update_status_info_and_selection)
else:
thread.fetch_result.connect(self.update_status_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_status_info(self, stage_status, unstage_status, untrack_status, select=None):
if select is None:
self.buffer_widget.eval_js_function("updateStatusInfo", stage_status, unstage_status, untrack_status)
else:
select_item_index = -1
select_item_type = ""
if len(untrack_status) > 0:
select_item_type = "untrack"
elif len(unstage_status) > 0:
select_item_type = "unstage"
elif len(stage_status) > 0:
select_item_type = "stage"
self.buffer_widget.eval_js_function("updateSelectInfo", stage_status, unstage_status, untrack_status, select_item_type, select_item_index)
QTimer().singleShot(300, self.init_diff)
@PostGui()
def update_status_info_and_selection(self, stage_status, unstage_status, untrack_status):
self.update_status_info(stage_status, unstage_status, untrack_status, True)
def init_diff(self):
if len(self.untrack_status) > 0:
self.update_diff("untrack", "")
elif len(self.unstage_status) > 0:
self.update_diff("unstage", "")
elif len(self.stage_status) > 0:
self.update_diff("stage", "")
def get_keybinding_info(self):
js_keybindig = get_emacs_var("eaf-git-js-keybinding")
js_keybindig_dict = {}
for keybindig_list in js_keybindig:
module_name = keybindig_list[0]
module_keybinding_dict = {}
for key_value in keybindig_list[1:][0]:
module_keybinding_dict[key_value[0]] = {
"command": key_value[1][0],
"description": key_value[1][1]
}
js_keybindig_dict[module_name] = module_keybinding_dict
return js_keybindig_dict
def fetch_unpush_info(self):
thread = FetchUnpushThread(self.repo, self.repo_root)
thread.fetch_result.connect(self.update_unpush_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_unpush_info(self, unpush_list):
self.buffer_widget.eval_js_function("updateUnpushInfo", unpush_list)
@QtCore.pyqtSlot()
def fetch_log_info(self):
if self.repo.head_is_unborn: return # noqa: E701
thread = FetchLogThread(self.repo, self.repo.head, True)
thread.fetch_result.connect(self.update_log_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_log_info(self, branch_name, log, search_cache_path, append):
if self.search_log_cache_path != "" and os.path.exists(self.search_log_cache_path):
if self.search_log_cache_path not in self.temp_files:
self.temp_files.append(self.search_log_cache_path)
self.search_log_cache_path = search_cache_path
self.buffer_widget.eval_js_function("updateLogInfo", branch_name, log, append)
def fetch_compare_log_info(self, branch_name):
branch = self.repo.branches.get(branch_name)
thread = FetchLogThread(self.repo, branch)
thread.fetch_result.connect(self.update_compare_log_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_compare_log_info(self, branch_name, log, search_cache_path, append):
self.buffer_widget.eval_js_function("updateCompareLogInfo", branch_name, log, append)
@QtCore.pyqtSlot()
def grep_log_info(self):
self.send_input_message("Grep log with: ", "grep_log", "string")
def handle_grep_log(self, keyword):
if self.repo.head_is_unborn: return # noqa: E701
message_to_emacs(f"Grep log with keyword: {keyword}...")
thread = GrepLogThread(self.repo, self.repo.head, keyword, True)
thread.fetch_result.connect(self.update_grep_log_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_grep_log_info(self, keyword, branch_name, log, search_cache_path):
if self.search_log_cache_path != "" and os.path.exists(self.search_log_cache_path):
if self.search_log_cache_path not in self.temp_files:
self.temp_files.append(self.search_log_cache_path)
self.search_log_cache_path = search_cache_path
self.buffer_widget.eval_js_function("updateLogInfo", branch_name, log)
message_to_emacs(f"Find log match keyword: {keyword}")
def fetch_stash_info(self):
thread = FetchStashThread(self.repo)
thread.fetch_result.connect(self.update_stash_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_stash_info(self, stash):
self.buffer_widget.eval_js_function("updateStashInfo", stash)
def fetch_submodule_info(self):
thread = FetchSubmoduleThread(self.repo, self.repo_root)
thread.fetch_result.connect(self.update_submodule_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_submodule_info(self, submodule, search_cache_path):
if self.search_submodule_cache_path != "" and os.path.exists(self.search_submodule_cache_path):
if self.search_submodule_cache_path not in self.temp_files:
self.temp_files.append(self.search_submodule_cache_path)
self.search_submodule_cache_path = search_cache_path
self.buffer_widget.eval_js_function("updateSubmoduleInfo", submodule, True)
def fetch_branch_info(self):
thread = FetchBranchThread(self.repo)
thread.fetch_result.connect(self.update_branch_info)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def update_branch_info(self, branch_list, remote_branch):
self.update_branch_list(branch_list, remote_branch)
@interactive
def search(self):
if self.nav_current_item == "Log":
self.search_log_count = 0
self.send_input_message("Search log: ", "search_log", "search")
elif self.nav_current_item == "Submodule":
self.search_submodule_count = 0
self.send_input_message("Search submodule: ", "search_submodule", "search")
def search_match_lines(self, search_string, cache_file_path):
import subprocess
command = "rg '{}' {} --color='never' --line-number --smart-case -o --replace=''".format(search_string, cache_file_path)
result = subprocess.run(command, shell=True, text=True, stdout=subprocess.PIPE)
return list(map(lambda x: int(x[:-1]) - 1, result.stdout.split()))
def handle_search_log(self, search_string):
in_minibuffer = get_emacs_func_result("minibufferp", [])
if in_minibuffer:
self.search_log_count += 1
count = self.search_log_count
QTimer().singleShot(300, lambda : self.try_search_log(count, search_string))
else:
self.buffer_widget.eval_js_function("searchLogsFinish")
def handle_search_submodule(self, search_string):
in_minibuffer = get_emacs_func_result("minibufferp", [])
if in_minibuffer:
self.search_submodule_count += 1
count = self.search_submodule_count
QTimer().singleShot(300, lambda : self.try_search_submodule(count, search_string))
else:
self.buffer_widget.eval_js_function("searchSubmodulesFinish")
def try_search_log(self, count, search_string):
if count == self.search_log_count and search_string.strip() != "":
if self.search_log_cache_path and os.path.exists(self.search_log_cache_path):
self.buffer_widget.eval_js_function("searchLogsStart",
search_string,
self.search_match_lines(search_string, self.search_log_cache_path))
def try_search_submodule(self, count, search_string):
if count == self.search_submodule_count and search_string.strip() != "":
if self.search_submodule_cache_path and os.path.exists(self.search_submodule_cache_path):
self.buffer_widget.eval_js_function(
"searchSubmodulesStart",
search_string,
self.search_match_lines(search_string, self.search_submodule_cache_path))
@PostGui()
def handle_search_forward(self, callback_tag):
if callback_tag == "search_log":
self.buffer_widget.eval_js_function("searchLogsJumpNext")
elif callback_tag == "search_submodule":
self.buffer_widget.eval_js_function("searchSubmodulesJumpNext")
@PostGui()
def handle_search_backward(self, callback_tag):
if callback_tag == "search_log":
self.buffer_widget.eval_js_function("searchLogsJumpPrev")
elif callback_tag == "search_submodule":
self.buffer_widget.eval_js_function("searchSubmodulesJumpPrev")
@PostGui()
def handle_search_finish(self, callback_tag):
if callback_tag == "search_log":
self.buffer_widget.eval_js_function("searchLogsFinish")
elif callback_tag == "search_submodule":
self.buffer_widget.eval_js_function("searchSubmodulesFinish")
@QtCore.pyqtSlot()
def status_copy_change_files_to_mirror_repo(self):
status = list(filter(lambda info: info[1] != GIT_STATUS_IGNORED, list(self.repo.status().items())))
if len(status) > 0:
self.send_input_message("Copy changes file to: ", "copy_changes_file_to_mirror", "file", self.repo_root)
else:
message_to_emacs("No file need submitted, nothing to copy.")
@QtCore.pyqtSlot()
def status_fetch_pr(self):
remote_default = next(self.repo.config.get_multivar("remote.pushdefault"), "origin")
origin_url = get_git_https_url(self.repo.remotes[remote_default].url)
message_to_emacs("Fetch PR list...")
thread = FetchPrListThread(origin_url)
thread.fetch_result.connect(self.read_pr)
self.thread_reference_list.append(thread)
thread.start()
@QtCore.pyqtSlot(list)
def read_pr(self, pr_list):
if len(pr_list) > 0:
self.pr_ids = []
self.pr_names = []
for pr in pr_list:
self.pr_ids.append(pr[0])
self.pr_names.append(pr[1])
self.send_input_message("Fetch pull request, please input PR number: ", "fetch_pr", "list", completion_list=self.pr_names)
else:
message_to_emacs("No PR found in repo.")
def handle_fetch_pr(self, pr_name):
try:
pr_number = self.pr_ids[self.pr_names.index(pr_name)]
message_to_emacs("Fetch PR {} ...".format(pr_number))
get_command_result("cd {}; git fetch origin pull/{}/head:pr_{} && git checkout pr_{}".format(
self.repo_root,
pr_number,
pr_number,
pr_number))
self.update_git_info()
message_to_emacs("Fetch PR {} done.".format(pr_number))
except:
message_to_emacs("Input wrong PR: {}".format(pr_name))
@QtCore.pyqtSlot()
def remote_copy_url(self):
remote_default = next(self.repo.config.get_multivar("remote.pushdefault"), "origin")
origin_url = get_git_https_url(self.repo.remotes[remote_default].url)
eval_in_emacs('kill-new', [origin_url])
message_to_emacs("Copy {}".format(origin_url))
@QtCore.pyqtSlot(str)
def send_message_to_emacs(self, message):
message_to_emacs(message)
@PostGui()
def handle_input_response(self, callback_tag, result_content):
from inspect import signature
handle_function_name = "handle_{}".format(callback_tag)
if hasattr(self, handle_function_name):
handle_function = getattr(self, handle_function_name)
function_argument_number = len(signature(getattr(self, handle_function_name)).parameters)
if function_argument_number == 1:
handle_function(result_content)
else:
handle_function()
@PostGui()
def cancel_input_response(self, callback_tag):
''' Cancel input message.'''
if callback_tag == "search_log":
self.buffer_widget.eval_js_function("searchLogsCancel")
elif callback_tag == "search_submodule":
self.buffer_widget.eval_js_function("searchSubmodulesCancel")
def handle_copy_changes_file_to_mirror(self, target_repo_dir):
current_repo_last_commit_id = self.last_commit_id
target_repo_last_commit_id = str(Repository(target_repo_dir).head.target)
if target_repo_last_commit_id == current_repo_last_commit_id:
status = list(filter(lambda info: info[1] != GIT_STATUS_IGNORED, list(self.repo.status().items())))
for (file, file_type) in status:
if file_type == GIT_STATUS_WT_DELETED:
os.remove(os.path.join(target_repo_dir, file))
else:
target_file = os.path.join(target_repo_dir, file)
if not os.path.exists(target_file):
os.makedirs(os.path.dirname(target_file), exist_ok=True)
shutil.copy(os.path.join(self.repo_root, file), target_file)
message_to_emacs("Update {} files to {}".format(len(status), os.path.join(target_repo_dir)))
else:
message_to_emacs("{} last commit is not same as current repo, stop copy files.".format(target_repo_dir))
@QtCore.pyqtSlot(str)
def show_commit_diff(self, commit_id):
commit = self.repo.revparse_single(commit_id)
parent_commits = commit.parents
if len(parent_commits) > 0:
eval_in_emacs("eaf-git-show-commit-diff", [self.repo.diff(parent_commits[0], commit).patch])
else:
eval_in_emacs("eaf-git-show-commit-diff", [commit.tree.diff_to_tree(swap=True).patch])
@QtCore.pyqtSlot(str)
def log_revert_commit(self, commit_id):
self.revert_commit = self.repo.revparse_single(commit_id)
self.send_input_message("Revert commit '{}' {}".format(commit_id, bytes_decode(self.revert_commit.raw_message)), "log_revert_commit", "yes-or-no")
def handle_log_revert_commit(self):
head = self.repo.head.peel()
try:
revert_index = self.repo.revert_commit(self.revert_commit, head)
except:
# When revert commit is merge commit, we need set mainline with 1 to make sure revert successfully.
revert_index = self.repo.revert_commit(self.revert_commit, head, 1)
parent, ref = self.repo.resolve_refish(refish=self.repo.head.name)
commit_message = bytes_decode(self.revert_commit.raw_message)
self.repo.create_commit(
ref.name,
self.repo.default_signature,
self.repo.default_signature,
"Revert {}".format(commit_message),
revert_index.write_tree(),
[parent.oid])
self.fetch_unpush_info()
self.fetch_status_info()
self.fetch_log_info()
message_to_emacs("Revert commit: {} {} ".format(self.revert_commit.id, commit_message))
@QtCore.pyqtSlot(str)
def log_revert_to(self, commit_id):
self.revert_to_commit = self.repo.revparse_single(commit_id)
self.send_input_message("Revert to commit '{}' {}".format(
commit_id,
bytes_decode(self.revert_to_commit.raw_message).splitlines()[0]), "log_revert_to_commit", "yes-or-no")
def handle_log_revert_to_commit(self):
short_commit_id = str(self.revert_to_commit.id)[:7]
revert_to_message = bytes_decode(self.revert_to_commit.raw_message).splitlines()[0]
result = get_command_result("cd {}; git revert --no-edit -n {}..HEAD".format(self.repo_root, short_commit_id))
if result == "":
revert_message = "Revert to commit: {} {}".format(short_commit_id, revert_to_message)
get_command_result("cd {}; git commit -m '{}'".format(self.repo_root, revert_message))
message_to_emacs(revert_message)
else:
message_to_emacs("Failed to revert to commit: {} reason: {}".format(self.revert_to_commit.id, result))
self.fetch_unpush_info()
self.fetch_status_info()
self.fetch_log_info()
@QtCore.pyqtSlot(str, str)
def log_reset_last(self, commit_id, commit_message):
self.log_commit_reset_last_id = commit_id
self.send_input_message("Reset last commit '{}' with mode: ".format(commit_message), "log_reset_last", "list", completion_list=["mixed", "soft", "hard"])
def handle_log_reset_last(self, mode):
reset_type = pygit2.GIT_RESET_MIXED
if mode == "soft":
reset_type = pygit2.GIT_RESET_SOFT
elif mode == "hard":
reset_type = pygit2.GIT_RESET_HARD
commit = self.repo.revparse_single(self.log_commit_reset_last_id)
parent_commits = commit.parents
if len(parent_commits) > 0:
self.repo.reset(parent_commits[0].id, reset_type)
self.fetch_log_info()
self.fetch_status_info()
self.fetch_unpush_info()
self.fetch_stash_info()
last_commit = self.repo.revparse_single(str(self.repo.head.target))
message_to_emacs("Current HEAD is: {}".format(bytes_decode(last_commit.raw_message)).splitlines()[0])
@QtCore.pyqtSlot(str, str)
def log_reset_to(self, commit_id, commit_message):
self.log_commit_reset_to_id = commit_id
self.log_commit_reset_to_message = commit_message
self.send_input_message("Reset to commit '{}' with mode: ".format(commit_message), "log_reset_last", "list", completion_list=["mixed", "soft", "hard"])
def handle_log_reset_to(self, mode):
reset_type = pygit2.GIT_RESET_MIXED
if mode == "soft":
reset_type = pygit2.GIT_RESET_SOFT
elif mode == "hard":
reset_type = pygit2.GIT_RESET_HARD
self.repo.reset(self.log_commit_reset_to_id, reset_type)
self.fetch_log_info()
self.fetch_status_info()
self.fetch_unpush_info()
self.fetch_stash_info()
message_to_emacs("Current HEAD is: {}".format(self.log_commit_reset_to_message))
@QtCore.pyqtSlot()
def log_merge_branch(self):
self.send_input_message("Select merge method: ", "log_select_merge_method", "list", completion_list=["merge", "rebase", "squash"])
def handle_log_select_merge_method(self, method):
self.merge_method = method
branches = self.repo.listall_branches()
self.send_input_message("Merge in {} mode from Branch: ".format(self.merge_method), "log_merge_branch", "list", completion_list=branches)
def handle_log_merge_branch(self, branch_name):
if branch_name == self.repo.head.shorthand:
message_to_emacs("Can't merge branch self.")
else:
# normal merge a branch
merge_branch = self.repo.lookup_branch(branch_name)
current_branch = self.repo.lookup_branch(self.repo.head.shorthand)
result = "Merge commits in {} mode from branch {} to {}".format(
self.merge_method,
merge_branch.name,
current_branch.name
)
try:
if self.merge_method == "merge":
self.repo.merge(merge_branch.target)
tree = self.repo.index.write_tree()
self.repo.create_commit(
current_branch.name,
self.repo.default_signature,
self.repo.default_signature,
"Merge branch {}".format(branch_name),
tree,
[current_branch.target, merge_branch.target])
elif self.merge_method == "rebase":
# rebase and merge a branch.
self.repo.checkout(current_branch)
result = get_command_result("cd {}; git rebase {}".format(self.repo_root, merge_branch.name))
elif self.merge_method == "squash":
# merge a branch and squash target all commits into one commit.
merge_base = self.repo.merge_base(current_branch.target, merge_branch.target)
current_branch_tree = self.repo.get(current_branch.target).tree
merge_branch_tree = self.repo.get(merge_branch.target).tree
merge_base_tree = self.repo.get(merge_base).tree
self.repo.checkout(current_branch)
index = self.repo.merge_trees(merge_base_tree, current_branch_tree, merge_branch_tree)
tree = index.write_tree(self.repo)
commit = self.repo.create_commit(
current_branch.name,
self.repo.default_signature,
self.repo.default_signature,
"Squash merge branch {}".format(branch_name),
tree,
[current_branch.target])
self.repo.reset(commit, pygit2.GIT_RESET_HARD)
else:
message_to_emacs("Unknown merge method.")
return
except Exception as err:
result = "Failed to merge commits in {} mode from branch {} to {}, Error: {}".format(
self.merge_method,
merge_branch.name,
current_branch.name,
err
)
self.fetch_log_info()
message_to_emacs(result)
@QtCore.pyqtSlot(int)
def show_stash_diff(self, stash_index):
stash_item = "stash@" + "{" + str(stash_index) + "}"
eval_in_emacs("eaf-git-show-commit-diff", [self.repo.diff("{}^".format(stash_item), stash_item).patch])
@QtCore.pyqtSlot(int, str)
def stash_apply(self, index, message):
self.stash_apply_index = index
self.stash_apply_message = message
self.send_input_message("Stash apply '{}'".format(message), "stash_apply", "yes-or-no")
@QtCore.pyqtSlot(int, str)
def stash_drop(self, index, message):
self.stash_drop_index = index
self.stash_drop_message = message
self.send_input_message("Stash drop '{}'".format(message), "stash_drop", "yes-or-no")
@QtCore.pyqtSlot(int, str)
def stash_pop(self, index, message):
self.stash_pop_index = index
self.stash_pop_message = message
self.send_input_message("Stash pop '{}'".format(message), "stash_pop", "yes-or-no")
def handle_stash_apply(self):
self.repo.stash_apply(index=self.stash_apply_index)
message_to_emacs("Stash apply '{}'".format(self.stash_apply_message))
self.fetch_stash_info()
self.fetch_status_info()
def handle_stash_drop(self):
self.repo.stash_drop(index=self.stash_drop_index)
message_to_emacs("Stash drop '{}'".format(self.stash_drop_message))
self.fetch_stash_info()
self.fetch_status_info()
def handle_stash_pop(self):
self.repo.stash_pop(index=self.stash_pop_index)
message_to_emacs("Stash pop '{}'".format(self.stash_pop_message))
self.fetch_stash_info()
self.fetch_status_info()
def highlight_diff(self, content):
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer
return highlight(content, guess_lexer(content), HtmlFormatter(full=True, style=self.highlight_style))
def highlight_diff_strict(self, content):
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import DiffLexer
return highlight(content, DiffLexer(), HtmlFormatter(full=True, style=self.highlight_style))
@QtCore.pyqtSlot(str, str)
def update_diff(self, type, file):
import time
tick = time.time()
self.diff_type = type
self.diff_file = file
self.diff_tick = tick
thread = HighlightDiffThread(self, type, file, tick)
thread.fetch_result.connect(self.render_diff)
self.thread_reference_list.append(thread)
thread.start()
@PostGui()
def render_diff(self, type, file, tick, diff_string, patch_set):
if self.diff_type == type and self.diff_file == file and self.diff_tick == tick:
self.buffer_widget.eval_js_function("updateChangeDiff", type, {"diff": diff_string, "patch_set": patch_set})
@QtCore.pyqtSlot()
def status_commit_stage(self):
if len(self.stage_status) > 0:
self.send_input_message("Commit stage files with message: ", "commit_stage_files")
else:
message_to_emacs("No stage files found, please stage file first.")
@QtCore.pyqtSlot()
def status_commit_all(self):
self.send_input_message("Commit all files with message: ", "commit_all_files")
@QtCore.pyqtSlot()
def status_commit_and_push(self):
self.send_input_message("Commit all files and push with message: ", "commit_and_push")
@QtCore.pyqtSlot()
def status_commit_and_push_with_ollama(self):
import shutil
if shutil.which("ollama"):
self.send_input_message("Commit all files and push with message: ", "commit_and_push")
thread = ParseGitDiffThread(self.url)
thread.fetch_result.connect(self.handle_status_commit_and_push_with_ollama)
self.thread_reference_list.append(thread)
thread.start()
else:
message_to_emacs("You need to install ollama in order to use AI to generate git commits")
@PostGui()
def handle_status_commit_and_push_with_ollama(self, patch_name):
eval_in_emacs("eaf-git-insert-commit-name", [patch_name])
@QtCore.pyqtSlot()
def status_commit_and_push_with_hooks(self):
self.send_input_message("Commit all files and push with message: ", "commit_and_push")
eval_in_emacs("eaf-git-run-commit-and-push-hook", [])
@QtCore.pyqtSlot(str, int)
def status_view_file(self, type, file_index):
if type == "untrack":
if file_index == -1:
message_to_emacs("Please select file to view.")
else:
self.status_open_file(self.untrack_status[file_index]["file"])
elif type == "unstage":
if file_index == -1:
message_to_emacs("Please select file to view.")
else:
self.status_open_file(self.unstage_status[file_index]["file"])
elif type == "stage":
if file_index == -1:
message_to_emacs("Please select file to view.")
else:
self.status_open_file(self.stage_status[file_index]["file"])
def status_open_file(self, filename):
filepath = os.path.join(self.repo_root, filename)
if os.path.isdir(filepath):
eval_in_emacs('eaf-open-in-file-manager', [filepath])
else:
eval_in_emacs("find-file", [filepath])
@QtCore.pyqtSlot(str, int)
def status_stage_file(self, type, file_index):
if type == "untrack":
if file_index == -1:
self.stage_untrack_files()
else:
self.stage_untrack_file(self.untrack_status[file_index])
elif type == "unstage":
if file_index == -1:
self.stage_unstage_files()
else:
self.stage_unstage_file(self.unstage_status[file_index])
elif type == "stage":
if file_index == -1:
self.unstage_staged_files()
else:
self.unstage_staged_file(self.stage_status[file_index])