Skip to content
Garot Conklin edited this page Jan 28, 2025 · 1 revision

Usage Guide

This guide covers the basic and advanced usage of githubauthlib.

Basic Usage

Retrieving a GitHub Token

The most common use case is retrieving a GitHub token:

from githubauthlib import get_github_token, GitHubAuthError

try:
    token = get_github_token()
    if token:
        print("Token retrieved successfully!")
    else:
        print("No token found in system keychain")
except GitHubAuthError as e:
    print(f"Error retrieving token: {e}")

Error Handling

The library provides specific exceptions for different error cases:

from githubauthlib import (
    get_github_token,
    GitHubAuthError,
    CredentialHelperError,
    UnsupportedPlatformError
)

try:
    token = get_github_token()
except CredentialHelperError as e:
    print(f"Error with credential helper: {e}")
except UnsupportedPlatformError as e:
    print(f"Unsupported operating system: {e}")
except GitHubAuthError as e:
    print(f"General authentication error: {e}")

Advanced Usage

Token Validation

You can validate a token's format:

from githubauthlib.github_auth import validate_token

token = "ghp_1234567890abcdef1234567890abcdef123456"
is_valid = validate_token(token)
print(f"Token is valid: {is_valid}")

Logging Configuration

The library uses Python's built-in logging module:

import logging

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Get token with detailed logging
token = get_github_token()

Integration Examples

Using with GitHub API

from githubauthlib import get_github_token
import requests

def get_github_user():
    token = get_github_token()
    if not token:
        raise ValueError("No GitHub token found")
    
    headers = {'Authorization': f'token {token}'}
    response = requests.get('https://api.github.com/user', headers=headers)
    return response.json()

# Usage
try:
    user_info = get_github_user()
    print(f"Logged in as: {user_info['login']}")
except Exception as e:
    print(f"Error: {e}")

Using with GitHub CLI

import subprocess
from githubauthlib import get_github_token

def run_github_cli_command(command):
    token = get_github_token()
    if not token:
        raise ValueError("No GitHub token found")
    
    env = {'GITHUB_TOKEN': token}
    result = subprocess.run(
        command,
        env=env,
        capture_output=True,
        text=True
    )
    return result.stdout

# Usage
try:
    repos = run_github_cli_command(['gh', 'repo', 'list'])
    print(repos)
except Exception as e:
    print(f"Error: {e}")

Best Practices

  1. Error Handling

    • Always wrap token retrieval in try-except blocks
    • Handle specific exceptions for better error reporting
  2. Token Security

    • Never log or print the actual token
    • Don't store tokens in plain text
    • Use environment variables when needed
  3. Performance

    • Cache the token if making multiple API calls
    • Reuse the token within the same session
  4. Logging

    • Configure logging appropriately for your environment
    • Avoid logging sensitive information

Common Patterns

Token Caching

from functools import lru_cache
from githubauthlib import get_github_token

@lru_cache(maxsize=1)
def get_cached_token():
    return get_github_token()

# Usage
token = get_cached_token()  # First call retrieves token
token = get_cached_token()  # Subsequent calls use cached value

Context Manager

from contextlib import contextmanager
from githubauthlib import get_github_token

@contextmanager
def github_token_context():
    token = get_github_token()
    if not token:
        raise ValueError("No GitHub token found")
    try:
        yield token
    finally:
        # Cleanup if needed
        pass

# Usage
with github_token_context() as token:
    # Use token here
    print("Token is available")

Next Steps