-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcli.py
More file actions
719 lines (608 loc) · 24 KB
/
Copy pathcli.py
File metadata and controls
719 lines (608 loc) · 24 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
"""
Command-line interface for gitfetch
"""
import argparse
import os
import sys
import subprocess
from typing import Optional
import readchar
from .display import DisplayFormatter
from .cache import CacheManager
from .config import ConfigManager
from .providers import ProviderConfig, PROVIDER_ENV_VARS, PROVIDER_DEFAULT_URLS
from . import __version__
def _background_refresh_cache_subprocess(username: str) -> None:
"""
Background cache refresh function that runs as a standalone script.
This is called by the subprocess, not directly.
"""
try:
# Re-create components
config_manager = ConfigManager()
cache_expiry = config_manager.get_cache_expiry_minutes()
cache_manager = CacheManager(cache_expiry_minutes=cache_expiry)
provider_config = config_manager.get_provider_config()
if not provider_config:
exit(1)
if not provider_config.url:
exit(1)
fetcher = _create_fetcher(
provider_config.name, provider_config.url, provider_config.token or None
)
fresh_user_data = fetcher.fetch_user_data(username)
fresh_stats = fetcher.fetch_user_stats(username, fresh_user_data)
cache_manager.cache_user_data(username, fresh_user_data, fresh_stats)
except Exception:
# Silent fail - this is background refresh
pass
def _debug_enabled() -> bool:
"""Return True when debug mode is enabled via env var."""
value = os.environ.get('DEBUG')
if value is None:
# Backward compatibility with older env var name.
value = os.environ.get('GITFETCH_DEBUG')
if value is None:
return False
return value.strip().lower() not in {'', '0', 'false', 'no', 'off'}
def parse_args() -> argparse.Namespace:
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description="""A neofetch-style CLI tool for git.
Supports GitHub, GitLab, Gitea, and Sourcehut.""",
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"username",
nargs="?",
help="Username to fetch stats for"
)
general_group = parser.add_argument_group('\033[92mGeneral Options\033[0m')
general_group.add_argument(
"--no-cache",
action="store_true",
help="Bypass cache and fetch fresh data"
)
general_group.add_argument(
"--clear-cache",
action="store_true",
help="Clear the cache and exit"
)
general_group.add_argument(
"--version",
action="store_true",
help="Show version and check for updates"
)
general_group.add_argument(
"--change-provider",
action="store_true",
help="Change the configured git provider"
)
# Hidden argument for background cache refresh
general_group.add_argument(
"--background-refresh",
type=str,
help=argparse.SUPPRESS # Hide from help
)
general_group.add_argument(
"--local",
action="store_true",
help="Fetch data specific to current local repo (requires .git folder)"
)
visual_group = parser.add_argument_group('\033[94mVisual Options\033[0m')
visual_group.add_argument(
"--spaced",
action="store_true",
help="Enable spaced layout"
)
visual_group.add_argument(
"--not-spaced",
action="store_true",
help="Disable spaced layout"
)
visual_group.add_argument(
"--custom-box",
type=str,
help="Custom character for contribution blocks (e.g., '■', '█')"
)
visual_group.add_argument(
"--graph-only",
action="store_true",
help="Show only the contribution graph"
)
visual_group.add_argument(
"--width",
type=int,
help="Set custom width for contribution graph"
)
visual_group.add_argument(
"--height",
type=int,
help="Set custom height for contribution graph"
)
visual_group.add_argument(
"--text",
type=str,
help="Display text as contribution graph pattern (simulation only)"
)
visual_group.add_argument(
"--shape",
nargs='+',
help=("Display one or more predefined shapes as contribution graph "
"(simulation only). Provide multiple shapes after the option: "
"--shape kitty kitty")
)
visual_group.add_argument(
"--graph-timeline",
action="store_true",
help="Show git timeline graph instead of contribution graph"
)
visibility_group = parser.add_argument_group('\033[95mVisibility\033[0m')
visibility_group.add_argument(
"--no-date",
action="store_true",
help="Hide month/date labels on contribution graph"
)
visibility_group.add_argument(
"--no-achievements",
action="store_true",
help="Hide achievements section"
)
visibility_group.add_argument(
"--no-languages",
action="store_true",
help="Hide languages section"
)
visibility_group.add_argument(
"--no-issues",
action="store_true",
help="Hide issues section"
)
visibility_group.add_argument(
"--no-pr",
action="store_true",
help="Hide pull requests section"
)
visibility_group.add_argument(
"--no-account",
action="store_true",
help="Hide account information section"
)
visibility_group.add_argument(
"--no-grid",
action="store_true",
help="Hide contribution grid/graph"
)
return parser.parse_args()
def main() -> int:
"""Main entry point for gitfetch CLI."""
try:
args = parse_args()
# Check for --local flag (must come before config init)
if args.local:
import os
if not os.path.exists('.git'):
print("Error: --local requires .git folder", file=sys.stderr)
return 1
# Local mode: no config, no remote API — read from .git directly
from .fetcher import BaseFetcher
config_manager = ConfigManager()
formatter = DisplayFormatter(
config_manager,
custom_box=args.custom_box,
show_date=not args.no_date,
graph_only=args.graph_only,
show_achievements=not args.no_achievements,
show_languages=not args.no_languages,
show_issues=not args.no_issues,
show_pr=not args.no_pr,
show_account=not args.no_account,
show_grid=not args.no_grid,
custom_width=args.width,
custom_height=args.height,
graph_timeline=args.graph_timeline,
local_mode=True,
)
spaced = True
if args.spaced:
spaced = True
elif args.not_spaced:
spaced = False
weeks = BaseFetcher._build_contribution_graph_from_git()
if not weeks:
print("No contributions found in local repository.")
return 0
stats = {'contribution_graph': weeks}
repo_name = os.path.basename(os.path.abspath('.'))
user_data = {
'name': repo_name,
'bio': 'local repository',
'website': '',
}
formatter.display(repo_name, user_data, stats, spaced=spaced)
return 0
# Handle background refresh mode (hidden feature)
if args.background_refresh:
_background_refresh_cache_subprocess(args.background_refresh)
return 0
if args.change_provider:
config_manager = ConfigManager()
print("🔄 Changing git provider...\n")
if not _initialize_gitfetch(config_manager):
print("Error: Failed to change provider", file=sys.stderr)
return 1
print("\n✅ Provider changed successfully!")
return 0
if args.version:
print(f"gitfetch version: {__version__}")
# Check for updates from GitHub
import requests
try:
resp = requests.get(
"https://api.github.com/repos/Matars/gitfetch/releases/latest", timeout=3)
if resp.status_code == 200:
latest = resp.json()["tag_name"].lstrip("v")
if latest != __version__:
print(f"\033[93mUpdate available: {latest}\n"
+ "Get it at: https://github.com/Matars/gitfetch/releases/latest\n"
+ "Or update using your package manager:\n"
+ "\t\tbrew update && brew upgrade gitfetch\n"
+ "\t\tpip install --upgrade gitfetch\n"
+ "\t\tpacman -Syu gitfetch-python\n"
+ "\t\tsudo apt update && sudo apt install --only-upgrade gitfetch\033[0m")
else:
print("You are using the latest version.")
else:
print("Could not check for updates.")
except Exception:
print("Could not check for updates.")
return 0
# Initialize config
config_manager = ConfigManager()
# Check if gitfetch is initialized
if not config_manager.is_initialized():
print("🚀 Welcome to gitfetch! Let's set up your configuration.\n")
if not _initialize_gitfetch(config_manager):
print("Error: Initialization failed", file=sys.stderr)
return 1
print("\n✅ Configuration saved! You can now use gitfetch.\n")
# Initialize components
cache_expiry = config_manager.get_cache_expiry_minutes()
cache_manager = CacheManager(cache_expiry_minutes=cache_expiry)
provider_config = config_manager.get_provider_config()
if not provider_config:
print("Provider not set. Run: gitfetch --change-provider")
return 1
if not provider_config.url:
print("Provider URL not set. Run: gitfetch --change-provider")
return 1
fetcher = _create_fetcher(
provider_config.name, provider_config.url, provider_config.token or None
)
# Handle custom box character
custom_box = args.custom_box
# Handle show date setting
show_date = not args.no_date
formatter = DisplayFormatter(
config_manager,
custom_box,
show_date,
args.graph_only,
not args.no_achievements,
not args.no_languages,
not args.no_issues,
not args.no_pr,
not args.no_account,
not args.no_grid,
args.width,
args.height,
args.graph_timeline,
args.local,
args.shape,
args.text,
)
if args.spaced:
spaced = True
elif args.not_spaced:
spaced = False
else:
spaced = True
# If --text or --shape provided, simulate contribution graph
# and reuse cached metadata (issues, PRs, languages, achievements)
if args.text or args.shape:
if args.text and args.shape:
print("Error: --text and --shape cannot be used together",
file=sys.stderr)
return 1
try:
if args.text:
# Build a fake contribution_graph from the text
text_grid = formatter._text_to_grid(args.text)
weeks = formatter._generate_weeks_from_text_grid(text_grid)
else: # args.shape
# Use the predefined shape pattern (shape may be a list)
shape_grid = formatter._shape_to_grid(args.shape)
weeks = formatter._generate_weeks_from_text_grid(
shape_grid)
except Exception as e:
print(f"Error generating graph: {e}", file=sys.stderr)
return 1
# Try to reuse cached user metadata/stats when available
lookup_username = args.username or config_manager.get_default_username()
cached_user = None
cached_stats = None
if lookup_username:
# Prefer fresh cache, but fall back to stale cache so
# simulated graphs can still show metadata like streaks
cached_user = (
cache_manager.get_cached_user_data(lookup_username)
or cache_manager.get_stale_cached_user_data(lookup_username)
)
cached_stats = (
cache_manager.get_cached_stats(lookup_username)
or cache_manager.get_stale_cached_stats(lookup_username)
)
if cached_stats:
# Replace only the contribution graph with our simulated weeks
cached_stats['contribution_graph'] = weeks
stats = cached_stats
else:
stats = {'contribution_graph': weeks}
if cached_user:
user_data = cached_user
display_name = cached_user.get('name') or lookup_username
else:
# Minimal fallback user_data for display purposes
display_name = (
args.username
or (args.text if args.text else ' '.join(args.shape) if args.shape else None)
)
user_data = {
'name': display_name,
'bio': '',
'website': '',
}
if display_name == None:
print("display name not set")
return 1
formatter.display(
display_name,
user_data,
stats,
spaced=spaced,
)
return 0
# Handle cache clearing
if args.clear_cache:
cache_manager.clear()
print("Cache cleared successfully!")
return 0
# Get username
username = (
args.username
or config_manager.get_default_username()
or None
)
if not username:
# Fall back to authenticated user
try:
username = fetcher.get_authenticated_user()
# Save as default for future use
config_manager.set_default_username(username)
config_manager.save()
except Exception:
username = _prompt_username()
if not username:
print("Error: Username is required", file=sys.stderr)
return 1
# Fetch data (with or without cache)
try:
use_cache = not args.no_cache
if use_cache:
user_data = cache_manager.get_cached_user_data(username)
stats = cache_manager.get_cached_stats(username)
# If fresh cache is available, just display
if user_data is not None and stats is not None:
formatter.display(username, user_data,
stats, spaced=spaced)
return 0
# Try stale cache for immediate display
stale_user_data = cache_manager.get_stale_cached_user_data(
username)
stale_stats = cache_manager.get_stale_cached_stats(username)
if stale_user_data is not None and stale_stats is not None:
formatter.display(username, stale_user_data,
stale_stats, spaced=spaced)
# Spawn a completely independent background process
# Spawn background refresh process
try:
subprocess.Popen(
[sys.executable, "-m", "gitfetch.cli",
"--background-refresh", username],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stdin=subprocess.DEVNULL,
start_new_session=True, # detach from parent
)
except Exception:
# If subprocess fails, silently continue
pass
return 0
# No cache at all so fall through to fresh fetch
# Either no_cache or no valid cache so just fetch fresh data
user_data = fetcher.fetch_user_data(username)
stats = fetcher.fetch_user_stats(username, user_data)
cache_manager.cache_user_data(username, user_data, stats)
# Display the results
formatter.display(username, user_data, stats, spaced=spaced)
return 0
except Exception as e:
# When debugging, print full traceback to help diagnose issues
# (useful when users report errors from package builds / other
# environments where the short error message is not enough).
try:
import traceback
if _debug_enabled():
traceback.print_exc()
else:
print(f"Error: {e}", file=sys.stderr)
except Exception:
# Fallback to simple message if traceback printing fails
print(f"Error: {e}", file=sys.stderr)
return 1
except KeyboardInterrupt:
print("\nInterrupted by user.", file=sys.stderr)
return 130
def _prompt_username() -> Optional[str]:
"""Prompt user for username if not provided."""
try:
username = input("Enter username: ").strip()
return username if username else None
except (KeyboardInterrupt, EOFError):
print()
return None
def _prompt_provider() -> Optional[str]:
"""Prompt user for git provider with interactive selection."""
providers = [
('github', 'GitHub'),
('gitlab', 'GitLab'),
('gitea', 'Gitea/Forgejo/Codeberg'),
('sourcehut', 'Sourcehut')
]
selected = 0
try:
while True:
# Clear screen and print header
print("\033[2J\033[H", end="")
print("Choose your git provider:")
print()
# Print options with cursor
for i, (key, name) in enumerate(providers):
indicator = "●" if i == selected else "○"
print(f"{indicator} {name}")
print()
print("Use ↑/↓ or j/k to navigate, Enter to confirm")
# Read key
key = readchar.readkey()
if key == readchar.key.UP or key == 'k':
selected = (selected - 1) % len(providers)
elif key == readchar.key.DOWN or key == 'j':
selected = (selected + 1) % len(providers)
elif key == readchar.key.ENTER:
print() # New line after selection
return providers[selected][0]
except (KeyboardInterrupt, EOFError):
print()
return None
def _create_fetcher(provider: str, base_url: str, token: Optional[str] = None):
"""Create the appropriate fetcher for the provider."""
if provider == 'github':
from .fetcher import GitHubFetcher
return GitHubFetcher(token)
elif provider == 'gitlab':
from .fetcher import GitLabFetcher
return GitLabFetcher(base_url, token)
elif provider == 'gitea':
from .fetcher import GiteaFetcher
return GiteaFetcher(base_url, token)
elif provider == 'sourcehut':
from .fetcher import SourcehutFetcher
return SourcehutFetcher(base_url, token)
else:
raise ValueError(f"Unsupported provider: {provider}")
def _initialize_gitfetch(config_manager: ConfigManager) -> bool:
"""
Initialize gitfetch by creating config directory and setting
multiple configuration options.
Args:
config_manager: ConfigManager instance
Returns:
True if initialization succeeded, False otherwise
"""
try:
# Ask user for git provider
provider = _prompt_provider()
if not provider:
return False
# Determine URL for provider
if provider == 'github':
url = PROVIDER_DEFAULT_URLS.get('github', 'https://api.github.com')
elif provider == 'gitlab':
url = PROVIDER_DEFAULT_URLS.get('gitlab', 'https://gitlab.com')
elif provider == 'gitea':
url = input("Enter Gitea/Forgejo/Codeberg URL: ").strip()
if not url:
print("Provider URL required", file=sys.stderr)
return False
elif provider == 'sourcehut':
url = PROVIDER_DEFAULT_URLS.get('sourcehut', 'https://git.sr.ht')
else:
print(f"Unsupported provider: {provider}", file=sys.stderr)
return False
# Ask for token (optional - only for extra rate limits)
token = ''
env_var = PROVIDER_ENV_VARS.get(provider, '')
# Make it clear CLI is required, token is optional for rate limits
if provider in ['github', 'gitlab']:
cli_name = 'gh' if provider == 'github' else 'glab'
print(f"\nNote: {cli_name} CLI is required for authentication.")
print(f"Token is optional but increases rate limits.\n")
token_msg = f"Enter your {provider} personal access token"
token_msg += f"\n(optional - for higher rate limits, press Enter to skip"
if env_var:
token_msg += f", or set {env_var} env var"
token_msg += "): "
token_input = input(token_msg).strip()
if token_input:
token = token_input
# Create provider config
provider_config = ProviderConfig(
name=provider,
username='', # Will be set after fetcher auth
url=url,
token=token
)
# Create fetcher to get authenticated user
fetcher = _create_fetcher(provider, url, token or None)
# Try to get authenticated user
try:
username = fetcher.get_authenticated_user()
# Show auth status with token info
token_status = "with token" if token else "without token (limited rate)"
print(f"✓ Authenticated as: {username} ({token_status})")
provider_config.username = username
except Exception as e:
print(f"Could not get authenticated user: {e}")
if provider == 'github':
print("Please install gh CLI and run: gh auth login")
elif provider == 'gitlab':
print("Please install glab CLI and run: glab auth login")
else:
print("Please ensure you have a valid token configured")
return False
# Ask for cache expiry time
cache_expiry_input = input(
"Cache expiry in minutes (default: 15, Enter for default): "
).strip()
if cache_expiry_input:
try:
cache_expiry = int(cache_expiry_input)
if cache_expiry < 1:
print("Cache expiry must be >= 1 min. Using default: 15")
cache_expiry = 15
config_manager.set_cache_expiry_minutes(cache_expiry)
except ValueError:
print("Invalid input. Using default: 15 minutes.")
config_manager.set_cache_expiry_minutes(15)
else:
config_manager.set_cache_expiry_minutes(15)
# Save configuration using new provider config system
config_manager.set_provider_config(provider_config)
config_manager.set_default_username(username)
config_manager.save()
return True
except Exception as e:
print(f"Error during initialization: {e}", file=sys.stderr)
return False
if __name__ == "__main__":
sys.exit(main())