-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub_insights_tab.py
1704 lines (1436 loc) · 71.7 KB
/
github_insights_tab.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
import sys
import logging
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QComboBox, QPushButton, QLabel,
QTreeView, QTextEdit, QLineEdit, QSplitter, QMessageBox, QTabWidget,
QTableWidget, QTableWidgetItem, QHeaderView, QScrollArea, QFrame, QDialog)
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont, QGuiApplication, QPainter, QColor, QPen
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QThreadPool, QRunnable, pyqtSlot
import requests
import base64
import markdown
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import QApplication, QListWidget, QPlainTextEdit
import re
import markdown
from PyQt5.QtWidgets import QSplitter, QPushButton, QMessageBox
from PyQt5.QtCore import Qt
from PyQt5.QtWebEngineWidgets import QWebEngineView
from PyQt5.QtCore import QUrl
import sip
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
import keyring
from helper_github_insights_tab.github_auth_dialog import GitHubAuthDialog
from helper_github_insights_tab.loading_overlay import LoadingOverlay
from helper_github_insights_tab.code_editor import LineNumberArea, CodeEditor, CodeHighlighter
from helper_github_insights_tab.blame_popup import BlamePopup
from cachetools import TTLCache
import asyncio
import aiohttp
from PyQt5.QtCore import QObject, pyqtSignal
from PyQt5.QtCore import QMetaType
from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLineEdit, QListWidget, QListWidgetItem
from PyQt5.QtCore import Qt, QTimer, pyqtSignal
import requests
class SearchableUserList(QWidget):
search_completed = pyqtSignal(list)
def __init__(self, parent=None, token=None, org_name=None):
super().__init__(parent)
self.token = token
self.org_name = org_name
self.layout = QVBoxLayout(self)
self.search_input = QLineEdit(self)
self.search_input.setPlaceholderText("Search for users...")
self.user_list = QListWidget(self)
self.layout.addWidget(self.search_input)
self.layout.addWidget(self.user_list)
self.search_timer = QTimer(self)
self.search_timer.setSingleShot(True)
self.search_timer.timeout.connect(self.search_users)
self.search_input.textChanged.connect(self.start_search_timer)
print("SearchableUserList initialized") # Debug print
def start_search_timer(self):
print(f"Search timer started for: {self.search_input.text()}") # Debug print
self.search_timer.start(300) # Wait for 300ms after the user stops typing
def search_users(self):
query = self.search_input.text()
print(f"Searching for: {query}") # Debug print
if len(query) < 3: # Only search if at least 3 characters are entered
self.user_list.clear()
return
headers = {"Authorization": f"token {self.token}"}
try:
url = f"https://github.hpe.com/api/v3/search/users"
params = {
"q": f"{query} in:login type:user org:{self.org_name}",
"per_page": 100
}
print(f"API call: {url}") # Debug print
print(f"Params: {params}") # Debug print
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
users = [user['login'] for user in response.json()['items']]
print(f"Found users: {users}") # Debug print
self.update_user_list(users)
self.search_completed.emit(users)
except requests.exceptions.RequestException as e:
print(f"Error searching users: {str(e)}")
self.user_list.clear()
def update_user_list(self, users):
self.user_list.clear()
for user in users:
item = QListWidgetItem(user)
self.user_list.addItem(item)
print(f"User list updated with {len(users)} users") # Debug print
def get_selected_users(self):
return [item.text() for item in self.user_list.selectedItems()]
class SyncedScrollArea(QScrollArea):
def __init__(self, parent=None):
super().__init__(parent)
self.viewport().installEventFilter(self)
def eventFilter(self, obj, event):
if obj == self.viewport() and event.type() == QEvent.Scroll:
self.parent().sync_scroll(self)
return super().eventFilter(obj, event)
class CommentSeparator(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedHeight(20) # Adjust this value to change the separator height
def paintEvent(self, event):
painter = QPainter(self)
painter.fillRect(self.rect(), QColor(240, 240, 240)) # Light gray background
painter.setPen(QPen(QColor(200, 200, 200), 1)) # Lighter gray line
painter.drawLine(0, self.height() // 2, self.width(), self.height() // 2)
class CommentWidget(QWidget):
def __init__(self, comment, parent=None):
super().__init__(parent)
self.comment = comment
self.init_ui()
def init_ui(self):
layout = QVBoxLayout(self)
# Header
header_layout = QHBoxLayout()
author_label = QLabel(f"<b>{self.comment['user']['login']}</b>")
time_label = QLabel(self.comment['created_at'])
header_layout.addWidget(author_label)
header_layout.addWidget(time_label)
header_layout.addStretch()
if not self.comment.get('resolved', False) and self.comment['type'] == 'review_comment':
resolve_button = QPushButton("Resolve")
resolve_button.clicked.connect(self.resolve_comment)
header_layout.addWidget(resolve_button)
layout.addLayout(header_layout)
# Comment body in Markdown
body_text = self.comment.get('body', '')
if body_text is not None:
body_html = markdown.markdown(body_text)
body_label = QLabel(body_html)
body_label.setWordWrap(True)
body_label.setTextFormat(Qt.RichText)
layout.addWidget(body_label)
else:
body_label = QLabel("No content")
layout.addWidget(body_label)
# Associated code (if any)
if self.comment['type'] == 'review_comment' and 'path' in self.comment and 'position' in self.comment:
code_frame = QFrame()
code_frame.setFrameShape(QFrame.StyledPanel)
code_layout = QVBoxLayout(code_frame)
code_label = QLabel(f"<b>File:</b> {self.comment['path']}")
code_layout.addWidget(code_label)
code_text = QTextEdit()
code_text.setReadOnly(True)
code_text.setMinimumHeight(300) # Increase the minimum height
code_text.setFont(QFont("Courier", 10)) # Set a monospace font and increase size
code_snippet = self.comment.get('code_snippet', 'Code snippet not available')
if code_snippet.startswith("Error fetching code snippet:"):
code_text.setStyleSheet("color: red;")
code_text.setPlainText(code_snippet)
code_layout.addWidget(code_text)
layout.addWidget(code_frame)
def resolve_comment(self):
print(f"Resolving comment: {self.comment.get('id', 'Unknown ID')}")
# Implement the actual resolution logic here
class Signals(QObject):
update_repo_combo = pyqtSignal(list)
update_repo_info = pyqtSignal(dict)
update_language_chart = pyqtSignal(dict)
update_commit_chart = pyqtSignal(list)
update_branches = pyqtSignal(list)
update_file_structure = pyqtSignal(list)
update_file_content = pyqtSignal(dict)
update_search_results = pyqtSignal(list)
update_prs = pyqtSignal(list)
update_pr_details = pyqtSignal(dict)
error_occurred = pyqtSignal(str)
class WorkerSignals(QObject):
finished = pyqtSignal()
error = pyqtSignal(str)
result = pyqtSignal(object)
class Worker(QRunnable):
def __init__(self, fn, *args, **kwargs):
super().__init__()
self.fn = fn
self.args = args
self.kwargs = kwargs
self.signals = WorkerSignals()
@pyqtSlot()
def run(self):
try:
result = self.fn(*self.args, **self.kwargs)
self.signals.result.emit(result)
except Exception as e:
self.signals.error.emit(str(e))
finally:
self.signals.finished.emit()
class GitHubInsightsTab(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.org_name = "hpe"
self.token = self.get_github_token()
self.cache = TTLCache(maxsize=100, ttl=300) # Cache with 5 minutes TTL
self.threadpool = QThreadPool()
self.signals = Signals()
# Separate reviewer widgets for PR tab
self.pr_reviewer_combo = QComboBox()
self.pr_reviewer_list = QListWidget()
self.pr_add_reviewer_button = QPushButton("Add Reviewer")
self.pr_remove_reviewer_button = QPushButton("Remove Reviewer")
# Separate reviewer widgets for Create PR tab
self.create_pr_reviewer_combo = QComboBox()
self.create_pr_reviewer_list = QListWidget()
self.create_pr_add_reviewer_button = QPushButton("Add Reviewer")
self.create_pr_remove_reviewer_button = QPushButton("Remove Reviewer")
# Connect signals
self.pr_add_reviewer_button.clicked.connect(self.add_pr_reviewer)
self.pr_remove_reviewer_button.clicked.connect(self.remove_pr_reviewer)
self.pr_reviewer_list.itemSelectionChanged.connect(self.update_pr_remove_reviewer_button)
self.create_pr_add_reviewer_button.clicked.connect(self.add_create_pr_reviewer)
self.create_pr_remove_reviewer_button.clicked.connect(self.remove_create_pr_reviewer)
self.create_pr_reviewer_list.itemSelectionChanged.connect(self.update_create_pr_remove_reviewer_button)
self.init_ui()
self.setup_browse_tab()
self.connect_signals()
# Create loading overlay after UI setup
self.loading_overlay = LoadingOverlay(self)
self.loading_overlay.hide()
# Load repositories after setup
QTimer.singleShot(0, self.load_repositories)
def add_pr_reviewer(self):
reviewer = self.pr_reviewer_combo.currentText()
if reviewer and self.pr_reviewer_list.findItems(reviewer, Qt.MatchExactly) == []:
self.add_reviewer_to_pr(reviewer)
def remove_pr_reviewer(self):
selected_items = self.pr_reviewer_list.selectedItems()
if selected_items:
reviewer = selected_items[0].text()
self.remove_reviewer_from_pr(reviewer)
def add_create_pr_reviewer(self):
selected_users = self.create_pr_user_search.get_selected_users()
for user in selected_users:
if self.create_pr_reviewer_list.findItems(user, Qt.MatchExactly) == []:
self.create_pr_reviewer_list.addItem(user)
self.create_pr_user_search.user_list.clearSelection()
self.create_pr_user_search.search_input.clear()
def remove_create_pr_reviewer(self):
selected_items = self.create_pr_reviewer_list.selectedItems()
for item in selected_items:
self.create_pr_reviewer_list.takeItem(self.create_pr_reviewer_list.row(item))
def update_pr_remove_reviewer_button(self):
self.pr_remove_reviewer_button.setEnabled(bool(self.pr_reviewer_list.selectedItems()))
def update_create_pr_remove_reviewer_button(self):
self.create_pr_remove_reviewer_button.setEnabled(bool(self.create_pr_reviewer_list.selectedItems()))
def update_remove_reviewer_button(self):
self.remove_reviewer_button.setEnabled(bool(self.reviewer_list.selectedItems()))
def connect_signals(self):
self.signals.update_repo_combo.connect(self.update_repo_combo)
self.signals.update_repo_info.connect(self.update_repo_info)
self.signals.update_language_chart.connect(self.update_language_chart)
self.signals.update_commit_chart.connect(self.update_commit_chart)
self.signals.update_branches.connect(self.update_branches)
self.signals.update_file_structure.connect(self.update_file_structure)
self.signals.update_file_content.connect(self.update_file_content)
self.signals.update_search_results.connect(self.update_search_results)
self.signals.update_prs.connect(self.update_prs)
self.signals.update_pr_details.connect(self.update_pr_details)
self.signals.error_occurred.connect(self.show_error_message)
def get_github_token(self):
token = keyring.get_password("github_insights", "github_token")
if not token:
dialog = GitHubAuthDialog(self)
if dialog.exec_() == QDialog.Accepted:
token = dialog.token
keyring.set_password("github_insights", "github_token", token)
else:
QMessageBox.critical(self, "Authentication Required", "GitHub token is required to use this feature.")
return None
return token
def showEvent(self, event):
super().showEvent(event)
self.loading_overlay.setGeometry(self.rect())
def resizeEvent(self, event):
super().resizeEvent(event)
if self.loading_overlay:
self.loading_overlay.setGeometry(self.rect())
def show_loading(self):
self.loading_overlay.setGeometry(self.rect())
self.loading_overlay.raise_() # Ensure it's on top
self.loading_overlay.show()
QApplication.processEvents() # Force update of the UI
def hide_loading(self):
self.loading_overlay.hide()
QApplication.processEvents() # Force update of the UI
def init_ui(self):
layout = QVBoxLayout(self)
# Repository selection
repo_layout = QHBoxLayout()
self.repo_combo = QComboBox()
repo_layout.addWidget(QLabel("Select Repository:"))
repo_layout.addWidget(self.repo_combo)
layout.addLayout(repo_layout)
# Tabs
self.tab_widget = QTabWidget()
layout.addWidget(self.tab_widget)
# Info Tab
self.info_tab = QScrollArea()
self.info_tab.setWidgetResizable(True)
self.info_content = QWidget()
self.info_layout = QVBoxLayout(self.info_content)
self.info_tab.setWidget(self.info_content)
self.tab_widget.addTab(self.info_tab, "Info")
# Browse Tab
self.browse_tab = QWidget()
self.browse_layout = QVBoxLayout(self.browse_tab)
self.tab_widget.addTab(self.browse_tab, "Browse")
# PRs Tab
self.prs_tab = QWidget()
self.prs_layout = QVBoxLayout(self.prs_tab)
self.tab_widget.addTab(self.prs_tab, "PRs")
# Create PR Tab
self.create_pr_tab = QWidget()
self.create_pr_layout = QVBoxLayout(self.create_pr_tab)
self.tab_widget.addTab(self.create_pr_tab, "Create PR")
self.setup_info_tab()
self.setup_prs_tab()
self.setup_create_pr_tab()
# Connect signals
self.repo_combo.currentTextChanged.connect(self.load_repo_data)
def show_loading_overlay(self):
self.create_pr_loading_overlay.setGeometry(self.rect())
self.create_pr_loading_overlay.show()
QApplication.processEvents()
def hide_loading_overlay(self):
self.create_pr_loading_overlay.hide()
QApplication.processEvents()
def setup_create_pr_tab(self):
main_layout = QHBoxLayout()
self.create_pr_layout.addLayout(main_layout)
# Left panel
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
# Source branch
self.source_branch_combo = QComboBox()
left_layout.addWidget(QLabel("Source Branch:"))
left_layout.addWidget(self.source_branch_combo)
# Target branch
self.dest_branch_combo = QComboBox()
left_layout.addWidget(QLabel("Target Branch:"))
left_layout.addWidget(self.dest_branch_combo)
# Reviewers section
reviewer_widget = QWidget()
reviewer_layout = QVBoxLayout(reviewer_widget)
reviewer_layout.addWidget(QLabel("Search and Select Reviewers:"))
self.create_pr_user_search = SearchableUserList(token=self.token, org_name=self.org_name)
reviewer_layout.addWidget(self.create_pr_user_search)
self.create_pr_add_reviewer_button = QPushButton("Add Selected Reviewers")
self.create_pr_add_reviewer_button.clicked.connect(self.add_create_pr_reviewer)
reviewer_layout.addWidget(self.create_pr_add_reviewer_button)
self.create_pr_reviewer_list = QListWidget()
reviewer_layout.addWidget(self.create_pr_reviewer_list)
self.create_pr_remove_reviewer_button = QPushButton("Remove Selected Reviewer")
self.create_pr_remove_reviewer_button.clicked.connect(self.remove_create_pr_reviewer)
reviewer_layout.addWidget(self.create_pr_remove_reviewer_button)
left_layout.addWidget(reviewer_widget)
# Create PR button
create_pr_button = QPushButton("Create PR")
create_pr_button.clicked.connect(self.create_pr)
left_layout.addWidget(create_pr_button)
left_layout.addStretch()
main_layout.addWidget(left_widget, 1)
# Right panel
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
# File changes dropdown
self.file_changes_combo = QComboBox()
self.file_changes_combo.currentTextChanged.connect(self.load_pr_file_diff)
right_layout.addWidget(QLabel("Changed Files:"))
right_layout.addWidget(self.file_changes_combo)
# Diff view
diff_splitter = QSplitter(Qt.Vertical)
self.old_diff_view = QTextEdit()
self.old_diff_view.setReadOnly(True)
self.old_diff_view.setStyleSheet("font-size: 14px; background-color: #f0f0f0;")
self.old_diff_view.verticalScrollBar().valueChanged.connect(lambda value: self.sync_scroll(self.old_diff_view))
self.new_diff_view = QTextEdit()
self.new_diff_view.setReadOnly(True)
self.new_diff_view.setStyleSheet("font-size: 14px; background-color: #f0f0f0;")
self.new_diff_view.verticalScrollBar().valueChanged.connect(lambda value: self.sync_scroll(self.new_diff_view))
diff_splitter.addWidget(self.old_diff_view)
diff_splitter.addWidget(self.new_diff_view)
right_layout.addWidget(diff_splitter)
main_layout.addWidget(right_widget, 2)
self.source_branch_combo.currentTextChanged.connect(self.update_file_changes)
self.dest_branch_combo.currentTextChanged.connect(self.update_file_changes)
# Add loading overlay
self.create_pr_loading_overlay = LoadingOverlay(self)
self.create_pr_loading_overlay.hide()
def remove_reviewer_from_pr(self, reviewer):
repo = self.repo_combo.currentText()
pr_number = self.current_pr_number
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.delete(
f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/pulls/{pr_number}/requested_reviewers",
json={"reviewers": [reviewer]},
headers=headers
)
response.raise_for_status()
items = self.pr_reviewer_list.findItems(reviewer, Qt.MatchExactly) # Changed from self.reviewer_list to self.pr_reviewer_list
if items:
self.pr_reviewer_list.takeItem(self.pr_reviewer_list.row(items[0])) # Changed from self.reviewer_list to self.pr_reviewer_list
except requests.exceptions.RequestException as e:
self.show_error_message(f"Failed to remove reviewer: {str(e)}")
def remove_reviewer(self):
selected_items = self.reviewer_list.selectedItems()
if selected_items:
reviewer = selected_items[0].text()
if hasattr(self, 'current_pr_number'):
# We're in the PR tab, so update the PR
self.remove_reviewer_from_pr(reviewer)
else:
# We're in the Create PR tab, just remove from the list
self.reviewer_list.takeItem(self.reviewer_list.row(selected_items[0]))
def load_reviewers(self, repo, pr_number):
headers = {"Authorization": f"token {self.token}"}
try:
# Fetch requested reviewers
requested_reviewers_response = requests.get(
f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/pulls/{pr_number}/requested_reviewers",
headers=headers
)
requested_reviewers_response.raise_for_status()
requested_reviewers = requested_reviewers_response.json()['users']
# Fetch reviews to get additional reviewers who have already submitted reviews
reviews_response = requests.get(
f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/pulls/{pr_number}/reviews",
headers=headers
)
reviews_response.raise_for_status()
reviews = reviews_response.json()
# Combine all unique reviewers
all_reviewers = set(reviewer['login'] for reviewer in requested_reviewers)
all_reviewers.update(review['user']['login'] for review in reviews)
self.pr_reviewer_list.clear()
for reviewer in all_reviewers:
self.pr_reviewer_list.addItem(reviewer)
print(f"Fetched reviewers: {list(all_reviewers)}")
except requests.exceptions.RequestException as e:
self.show_error_message(f"Failed to load reviewers: {str(e)}")
def load_repositories(self):
if not self.token:
return
self.show_loading()
worker = Worker(self.fetch_repositories)
worker.signals.result.connect(self.update_repo_combo)
worker.signals.finished.connect(self.hide_loading)
worker.signals.error.connect(self.handle_error)
self.threadpool.start(worker)
def handle_error(self, error_message):
self.hide_loading()
self.show_error_message(error_message)
def fetch_repositories(self):
headers = {"Authorization": f"token {self.token}"}
org_name = "hpe"
try:
response = requests.get(
f"https://github.hpe.com/api/v3/search/repositories",
params={
"q": f"org:{org_name} ez in:name",
"sort": "updated",
"order": "desc",
"per_page": 100
},
headers=headers
)
response.raise_for_status()
search_results = response.json()
ez_repos = [repo['name'] for repo in search_results.get('items', [])]
return sorted(ez_repos)
except requests.exceptions.RequestException as e:
raise Exception(f"Failed to search repositories: {str(e)}")
def update_repo_combo(self, repos):
self.repo_combo.clear()
self.repo_combo.addItems(repos)
def load_repo_data(self, repo):
if not self.token or not repo:
return
self.show_loading()
worker = Worker(self.fetch_repo_data, repo)
worker.signals.result.connect(self.update_repo_info)
worker.signals.finished.connect(self.hide_loading)
worker.signals.error.connect(self.handle_error)
self.threadpool.start(worker)
# Only load branches if a repository is selected
if repo:
self.load_branches()
self.update_file_changes()
def fetch_repo_data(self, repo):
repo_info = self.fetch_repo_info(repo)
branches = self.fetch_branches(repo)
prs = self.fetch_prs(repo)
return {'repo_info': repo_info, 'branches': branches, 'prs': prs}
def sync_scroll(self, source):
if source == self.old_diff_view:
self.new_diff_view.verticalScrollBar().setValue(source.verticalScrollBar().value())
else:
self.old_diff_view.verticalScrollBar().setValue(source.verticalScrollBar().value())
def fetch_repo_info(self, repo):
cache_key = f"repo_info_{repo}"
if cache_key in self.cache:
return self.cache[cache_key]
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}", headers=headers)
response.raise_for_status()
repo_data = response.json()
self.cache[cache_key] = repo_data
return repo_data
except requests.exceptions.RequestException as e:
error_message = f"Failed to fetch repo info: {str(e)}"
if hasattr(e, 'response') and e.response is not None:
error_message += f"\nStatus code: {e.response.status_code}"
error_message += f"\nResponse text: {e.response.text}"
self.signals.error_occurred.emit(error_message)
return None
def update_repo_info(self, repo_data):
if not isinstance(repo_data, dict) or 'repo_info' not in repo_data:
self.repo_summary.setText("Failed to fetch repository information.")
return
repo_info = repo_data['repo_info']
if not isinstance(repo_info, dict):
self.repo_summary.setText("Invalid repository information format.")
return
summary = f"Repository: {repo_info.get('name', 'Unknown')}\n"
summary += f"Description: {repo_info.get('description', 'No description')}\n"
summary += f"Stars: {repo_info.get('stargazers_count', 'N/A')}\n"
summary += f"Forks: {repo_info.get('forks_count', 'N/A')}\n"
summary += f"Open Issues: {repo_info.get('open_issues_count', 'N/A')}\n"
summary += f"Created: {repo_info.get('created_at', 'N/A')}\n"
summary += f"Last Updated: {repo_info.get('updated_at', 'N/A')}\n"
self.repo_summary.setText(summary)
if 'name' in repo_info:
self.load_language_chart(repo_info['name'])
self.load_commit_chart(repo_info['name'])
else:
print("Warning: Repository name not found in repo_info")
# Ensure the info tab is visible and updated
self.tab_widget.setCurrentWidget(self.info_tab)
self.info_tab.update()
def load_language_chart(self, repo):
worker = Worker(self.fetch_language_data, repo)
worker.setAutoDelete(True)
self.threadpool.start(worker)
def fetch_language_data(self, repo):
cache_key = f"language_data_{repo}"
if cache_key in self.cache:
self.signals.update_language_chart.emit(self.cache[cache_key])
return
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/languages", headers=headers)
response.raise_for_status()
languages = response.json()
self.cache[cache_key] = languages
self.signals.update_language_chart.emit(languages)
except requests.exceptions.RequestException as e:
self.signals.error_occurred.emit(f"Error fetching language data: {str(e)}")
def update_language_chart(self, languages):
ax = self.language_chart.figure.subplots()
ax.clear()
ax.pie(languages.values(), labels=languages.keys(), autopct='%1.1f%%')
ax.set_title("Language Breakdown")
self.language_chart.draw()
def load_commit_chart(self, repo):
worker = Worker(self.fetch_commit_data, repo)
worker.setAutoDelete(True)
self.threadpool.start(worker)
def fetch_commit_data(self, repo):
cache_key = f"commit_data_{repo}"
if cache_key in self.cache:
self.signals.update_commit_chart.emit(self.cache[cache_key])
return
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/stats/commit_activity", headers=headers)
response.raise_for_status()
commit_data = response.json()
self.cache[cache_key] = commit_data
self.signals.update_commit_chart.emit(commit_data)
except requests.exceptions.RequestException as e:
self.signals.error_occurred.emit(f"Error fetching commit data: {str(e)}")
def update_commit_chart(self, commit_data):
ax = self.commit_chart.figure.subplots()
ax.clear()
weeks = range(len(commit_data))
commits = [week['total'] for week in commit_data]
ax.bar(weeks, commits)
ax.set_title("Commit Activity (Last 52 Weeks)")
ax.set_xlabel("Weeks Ago")
ax.set_ylabel("Number of Commits")
self.commit_chart.draw()
def fetch_branches(self, repo):
cache_key = f"branches_{repo}"
if cache_key in self.cache:
self.signals.update_branches.emit(self.cache[cache_key])
return
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/branches", headers=headers)
response.raise_for_status()
branches = [branch['name'] for branch in response.json()]
self.cache[cache_key] = branches
self.signals.update_branches.emit(branches)
except requests.exceptions.RequestException as e:
self.signals.error_occurred.emit(f"Failed to fetch branches: {str(e)}")
def update_branches(self, branches):
self.branch_combo.clear()
self.branch_combo.addItems(branches)
if branches:
self.branch_combo.setCurrentIndex(0)
self.load_file_structure(branches[0])
def load_file_structure(self, branch):
if not branch or not hasattr(self, 'file_tree'):
return
repo = self.repo_combo.currentText()
worker = Worker(self.fetch_file_structure, repo, branch)
worker.setAutoDelete(True)
self.threadpool.start(worker)
def fetch_file_structure(self, repo, branch):
cache_key = f"file_structure_{repo}_{branch}"
if cache_key in self.cache:
self.signals.update_file_structure.emit(self.cache[cache_key])
return
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/git/trees/{branch}?recursive=1", headers=headers)
response.raise_for_status()
tree = response.json()['tree']
self.cache[cache_key] = tree
self.signals.update_file_structure.emit(tree)
except requests.exceptions.RequestException as e:
self.signals.error_occurred.emit(f"Failed to fetch file structure: {str(e)}")
def update_file_structure(self, tree):
model = QStandardItemModel()
root = model.invisibleRootItem()
for item in tree:
path = item['path'].split('/')
parent = root
for i, folder in enumerate(path):
if i == len(path) - 1:
child = QStandardItem(folder)
child.setData(item['path'], Qt.UserRole)
parent.appendRow(child)
else:
found = False
for row in range(parent.rowCount()):
if parent.child(row).text() == folder:
parent = parent.child(row)
found = True
break
if not found:
new_folder = QStandardItem(folder)
parent.appendRow(new_folder)
parent = new_folder
if self.file_tree is not None and not sip.isdeleted(self.file_tree):
self.file_tree.setModel(model)
def load_file_content(self, index):
item = self.file_tree.model().itemFromIndex(index)
file_path = item.data(Qt.UserRole)
if not file_path:
return
repo = self.repo_combo.currentText()
branch = self.branch_combo.currentText()
worker = Worker(self.fetch_file_content, repo, branch, file_path)
worker.setAutoDelete(True)
self.threadpool.start(worker)
def fetch_file_content(self, repo, branch, file_path):
cache_key = f"file_content_{repo}_{branch}_{file_path}"
if cache_key in self.cache:
self.signals.update_file_content.emit(self.cache[cache_key])
return
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/contents/{file_path}?ref={branch}", headers=headers)
response.raise_for_status()
file_data = response.json()
self.cache[cache_key] = file_data
self.signals.update_file_content.emit(file_data)
except requests.exceptions.RequestException as e:
if response.status_code == 404:
error_message = f"Error fetching file content: File {file_path} not found in branch {branch}"
else:
error_message = f"Failed to fetch file content: {str(e)}"
self.signals.error_occurred.emit(error_message)
def update_file_content(self, file_data):
if isinstance(file_data, dict) and file_data.get('type') == 'file':
if file_data['encoding'] == 'base64':
try:
content = base64.b64decode(file_data['content']).decode('utf-8')
self.file_content.setPlainText(content)
# Apply syntax highlighting
highlighter = CodeHighlighter(self.file_content.document())
except UnicodeDecodeError:
self.file_content.setPlainText(f"Binary file: {file_data['path']}\nSize: {file_data['size']} bytes")
else:
self.file_content.setPlainText(f"Unsupported encoding: {file_data['encoding']}")
else:
self.file_content.setPlainText(f"This is not a file or the response is unexpected.")
def search_repository(self):
query = self.search_input.text()
if not query:
return
repo = self.repo_combo.currentText()
worker = Worker(self.fetch_search_results, repo, query)
worker.setAutoDelete(True)
self.threadpool.start(worker)
def fetch_search_results(self, repo, query):
headers = {"Authorization": f"token {self.token}"}
try:
response = requests.get(
f"https://github.hpe.com/api/v3/search/code",
params={
"q": f"repo:{self.org_name}/{repo} {query}",
"per_page": 100
},
headers=headers
)
response.raise_for_status()
results = response.json()['items']
self.signals.update_search_results.emit(results)
except requests.exceptions.RequestException as e:
self.signals.error_occurred.emit(f"Failed to search repository: {str(e)}")
def update_search_results(self, results):
search_results = "Search Results:\n\n"
for item in results:
search_results += f"File: {item['path']}\n"
search_results += f"URL: {item['html_url']}\n\n"
self.file_content.setText(search_results)
def fetch_prs(self, repo):
cache_key = f"prs_{repo}"
if cache_key in self.cache:
self.signals.update_prs.emit(self.cache[cache_key])
return
headers = {"Authorization": f"token {self.token}"}
try:
# Fetch last 50 PRs (both open and closed)
prs_response = requests.get(
f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/pulls",
params={"state": "all", "sort": "created", "direction": "desc", "per_page": 50},
headers=headers
)
prs_response.raise_for_status()
all_prs = prs_response.json()
self.cache[cache_key] = all_prs
self.signals.update_prs.emit(all_prs)
except requests.exceptions.RequestException as e:
self.signals.error_occurred.emit(f"Failed to fetch PRs: {str(e)}")
def update_prs(self, all_prs):
self.pr_table.setRowCount(0)
self.pr_table.setColumnCount(7)
self.pr_table.setHorizontalHeaderLabels(["PR #", "Title", "Owner", "Source", "Target", "Date Opened", "Status"])
# Set column widths
self.pr_table.setColumnWidth(0, 60) # PR #
self.pr_table.setColumnWidth(1, 400) # Title
self.pr_table.setColumnWidth(2, 200) # Owner
self.pr_table.setColumnWidth(3, 100) # Source
self.pr_table.setColumnWidth(4, 100) # Target
self.pr_table.setColumnWidth(5, 150) # Date Opened
self.pr_table.setColumnWidth(6, 100) # Status
owners = set(["All Owners"])
for pr in all_prs:
row_position = self.pr_table.rowCount()
self.pr_table.insertRow(row_position)
self.pr_table.setItem(row_position, 0, QTableWidgetItem(str(pr['number'])))
self.pr_table.setItem(row_position, 1, QTableWidgetItem(pr['title']))
self.pr_table.setItem(row_position, 2, QTableWidgetItem(pr['user']['login']))
self.pr_table.setItem(row_position, 3, QTableWidgetItem(pr['head']['ref']))
self.pr_table.setItem(row_position, 4, QTableWidgetItem(pr['base']['ref']))
self.pr_table.setItem(row_position, 5, QTableWidgetItem(pr['created_at']))
self.pr_table.setItem(row_position, 6, QTableWidgetItem(pr['state']))
owners.add(pr['user']['login'])
# Update owner filter
current_owner = self.owner_filter.currentText()
self.owner_filter.clear()
self.owner_filter.addItems(sorted(owners))
if current_owner in owners:
self.owner_filter.setCurrentText(current_owner)
else:
self.owner_filter.setCurrentText("All Owners")
# Make the title column stretch to fill remaining space
self.pr_table.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
self.apply_filters()
def load_pr_details(self, item):
if isinstance(item, str):
pr_number = item
else:
pr_number = self.pr_table.item(item.row(), 0).text()
self.current_pr_number = pr_number # Store the current PR number
repo = self.repo_combo.currentText()
worker = Worker(self.fetch_pr_details, repo, pr_number)
worker.signals.result.connect(self.update_pr_details)
worker.signals.finished.connect(self.hide_loading)
worker.signals.error.connect(self.handle_error)
self.threadpool.start(worker)
# Load comments and reviewers
self.load_pr_comments(repo, pr_number)
self.load_reviewers(repo, pr_number) # Make sure this line is present
def fetch_pr_details(self, repo, pr_number):
cache_key = f"pr_details_{repo}_{pr_number}"
if cache_key in self.cache:
return self.cache[cache_key]
headers = {"Authorization": f"token {self.token}"}
try:
# Fetch PR details
pr_response = requests.get(
f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/pulls/{pr_number}",
headers=headers
)
pr_response.raise_for_status()
pr_data = pr_response.json()
# Fetch commits for this PR
commits_response = requests.get(
f"https://github.hpe.com/api/v3/repos/{self.org_name}/{repo}/pulls/{pr_number}/commits",
headers=headers
)
commits_response.raise_for_status()
commits = commits_response.json()
pr_details = {
'pr_data': pr_data,
'commits': commits
}
self.cache[cache_key] = pr_details
return pr_details
except requests.exceptions.RequestException as e:
error_message = f"Failed to fetch PR details: {str(e)}"
if hasattr(e, 'response') and e.response is not None:
error_message += f"\nStatus code: {e.response.status_code}"
error_message += f"\nResponse text: {e.response.text}"
raise Exception(error_message)
def update_pr_details(self, pr_details):
pr_data = pr_details['pr_data']
commits = pr_details['commits']
# Update description tab
self.pr_description_editor.setPlainText(pr_data.get('body', ''))
self.update_description_preview()
def load_commit_file_diff(self, filename):
print(f"Debug: load_commit_file_diff called with filename: {filename}")
file_data = self.file_combo.currentData()
print(f"Debug: file_data: {file_data}")
if file_data: