Skip to content

Commit 7f54be8

Browse files
committed
better gh interactivty
1 parent ef67fb6 commit 7f54be8

File tree

2 files changed

+51
-19
lines changed

2 files changed

+51
-19
lines changed

src/gitfetch/cli.py

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def parse_args() -> argparse.Namespace:
4949
action="store_true",
5050
help="Enable spaced layout"
5151
)
52-
52+
5353
parser.add_argument(
5454
"--not-spaced",
5555
action="store_true",
@@ -126,10 +126,17 @@ def main() -> int:
126126
# Try to get default username from config
127127
username = config_manager.get_default_username()
128128
if not username:
129-
username = _prompt_username()
130-
if not username:
131-
print("Error: Username is required", file=sys.stderr)
132-
return 1
129+
# Fall back to authenticated user
130+
try:
131+
username = fetcher.get_authenticated_user()
132+
# Save as default for future use
133+
config_manager.set_default_username(username)
134+
config_manager.save()
135+
except Exception:
136+
username = _prompt_username()
137+
if not username:
138+
print("Error: Username is required", file=sys.stderr)
139+
return 1
133140

134141
# Fetch data (with or without cache)
135142
try:
@@ -147,7 +154,8 @@ def main() -> int:
147154
stale_stats = cache_manager.get_stale_cached_stats(username)
148155
if stale_user_data is not None and stale_stats is not None:
149156
# Display stale cache immediately
150-
formatter.display(username, stale_user_data, stale_stats, spaced=spaced)
157+
formatter.display(username, stale_user_data,
158+
stale_stats, spaced=spaced)
151159
print("\n🔄 Refreshing data in background...",
152160
file=sys.stderr)
153161

@@ -195,8 +203,8 @@ def _prompt_username() -> Optional[str]:
195203

196204
def _initialize_gitfetch(config_manager: ConfigManager) -> bool:
197205
"""
198-
Initialize gitfetch by creating config directory and asking for
199-
default username.
206+
Initialize gitfetch by creating config directory and setting
207+
the authenticated user as default.
200208
201209
Args:
202210
config_manager: ConfigManager instance
@@ -205,14 +213,14 @@ def _initialize_gitfetch(config_manager: ConfigManager) -> bool:
205213
True if initialization succeeded, False otherwise
206214
"""
207215
try:
208-
# Prompt for default username
209-
print("Please enter your default GitHub username.")
210-
print("(You can override this later by passing a username as "
211-
"an argument)")
212-
username = input("\nGitHub username: ").strip()
213-
214-
if not username:
215-
print("Error: Username cannot be empty", file=sys.stderr)
216+
# Try to get authenticated user from GitHub CLI
217+
fetcher = GitHubFetcher()
218+
try:
219+
username = fetcher.get_authenticated_user()
220+
print(f"Using authenticated GitHub user: {username}")
221+
except Exception as e:
222+
print(f"Could not get authenticated user: {e}")
223+
print("Please ensure GitHub CLI is authenticated with: gh auth login")
216224
return False
217225

218226
# Save configuration
@@ -221,9 +229,6 @@ def _initialize_gitfetch(config_manager: ConfigManager) -> bool:
221229

222230
return True
223231

224-
except (KeyboardInterrupt, EOFError):
225-
print("\nInitialization cancelled.")
226-
return False
227232
except Exception as e:
228233
print(f"Error during initialization: {e}", file=sys.stderr)
229234
return False

src/gitfetch/fetcher.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,33 @@ def _check_gh_cli(self) -> None:
4747
print("Error: gh CLI command timed out", file=sys.stderr)
4848
sys.exit(1)
4949

50+
def get_authenticated_user(self) -> str:
51+
"""
52+
Get the authenticated GitHub username.
53+
54+
Returns:
55+
The login of the authenticated user
56+
"""
57+
try:
58+
result = subprocess.run(
59+
['gh', 'auth', 'status', '--json', 'hosts'],
60+
capture_output=True,
61+
text=True,
62+
timeout=5
63+
)
64+
if result.returncode != 0:
65+
raise Exception("Failed to get auth status")
66+
67+
data = json.loads(result.stdout)
68+
hosts = data.get('hosts', {})
69+
github_com = hosts.get('github.com', [])
70+
if github_com and len(github_com) > 0:
71+
return github_com[0]['login']
72+
else:
73+
raise Exception("No GitHub.com auth found")
74+
except (subprocess.TimeoutExpired, json.JSONDecodeError, KeyError):
75+
raise Exception("Could not determine authenticated user")
76+
5077
def _gh_api(self, endpoint: str, method: str = "GET") -> Any:
5178
"""
5279
Call GitHub API using gh CLI.

0 commit comments

Comments
 (0)