-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathdisplay.py
More file actions
1564 lines (1321 loc) · 55.3 KB
/
Copy pathdisplay.py
File metadata and controls
1564 lines (1321 loc) · 55.3 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
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
"""
Display formatter for git provider statistics in neofetch style
"""
from typing import Dict, Any, Optional
import shutil
import sys
import re
import unicodedata
from datetime import datetime
from .config import ConfigManager
from .text_patterns import CHAR_PATTERNS
from .calculations import calculate_total_contributions, get_contribution_color_level
import subprocess
import webcolors
def hex_to_ansi(hex_color: str, background: bool = False) -> str:
"""Convert hex color to ANSI escape code."""
if not hex_color.startswith("#"):
return hex_color # Already ANSI or invalid
hex_color = hex_color.lstrip("#")
if len(hex_color) != 6:
return hex_color
try:
r = int(hex_color[0:2], 16)
g = int(hex_color[2:4], 16)
b = int(hex_color[4:6], 16)
if background:
return f"\033[48;2;{r};{g};{b}m"
else:
return f"\033[38;2;{r};{g};{b}m"
except ValueError:
return hex_color
class DisplayFormatter:
"""Formats and displays git provider stats in a neofetch-style layout."""
def __init__(
self,
config_manager: ConfigManager,
custom_box: Optional[str] = None,
show_date: Optional[bool] = None,
graph_only: bool = False,
show_achievements: bool = True,
show_languages: bool = True,
show_issues: bool = True,
show_pr: bool = True,
show_account: bool = True,
show_grid: bool = True,
custom_width: Optional[int] = None,
custom_height: Optional[int] = None,
graph_timeline: bool = False,
local_mode: bool = False,
shape: Optional[list] = None,
text: Optional[str] = None,
text_patterns: Optional[dict] = None,
):
"""Initialize the display formatter."""
terminal_size = shutil.get_terminal_size()
self.terminal_width = terminal_size.columns
self.terminal_height = terminal_size.lines
# Reserve some lines for prompt/shell status
self.available_height = max(10, self.terminal_height - 2)
self.enable_color = sys.stdout.isatty()
self.colors = config_manager.get_ansi_colors()
self.hex_colors = config_manager.get_colors()
self.custom_box = custom_box or config_manager.get_custom_box() or "■"
self.show_date = show_date if show_date is not None else True
self.graph_only = graph_only
self.show_achievements = show_achievements
self.show_languages = show_languages
self.show_issues = show_issues
self.show_pr = show_pr
self.show_account = show_account
self.show_grid = show_grid
self.custom_width = custom_width
self.custom_height = custom_height
self.graph_timeline = graph_timeline
self.local_mode = local_mode
self.text = text
# Allow overriding or extending the built-in character patterns.
# If not provided, fall back to bundled CHAR_PATTERNS.
self.text_patterns = text_patterns or CHAR_PATTERNS
# Store shape (may be None or list/str). If simulating text or
# shape, always suppress month/date line because month labels don't
# align with simulated grids.
self.shape = shape
self.suppress_month_line = bool(self.text) or bool(self.shape)
def display(
self,
username: str,
user_data: Dict[str, Any],
stats: Dict[str, Any],
spaced=True,
) -> None:
"""
Display git provider statistics in neofetch style.
Args:
username: Git provider username
user_data: User profile data
stats: User statistics data
spaced: Spaced layout
"""
# Determine layout based on available space and content dimensions
layout = self._determine_layout(username, user_data, stats)
if layout == "minimal":
# Only show contribution graph
self._display_minimal(username, stats, spaced)
elif layout == "compact":
# Show graph and key info
self._display_compact(username, user_data, stats, spaced)
else:
# Full layout with all sections
self._display_full(username, user_data, stats, spaced)
print() # Empty line at the end
def _calculate_layout_dimensions(
self,
username: str,
user_data: Dict[str, Any],
stats: Dict[str, Any],
layout: str,
) -> tuple:
"""Calculate width and height required for a given layout."""
if layout == "minimal":
return self._calculate_minimal_dimensions(username, stats)
elif layout == "compact":
return self._calculate_compact_dimensions(username, user_data, stats)
elif layout == "full":
return self._calculate_full_dimensions(username, user_data, stats)
return (0, 0)
def _calculate_minimal_dimensions(
self, username: str, stats: Dict[str, Any]
) -> tuple:
"""Calculate dimensions for minimal layout (graph only)."""
if not self.show_grid:
# Just header dimensions
contrib_graph = stats.get("contribution_graph", [])
total_contribs = self._calculate_total_contributions(
self._get_recent_weeks(contrib_graph)
)
header_lines = self._graph_header(username, total_contribs)
width = max((self._display_width(line) for line in header_lines), default=0)
height = len(header_lines)
return (width, height)
# Use custom dimensions if provided
width = (
self.custom_width
if self.custom_width is not None
else self.terminal_width - 4
)
height = self.custom_height if self.custom_height is not None else 7
return (width, height)
def _calculate_compact_dimensions(
self, username: str, user_data: Dict[str, Any], stats: Dict[str, Any]
) -> tuple:
"""Calculate dimensions for compact layout."""
contrib_graph = stats.get("contribution_graph", [])
recent_weeks = self._get_recent_weeks(contrib_graph)
graph_width = (
self.custom_width
if self.custom_width is not None
else max(40, (self.terminal_width - 40) * 3 // 4)
)
if self.show_grid:
# Use custom height for graph height
graph_height = self.custom_height if self.custom_height is not None else 7
else:
# Just header for dimensions
total_contribs = self._calculate_total_contributions(recent_weeks)
graph_lines = self._graph_header(username, total_contribs)
graph_width = max(
(self._display_width(line) for line in graph_lines), default=0
)
graph_height = len(graph_lines)
right_side = []
if self.show_account:
info_lines = self._format_user_info_compact(user_data, stats)
right_side.extend(info_lines)
if self.show_achievements:
achievements = self._build_achievements(recent_weeks, stats)
if achievements:
if right_side:
right_side.append("")
right_side.extend(achievements)
max_lines = max(graph_height, len(right_side))
right_width = max((self._display_width(line) for line in right_side), default=0)
total_width = graph_width + 2 + right_width
return (total_width, max_lines)
def _calculate_full_dimensions(
self, username: str, user_data: Dict[str, Any], stats: Dict[str, Any]
) -> tuple:
"""Calculate dimensions for full layout."""
contrib_graph = stats.get("contribution_graph", [])
graph_width = (
self.custom_width
if self.custom_width is not None
else max(50, (self.terminal_width - 10) * 3 // 4)
)
left_side = []
if self.show_grid:
left_side = self._get_contribution_graph_lines(
contrib_graph,
username,
width_constraint=graph_width,
include_sections=False,
spaced=True,
)
info_lines = (
self._format_user_info(user_data, stats) if self.show_account else []
)
language_lines = self._format_languages(stats) if self.show_languages else []
recent_weeks = self._get_recent_weeks(contrib_graph)
achievements = (
self._build_achievements(recent_weeks, stats)
if self.show_achievements
else []
)
right_side = list(info_lines)
if language_lines and self.terminal_width >= 120:
right_side.append("")
right_side.extend(language_lines)
if achievements:
right_side.append("")
right_side.extend(achievements)
max_left_width = (
max(self._display_width(line) for line in left_side) if left_side else 0
)
max_right_width = (
max(self._display_width(line) for line in right_side) if right_side else 0
)
total_width = max_left_width + 2 + max_right_width
total_height = max(len(left_side), len(right_side))
return (total_width, total_height)
def _determine_layout(
self, username: str, user_data: Dict[str, Any], stats: Dict[str, Any]
) -> str:
"""Determine layout based on available space and content dimensions."""
# If graph_only is set, always use minimal
if self.graph_only:
return "minimal"
layouts = ["full", "compact", "minimal"]
best_layout = "minimal"
for layout in layouts:
width, height = self._calculate_layout_dimensions(
username, user_data, stats, layout
)
# Check if this layout fits
if width <= self.terminal_width and height <= self.available_height:
best_layout = layout
break
return best_layout
def _display_minimal(
self, username: str, stats: Dict[str, Any], spaced=True
) -> None:
"""Display only contribution graph for narrow terminals."""
if self.graph_timeline:
# Show git timeline graph
try:
timeline_text = self._get_graph_text()
print(timeline_text)
except Exception as e:
print(f"Error displaying timeline: {e}")
return
if not self.show_grid:
# Show just the header without grid
contrib_graph = stats.get("contribution_graph", [])
total_contribs = self._calculate_total_contributions(
self._get_recent_weeks(contrib_graph)
)
header_lines = self._graph_header(username, total_contribs)
for line in header_lines:
print(line)
return
contrib_graph = stats.get("contribution_graph", [])
graph_lines = self._get_contribution_graph_lines(
contrib_graph,
username,
width_constraint=self.terminal_width - 4,
include_sections=False,
spaced=spaced,
)
for line in graph_lines:
print(line)
def _display_compact(
self,
username: str,
user_data: Dict[str, Any],
stats: Dict[str, Any],
spaced=True,
) -> None:
"""Display graph and minimal info side-by-side (no languages)."""
if self.graph_timeline:
# Show git timeline graph (only if no right side content for layout)
right_side = []
if self.show_account:
info_lines = self._format_user_info_compact(user_data, stats)
right_side.extend(info_lines)
if self.show_achievements:
contrib_graph = stats.get("contribution_graph", [])
recent_weeks = self._get_recent_weeks(contrib_graph)
achievements = self._build_achievements(recent_weeks, stats)
if achievements:
if right_side:
right_side.append("")
right_side.extend(achievements)
if not right_side:
try:
timeline_text = self._get_graph_text()
print(timeline_text)
except Exception as e:
print(f"Error displaying timeline: {e}")
return
# Fall back to normal display if there's right side content
contrib_graph = stats.get("contribution_graph", [])
recent_weeks = self._get_recent_weeks(contrib_graph)
graph_width = max(40, (self.terminal_width - 40) * 3 // 4)
if self.show_grid:
graph_lines = self._get_contribution_graph_lines(
contrib_graph,
username,
width_constraint=graph_width,
include_sections=False,
spaced=spaced,
)
else:
# Show just header without grid
total_contribs = self._calculate_total_contributions(recent_weeks)
graph_lines = self._graph_header(username, total_contribs)
right_side = []
if self.show_account:
info_lines = self._format_user_info_compact(user_data, stats)
right_side.extend(info_lines)
if self.show_achievements:
achievements = self._build_achievements(recent_weeks, stats)
if achievements:
if right_side:
right_side.append("")
right_side.extend(achievements)
# If no right side content, just show left side
if not right_side:
for line in graph_lines:
print(line)
return
# Display side-by-side
max_lines = max(len(graph_lines), len(right_side))
for i in range(max_lines):
graph_part = graph_lines[i] if i < len(graph_lines) else ""
graph_len = self._display_width(graph_part)
padding = " " * max(0, graph_width - graph_len)
info_part = right_side[i] if i < len(right_side) else ""
print(f"{graph_part}{padding} {info_part}")
def _reverse_truncate(self, line: str, max_width: int):
pattern = r"(\x1b\[[0-9;]*m)(.*?)(?=(\x1b\[[0-9;]*m)|$)"
matches = re.findall(pattern, line, flags=re.DOTALL)
segments = [(m[0], m[1]) for m in matches]
width = sum(len(text) for _, text in segments)
if width <= max_width:
return line.rjust(max_width)
result = []
remaining = max_width
for color, text in reversed(segments):
if remaining <= 0:
break
if len(text) <= remaining:
result.append((color, text))
remaining -= len(text)
else:
result.append((color, text[-remaining:]))
remaining = 0
final = "".join(color + text for color, text in reversed(result))
final += self.colors.get("reset", "\x1b[0m")
return final
def _display_full(
self,
username: str,
user_data: Dict[str, Any],
stats: Dict[str, Any],
spaced=True,
) -> None:
"""Display full layout with graph and all info sections."""
left_side = []
if self.graph_timeline:
# Show git timeline graph instead of contribution graph
try:
timeline_text = self._get_graph_text(False)
left_side = timeline_text.split("\n")
# Still show right side info
contrib_graph = stats.get("contribution_graph", [])
info_lines = (
self._format_user_info(user_data, stats)
if self.show_account
else []
)
language_lines = (
self._format_languages(stats) if self.show_languages else []
)
recent_weeks = self._get_recent_weeks(contrib_graph)
achievements = (
self._build_achievements(recent_weeks, stats)
if self.show_achievements
else []
)
right_side = list(info_lines)
if language_lines and self.terminal_width >= 120:
right_side.append("")
right_side.extend(language_lines)
if achievements:
right_side.append("")
right_side.extend(achievements)
right_width = max(self._display_width(line) for line in right_side)
offset = 80
max_width = self.terminal_width - right_width - offset
if right_side and left_side:
print() # Add spacing
for l, r in zip(left_side, right_side):
print(
self._reverse_truncate(l, max_width),
self.colors["reset"],
r,
)
except Exception as e:
print(f"Error displaying timeline: {e}")
return
contrib_graph = stats.get("contribution_graph", [])
graph_width = (
self.custom_width
if self.custom_width is not None
else max(50, (self.terminal_width - 10) * 3 // 4)
)
if self.show_grid:
left_side = self._get_contribution_graph_lines(
contrib_graph,
username,
width_constraint=graph_width,
include_sections=False,
spaced=spaced,
)
# Add PR/issues sections to left side if enabled
if self.show_pr or self.show_issues:
pull_request_lines = (
self._format_pull_requests(stats) if self.show_pr else []
)
issue_lines = self._format_issues(stats) if self.show_issues else []
section_columns = []
if pull_request_lines and issue_lines:
pr_width = max(
(self._display_width(line) for line in pull_request_lines),
default=0,
)
issue_width = max(
(self._display_width(line) for line in issue_lines), default=0
)
total_width = pr_width + issue_width + len(" ") # gap
if total_width <= graph_width:
section_columns = [pull_request_lines, issue_lines]
elif pull_request_lines:
section_columns = [pull_request_lines]
elif issue_lines:
section_columns = [issue_lines]
combined_sections = self._combine_section_grid(
section_columns, width_limit=graph_width
)
if combined_sections:
if left_side:
left_side.append("")
left_side.extend(combined_sections)
elif not self.show_grid:
# If no grid and no PR/issues, show just header
total_contribs = self._calculate_total_contributions(
self._get_recent_weeks(contrib_graph)
)
left_side = self._graph_header(username, total_contribs)
info_lines = (
self._format_user_info(user_data, stats) if self.show_account else []
)
language_lines = self._format_languages(stats) if self.show_languages else []
recent_weeks = self._get_recent_weeks(contrib_graph)
achievements = (
self._build_achievements(recent_weeks, stats)
if self.show_achievements
else []
)
right_side = list(info_lines)
if language_lines and self.terminal_width >= 120:
right_side.append("")
right_side.extend(language_lines)
if achievements:
right_side.append("")
right_side.extend(achievements)
# If no right side content, just show left side
if not right_side:
for line in left_side:
print(line)
return
# Display side-by-side
max_left_width = (
max(self._display_width(line) for line in left_side) if left_side else 0
)
for i in range(max(len(left_side), len(right_side))):
if i < len(left_side):
left_raw = left_side[i]
else:
left_raw = ""
raw_length = self._display_width(left_raw)
padding = " " * max(0, max_left_width - raw_length)
left_part = f"{left_raw}{padding}"
info_part = right_side[i] if i < len(right_side) else ""
print(f"{left_part} {info_part}")
def _get_contribution_graph_lines(
self,
weeks_data: list,
username: str,
width_constraint: Optional[int] = None,
include_sections: bool = True,
spaced: bool = True,
stats: Optional[Dict[str, Any]] = None,
) -> list:
"""
Get contribution graph as lines for display.
Args:
weeks_data: List of weeks with contribution data
username: GitHub username
width_constraint: Maximum width in characters (None for auto)
Returns:
List of strings representing graph lines
"""
if self.text:
# Generate fake weeks_data from text
text_grid = self._text_to_grid(self.text)
if not text_grid:
return ["No text to display"]
weeks_data = self._generate_weeks_from_text_grid(text_grid)
if self.local_mode:
try:
weeks_data = self._get_local_contribution_weeks()
except Exception as e:
return [f"Error getting local contributions: {e}"]
else:
weeks_data = weeks_data
recent_weeks = self._get_recent_weeks(weeks_data)
total_contribs = self._calculate_total_contributions(recent_weeks)
header_lines = self._graph_header(username, total_contribs)
if not recent_weeks:
return [*header_lines, *self._empty_graph_placeholder()]
# Calculate how many weeks we can fit
if self.custom_width is not None:
width_constraint = self.custom_width
elif width_constraint is None:
width_constraint = self.terminal_width - 8
max_weeks = self._calculate_max_weeks(width_constraint)
display_weeks = (
recent_weeks[-max_weeks:] if len(recent_weeks) > max_weeks else recent_weeks
)
# Determine how many days to show
days_to_show = 7
if self.custom_height is not None:
days_to_show = min(7, max(1, self.custom_height))
# Prepare rows for each day of the week (Sun-Sat)
day_rows: list[list[str]] = [[] for _ in range(days_to_show)]
for week in display_weeks:
days = week.get("contributionDays", [])
for idx in range(days_to_show):
day = days[idx] if idx < len(days) else {}
count = day.get("contributionCount", 0)
if spaced:
block = self._get_contribution_block_spaced(count)
else:
block = self._get_contribution_block(count)
day_rows[idx].append(block)
lines = [*header_lines]
if self.suppress_month_line or not self.show_date:
month_line = None
else:
month_line = self._build_month_line_spaced(display_weeks)
if month_line and month_line.strip():
lines.append(month_line)
# Add grid rows (no vertical spacing between rows)
for row_idx, row in enumerate(day_rows):
lines.append(f" {''.join(row)}")
# Add achievements section
if include_sections:
achievements = self._build_achievements(recent_weeks, stats)
if achievements:
lines.append("")
lines.extend(achievements)
return lines
def _get_local_contribution_weeks(self):
"""Get contribution weeks from local git repository."""
from .fetcher import BaseFetcher
return BaseFetcher._build_contribution_graph_from_git()
def _get_graph_text(self, vertical=False):
text = (
subprocess.check_output(
[
"git",
"--no-pager",
"log",
"--color=always",
"--graph",
"--all",
'--pretty=format:""',
]
)
.decode()
.replace('"', "")
)
if vertical:
return text
text = text.translate(str.maketrans(r"\/", r"\/"[::-1])).replace("|", "-")
ANSI_PATTERN = re.compile(r"\033\[[0-9;]*m")
lines = text.splitlines()
parsed_lines = []
for line in lines:
parts = ANSI_PATTERN.split(line)
codes = ANSI_PATTERN.findall(line)
current_color = ""
parsed = []
for i, seg in enumerate(parts):
for ch in seg:
parsed.append((ch, current_color))
if i < len(codes):
code = codes[i]
current_color = "" if code == "\033[0m" else code
parsed_lines.append(parsed)
if not parsed_lines:
return ""
max_len = max(len(line) for line in parsed_lines)
padded = [line + [(" ", "")] * (max_len - len(line)) for line in parsed_lines]
rotated = []
for col in reversed(range(max_len)):
new_row = [padded[row][col] for row in range(len(padded))]
rotated.append(new_row)
out_lines = []
for row in rotated:
cur_color = ""
out_line = ""
for ch, color in row:
if color != cur_color:
out_line += color
cur_color = color
out_line += ch
if cur_color:
out_line += "\033[0m"
out_lines.append(out_line)
return "\n".join(out_lines)
def _format_user_info_compact(
self, user_data: Dict[str, Any], stats: Dict[str, Any]
) -> list:
"""Format minimal user info for compact layout."""
lines = []
name = user_data.get("name") or user_data.get("login", "unknown")
total_contributions = stats.get("total_contributions")
if total_contributions is None:
total_contributions = self._calculate_total_contributions(
stats.get("contribution_graph", [])
)
# Format user line with same coloring as full display
contrib_str = self._colorize(f"{total_contributions:,}", "orange")
name_str = self._colorize(name, "header")
phrase_str = self._colorize("contributions this year", "header")
user_line = f"{name_str} - {contrib_str} {phrase_str}"
lines.append(user_line)
return lines
def _format_user_info(
self, user_data: Dict[str, Any], stats: Dict[str, Any]
) -> list:
"""
Format user information lines.
Args:
user_data: User profile data
stats: User statistics data
Returns:
List of formatted info strings
"""
lines = []
name = user_data.get("name") or user_data.get("login", "unknown")
total_contributions = stats.get("total_contributions")
if total_contributions is None:
total_contributions = self._calculate_total_contributions(
stats.get("contribution_graph", [])
)
# Format user line with colored segments
contrib_str = self._colorize(f"{total_contributions:,}", "orange")
name_str = self._colorize(name, "header")
phrase_str = self._colorize("contributions this year", "header")
user_line = f"{name_str} - {contrib_str} {phrase_str}"
lines.append(user_line)
plain_line = f"{name} - {total_contributions:,} contributions this year"
lines.append(self._colorize("─" * len(plain_line), "muted"))
def add_line(label: str, value: str) -> None:
if value:
lines.append(f"{self._label(label)} {value}")
bio = user_data.get("bio", "")
if bio:
trimmed_bio = bio.strip().replace("\n", " ")
lines.append(f"{self._label('Bio')} {trimmed_bio[:80]}")
add_line("Company", user_data.get("company"))
add_line("Website", user_data.get("blog"))
# Add stars amount under website
total_stars = stats.get("total_stars")
if total_stars is not None:
add_line("Stars", f"{total_stars} ⭐")
return lines
def _format_overview(self, stats: Dict[str, Any]) -> list:
"""Format overview statistics for left column."""
lines = []
lines.extend(self._section_header("Overview"))
total_repos = stats.get("total_repos", 0)
total_stars = stats.get("total_stars", 0)
total_forks = stats.get("total_forks", 0)
lines.append(self._format_stat_line("Repositories", total_repos))
lines.append(self._format_stat_line("Stars", total_stars))
lines.append(self._format_stat_line("Forks", total_forks))
return lines
def _format_languages(self, stats: Dict[str, Any]) -> list:
"""Format language distribution for right column."""
languages = stats.get("languages", {})
if not languages:
return []
lines = []
lines.extend(self._section_header("Top Languages"))
sorted_langs = sorted(
languages.items(), key=lambda item: item[1], reverse=True
)[:5]
for lang, percentage in sorted_langs:
# Reword 'Jupyter notebook' to 'Jupyter'
if lang.lower() == "jupyter notebook":
lang = "Jupyter"
lines.append(self._format_language_line(lang, percentage))
return lines
def _format_pull_requests(self, stats: Dict[str, Any]) -> list:
"""Format pull request dashboard section."""
pr_data = stats.get("pull_requests") or {}
groups = [
("Awaiting Review", pr_data.get("awaiting_review", {})),
("Your Open PRs", pr_data.get("open", {})),
("Mentions", pr_data.get("mentions", {})),
]
return self._format_dashboard_section("Pull Requests", groups)
def _format_issues(self, stats: Dict[str, Any]) -> list:
"""Format issues dashboard section."""
issue_data = stats.get("issues") or {}
groups = [
("Assigned", issue_data.get("assigned", {})),
("Created (open)", issue_data.get("created", {})),
("Mentions", issue_data.get("mentions", {})),
]
return self._format_dashboard_section("Issues", groups)
def _render_progress_bar(self, percentage: float, width: int = 24) -> str:
"""Render a progress bar for percentage values."""
width = max(width, 1)
capped_percentage = max(0.0, min(percentage, 100.0))
filled = int(round((capped_percentage / 100) * width))
filled = min(filled, width)
empty = width - filled
filled_segment = "▰" * filled
empty_segment = "▱" * empty
if self.enable_color and filled_segment:
filled_segment = self._colorize(filled_segment, "green")
return f"[{filled_segment}{empty_segment}]"
def _render_progress_bar_no_brackets(
self, percentage: float, width: int = 24
) -> str:
"""Render a progress bar without brackets for percentage values."""
width = max(width, 1)
capped_percentage = max(0.0, min(percentage, 100.0))
filled = int(round((capped_percentage / 100) * width))
filled = min(filled, width)
empty = width - filled
filled_segment = "▰" * filled
empty_segment = "▱" * empty
if self.enable_color and filled_segment:
filled_segment = self._colorize(filled_segment, "green")
return f"{filled_segment}{empty_segment}"
def _section_header(self, title: str) -> list:
"""Create a stylized section header."""
heading = title.upper()
underline = "─" * len(heading)
return [self._colorize(heading, "header"), self._colorize(underline, "muted")]
def _label(self, text: str) -> str:
"""Format labels with consistent padding."""
label = f"{text}:"
padded = f"{label:<12}"
if self.enable_color:
return self._colorize(padded, "bold")
return padded
def _format_stat_line(self, label: str, value: Any) -> str:
"""Format a single statistics line."""
return f"{self._label(label)} {value}"
def _format_language_line(self, language: str, percentage: float) -> str:
"""Format language entry with progress bar."""
# Use consistent padding without relying on label() which adds colors
lang_label = f"{language}:"
padded_label = f"{lang_label:<12}"
if self.enable_color:
padded_label = self._colorize(padded_label, "bold")
bar = self._render_progress_bar_no_brackets(percentage)
return f"{padded_label} {bar} {percentage:5.1f}%"
def _format_dashboard_section(self, title: str, groups: list) -> list:
"""Format a dashboard section with grouped items."""
if not groups:
return []
lines = []
lines.extend(self._section_header(title))
label_width = max((len(label) for label, _ in groups), default=0) + 2
for idx, (label, data) in enumerate(groups):
total = (data or {}).get("total_count", 0)
label_text = self._dashboard_label(label, label_width)
lines.append(f"{label_text} {total}")
items = (data or {}).get("items", [])[:3]
if not items:
lines.append(" • None")
else:
for item in items:
lines.append(self._format_dashboard_item(item))
if idx < len(groups) - 1:
pass # Remove empty line between groups
return lines
def _dashboard_label(self, text: str, width: int = 20) -> str:
label = f"{text}:"
padded = f"{label:<{width}}"
if self.enable_color:
return self._colorize(padded, "header")
return padded
def _format_dashboard_item(
self, item: Dict[str, Any], title_width: int = 24, repo_width: int = 16
) -> str:
title = self._truncate_text(item.get("title", ""), title_width)
repo = item.get("repo", "")
repo_part = ""
if repo:
repo_part = f" ({self._truncate_text(repo, repo_width)})"
bullet = f"• {title}{repo_part}"
return f" {bullet}"
def _truncate_text(self, text: str, max_width: int) -> str:
if self._display_width(text) <= max_width:
return text
ellipsis = "…"
truncated = ""
for char in text:
if self._display_width(truncated + char + ellipsis) > max_width:
break
truncated += char
return truncated + ellipsis
def _graph_header(self, username: str, total_contributions: int) -> list:
"""Return standardized header lines for the contribution graph."""
# Header intentionally blank; graph should start with month labels.
return []
def _calculate_max_weeks(self, width_available: int) -> int:
"""Calculate how many weeks fit in available width."""
# Each week is 2 chars wide (■ )
block_width = 2
header_margin = 4
available_for_graph = width_available - header_margin
max_weeks = max(13, available_for_graph // block_width)
return min(52, max_weeks)
def _build_month_line(self, weeks_data: list) -> str:
"""Build a month label line aligned with contribution weeks."""
if not weeks_data:
return ""