Powerful CLI tool for analyzing GitHub repository statistics and trends
Outil CLI puissant pour analyser les statistiques et tendances des dépôts GitHub
Quick Start • Documentation • Examples • Contributing • License
GitHub Repository Analyzer is a production-ready command-line tool that extracts comprehensive statistics from GitHub repositories using the official GitHub API v3. Born from the need to quickly assess repository health, activity patterns, and community engagement, this tool transforms raw API data into actionable insights.
The Problem: Developers, open-source maintainers, and project managers need quick visibility into repository metrics—stars, forks, contributor activity, issue trends—without manually navigating GitHub's web interface or writing custom API scripts. Existing solutions are either outdated, lack flexibility in output formats, or require complex setup.
The Solution: A zero-configuration CLI tool that authenticates via GitHub tokens, fetches real-time statistics, and exports data in JSON or CSV formats. Built with modern Python practices (type hints, async support, comprehensive testing), it handles rate limiting gracefully and supports both public and private repositories.
Key Benefits:
- ⚡ Instant insights: Single command to fetch stars, forks, contributors, and activity trends
- 📊 Flexible output: Export to JSON for programmatic processing or CSV for spreadsheets
- 🔒 Secure authentication: Uses GitHub personal access tokens with automatic rate limit handling
- 🧪 Battle-tested: Full pytest coverage with pre-commit hooks ensuring code quality
- 🌍 Bilingual documentation: Complete EN/FR support for international developers
Target Audience: Solo developers tracking their projects, open-source maintainers analyzing community engagement, DevOps teams monitoring repository health metrics, and project managers requiring periodic statistics reports.
GitHub Repository Analyzer est un outil en ligne de commande prêt pour la production qui extrait des statistiques complètes des dépôts GitHub en utilisant l'API officielle GitHub v3. Né du besoin d'évaluer rapidement la santé d'un dépôt, les patterns d'activité et l'engagement de la communauté, cet outil transforme les données brutes de l'API en insights actionnables.
Le Problème : Les développeurs, mainteneurs open-source et chefs de projet ont besoin d'une visibilité rapide sur les métriques de dépôt—étoiles, forks, activité des contributeurs, tendances des issues—sans naviguer manuellement dans l'interface web de GitHub ni écrire des scripts API personnalisés. Les solutions existantes sont soit obsolètes, manquent de flexibilité dans les formats de sortie, ou nécessitent une configuration complexe.
La Solution : Un outil CLI sans configuration qui s'authentifie via des tokens GitHub, récupère les statistiques en temps réel et exporte les données aux formats JSON ou CSV. Construit avec les pratiques Python modernes (type hints, support async, tests complets), il gère gracieusement les limites de taux et supporte les dépôts publics et privés.
Bénéfices Clés :
- ⚡ Insights instantanés : Une seule commande pour récupérer étoiles, forks, contributeurs et tendances d'activité
- 📊 Sortie flexible : Export en JSON pour traitement programmatique ou CSV pour tableurs
- 🔒 Authentification sécurisée : Utilise les tokens d'accès personnels GitHub avec gestion automatique des limites de taux
- 🧪 Testé au combat : Couverture pytest complète avec hooks pre-commit assurant la qualité du code
- 🌍 Documentation bilingue : Support complet EN/FR pour les développeurs internationaux
Public Cible : Développeurs solo suivant leurs projets, mainteneurs open-source analysant l'engagement communautaire, équipes DevOps surveillant les métriques de santé des dépôts, et chefs de projet nécessitant des rapports statistiques périodiques.
-
🎯 Comprehensive Metrics: Fetch stars, forks, watchers, open/closed issues, pull requests, and contributor counts with a single command. Example:
gh-stats valorisa/my-reporeturns all metrics in under 2 seconds. -
⚡ Activity Trends: Analyze commit frequency, issue resolution time, and contributor activity over custom time periods (7d, 30d, 90d, 1y). Perfect for monthly reports or identifying development velocity changes.
-
📊 Multiple Export Formats: Output to JSON for integration with CI/CD pipelines or CSV for importing into Excel/Google Sheets. Both formats preserve full type information and include timestamps.
-
🔒 Secure Token Management: Store GitHub tokens in environment variables or
.envfiles. Supports fine-grained personal access tokens with automatic expiry warnings and rate limit headers. -
🌐 Rate Limit Awareness: Automatically detects and respects GitHub's API rate limits (5000 req/hour for authenticated users). Includes a
--dry-runmode to preview requests without consuming quota. -
🧪 100% Test Coverage: Full pytest suite with unit and integration tests. Pre-commit hooks run ruff linting, type checking (mypy), and security audits (bandit) automatically.
-
🚀 Zero Configuration: Works out-of-the-box with minimal setup. Optional configuration file (
~/.github-stats.yaml) for power users wanting custom defaults. -
📦 Batch Processing: Analyze multiple repositories in a single run. Example:
gh-stats --repos repos.txt --format csv --output stats.csvprocesses 50+ repos in minutes.
-
🎯 Métriques Complètes : Récupère étoiles, forks, watchers, issues ouvertes/fermées, pull requests et nombre de contributeurs avec une seule commande. Exemple :
gh-stats valorisa/my-reporetourne toutes les métriques en moins de 2 secondes. -
⚡ Tendances d'Activité : Analyse la fréquence des commits, le temps de résolution des issues et l'activité des contributeurs sur des périodes personnalisées (7j, 30j, 90j, 1an). Parfait pour les rapports mensuels ou identifier les changements de vélocité de développement.
-
📊 Formats d'Export Multiples : Sortie en JSON pour intégration avec pipelines CI/CD ou CSV pour import dans Excel/Google Sheets. Les deux formats préservent l'information de type complète et incluent les timestamps.
-
🔒 Gestion Sécurisée des Tokens : Stocke les tokens GitHub dans les variables d'environnement ou fichiers
.env. Supporte les tokens d'accès personnels fine-grained avec avertissements d'expiration automatiques et headers de limites de taux. -
🌐 Conscience des Limites de Taux : Détecte et respecte automatiquement les limites de taux de l'API GitHub (5000 req/heure pour utilisateurs authentifiés). Inclut un mode
--dry-runpour prévisualiser les requêtes sans consommer le quota. -
🧪 Couverture de Tests 100% : Suite pytest complète avec tests unitaires et d'intégration. Les hooks pre-commit exécutent le linting ruff, vérification de types (mypy) et audits de sécurité (bandit) automatiquement.
-
🚀 Configuration Zéro : Fonctionne out-of-the-box avec configuration minimale. Fichier de configuration optionnel (
~/.github-stats.yaml) pour power users voulant des défauts personnalisés. -
📦 Traitement par Lots : Analyse plusieurs dépôts en une seule exécution. Exemple :
gh-stats --repos repos.txt --format csv --output stats.csvtraite plus de 50 dépôts en minutes.
- Python 3.10+ (tested on 3.10, 3.11, 3.12)
- Git 2.30+ (for cloning the repository)
- GitHub Personal Access Token (classic or fine-grained with
reposcope for private repos, no scope needed for public repos) - pip 23.0+ (for dependency installation)
# Clone the repository
git clone https://github.com/valorisa/github-repository-analyzer.git
cd github-repository-analyzer
# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Install in development mode
pip install -e .
# Set up your GitHub token
export GITHUB_TOKEN="ghp_your_token_here"
# Verify installation
gh-stats --version# Analyze a single repository
gh-stats octocat/Hello-World
# Export to JSON
gh-stats octocat/Hello-World --format json --output hello-world-stats.json
# Analyze with activity trends (last 30 days)
gh-stats octocat/Hello-World --trends 30d
# Batch analyze multiple repositories
echo "octocat/Hello-World" > repos.txt
echo "torvalds/linux" >> repos.txt
gh-stats --repos repos.txt --format csv --output batch-stats.csvTip
Pro tip: Use fine-grained personal access tokens with read-only metadata and contents permissions for enhanced security. They expire automatically and reduce risk if leaked.
- Python 3.10+ (testé sur 3.10, 3.11, 3.12)
- Git 2.30+ (pour cloner le dépôt)
- Token d'Accès Personnel GitHub (classique ou fine-grained avec scope
repopour dépôts privés, aucun scope nécessaire pour dépôts publics) - pip 23.0+ (pour installation des dépendances)
# Cloner le dépôt
git clone https://github.com/valorisa/github-repository-analyzer.git
cd github-repository-analyzer
# Créer l'environnement virtuel
python3 -m venv .venv
source .venv/bin/activate # Sur Windows : .venv\Scripts\activate
# Installer les dépendances
pip install -r requirements.txt
# Installer en mode développement
pip install -e .
# Configurer votre token GitHub
export GITHUB_TOKEN="ghp_votre_token_ici"
# Vérifier l'installation
gh-stats --version# Analyser un seul dépôt
gh-stats octocat/Hello-World
# Exporter en JSON
gh-stats octocat/Hello-World --format json --output hello-world-stats.json
# Analyser avec tendances d'activité (30 derniers jours)
gh-stats octocat/Hello-World --trends 30d
# Analyser par lots plusieurs dépôts
echo "octocat/Hello-World" > repos.txt
echo "torvalds/linux" >> repos.txt
gh-stats --repos repos.txt --format csv --output batch-stats.csv[!CONSEIL] Astuce pro : Utilisez des tokens d'accès personnels fine-grained avec permissions lecture seule
metadataetcontentspour sécurité renforcée. Ils expirent automatiquement et réduisent le risque en cas de fuite.
flowchart TD
A[CLI Entry Point] --> B{Authentication}
B -->|Token Valid| C[GitHub API Client]
B -->|No Token| D[Error: Token Required]
C --> E[Rate Limit Check]
E -->|Within Limits| F[Fetch Repository Data]
E -->|Exceeded| G[Wait/Retry Logic]
F --> H[Parse Metrics]
H --> I{Output Format}
I -->|JSON| J[JSON Serializer]
I -->|CSV| K[CSV Writer]
J --> L[Write to File/Stdout]
K --> L
style B fill:#fff3cd
style E fill:#d1ecf1
style H fill:#d4edda
style L fill:#f8d7da
The tool supports three configuration methods (in order of precedence):
- Command-line arguments (highest priority)
- Environment variables (
GITHUB_TOKEN,GITHUB_API_URL) - Configuration file (
~/.github-stats.yaml)
Example ~/.github-stats.yaml:
github:
token: ghp_your_token_here
api_url: https://api.github.com # Override for GitHub Enterprise
defaults:
format: json
output_dir: ~/github-stats-reports
trend_period: 30d
rate_limit:
respect_limits: true
retry_on_exceed: true
max_retries: 3gh-stats [REPO] [OPTIONS]
Arguments:
REPO Repository in format 'owner/repo'
Options:
--format FORMAT Output format: json, csv (default: json)
--output FILE Output file path (default: stdout)
--trends PERIOD Analyze activity trends: 7d, 30d, 90d, 1y
--repos FILE Batch process repositories from file
--token TOKEN GitHub personal access token
--dry-run Preview API requests without execution
--verbose, -v Enable verbose logging
--version Show version and exit
--help Show this message and exit
Error: "API rate limit exceeded"
- Cause: You've hit GitHub's 5000 requests/hour limit for authenticated users (60/hour for unauthenticated)
- Solution: Wait for the rate limit reset time (check
X-RateLimit-Resetheader in verbose mode) or use--dry-runto preview requests without consuming quota - Prevention: Use
--reposwith smaller batches or increase time between requests
Error: "Authentication failed (401)"
- Cause: Invalid or expired GitHub token
- Solution: Generate a new personal access token at https://github.com/settings/tokens with appropriate scopes (
repofor private repos, no scope for public) - Check: Verify token is correctly set in environment:
echo $GITHUB_TOKEN
Error: "Repository not found (404)"
- Cause: Repository doesn't exist, is private and token lacks permissions, or typo in repo name
- Solution: Verify repository exists on GitHub, check token has
reposcope for private repos, ensure format isowner/repo - Debug: Use
--verboseflag to see full API response
Performance: Slow batch processing
- Cause: Sequential API requests for large repository lists
- Solution: Split large files into smaller batches (50-100 repos per file), use
--format csvwhich has lower serialization overhead - Optimization: Run multiple instances in parallel with different token quotas
Import Error: "Module not found"
- Cause: Virtual environment not activated or dependencies not installed
- Solution: Activate venv (
source .venv/bin/activate), reinstall dependencies (pip install -r requirements.txt) - Verify: Run
which python(should point to.venv/bin/python)
# Clone and enter directory
git clone https://github.com/valorisa/github-repository-analyzer.git
cd github-repository-analyzer
# Create virtual environment
make venv
# Activate virtual environment
source .venv/bin/activate
# Install all dependencies (including dev dependencies)
make install-dev
# Install pre-commit hooks
pre-commit install# Run all tests with coverage
make test
# Run specific test file
pytest tests/test_cli.py -v
# Run with coverage report
make coverage
# Run linting
make lint
# Run type checking
make typecheck- Linting: ruff with
pyproject.tomlconfiguration - Type Checking: mypy with strict mode enabled
- Security: bandit for security issue detection
- Formatting: ruff format (Black-compatible)
- Commit Messages: Conventional Commits (enforced by pre-commit)
# Cloner et entrer dans le répertoire
git clone https://github.com/valorisa/github-repository-analyzer.git
cd github-repository-analyzer
# Créer l'environnement virtuel
make venv
# Activer l'environnement virtuel
source .venv/bin/activate
# Installer toutes les dépendances (y compris dépendances dev)
make install-dev
# Installer les hooks pre-commit
pre-commit install# Exécuter tous les tests avec couverture
make test
# Exécuter un fichier de test spécifique
pytest tests/test_cli.py -v
# Exécuter avec rapport de couverture
make coverage
# Exécuter le linting
make lint
# Exécuter la vérification de types
make typecheck- Linting : ruff avec configuration
pyproject.toml - Vérification de Types : mypy avec mode strict activé
- Sécurité : bandit pour détection de problèmes de sécurité
- Formatage : ruff format (compatible Black)
- Messages de Commit : Conventional Commits (appliqué par pre-commit)
The project maintains 100% test coverage with pytest. Tests are organized into:
- Unit tests:
tests/test_cli.py,tests/test_api.py- Fast, isolated component tests - Integration tests:
tests/test_integration.py- End-to-end workflows with mock API - Fixtures:
tests/conftest.py- Shared test data and mock responses
Running specific test categories:
# Unit tests only
pytest tests/test_cli.py tests/test_api.py
# Integration tests
pytest tests/test_integration.py
# Tests with specific marker
pytest -m "not slow"Le projet maintient une couverture de tests de 100% avec pytest. Les tests sont organisés en :
- Tests unitaires :
tests/test_cli.py,tests/test_api.py- Tests de composants rapides et isolés - Tests d'intégration :
tests/test_integration.py- Workflows end-to-end avec API mock - Fixtures :
tests/conftest.py- Données de test partagées et réponses mock
Exécuter des catégories spécifiques de tests :
# Tests unitaires seulement
pytest tests/test_cli.py tests/test_api.py
# Tests d'intégration
pytest tests/test_integration.py
# Tests avec marqueur spécifique
pytest -m "not slow"# Build distribution packages
python -m build
# Upload to Test PyPI (optional)
python -m twine upload --repository testpypi dist/*
# Upload to PyPI
python -m twine upload dist/*# Build Docker image
docker build -t github-stats:latest .
# Run container with token
docker run -e GITHUB_TOKEN=$GITHUB_TOKEN github-stats:latest octocat/Hello-World# Construire les packages de distribution
python -m build
# Uploader vers Test PyPI (optionnel)
python -m twine upload --repository testpypi dist/*
# Uploader vers PyPI
python -m twine upload dist/*# Construire l'image Docker
docker build -t github-stats:latest .
# Exécuter le container avec token
docker run -e GITHUB_TOKEN=$GITHUB_TOKEN github-stats:latest octocat/Hello-WorldContributions are welcome! Please read CONTRIBUTING.md for details on our code of conduct and the process for submitting pull requests.
Quick Contribution Guide:
- Fork the repository
- Create your feature branch (
git checkout -b feat/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feat/amazing-feature) - Open a Pull Request
Les contributions sont les bienvenues ! Veuillez lire CONTRIBUTING.md pour les détails sur notre code de conduite et le processus de soumission des pull requests.
Guide de Contribution Rapide :
- Forker le dépôt
- Créer votre branche de fonctionnalité (
git checkout -b feat/fonctionnalite-incroyable) - Committer vos changements (
git commit -m 'feat: ajouter fonctionnalite incroyable') - Pousser vers la branche (
git push origin feat/fonctionnalite-incroyable) - Ouvrir une Pull Request
See CHANGELOG.md for a detailed history of changes.
Voir CHANGELOG.md pour un historique détaillé des changements.
See SECURITY.md for our security policy and how to report vulnerabilities.
Voir SECURITY.md pour notre politique de sécurité et comment signaler des vulnérabilités.
This project is licensed under the MIT License - see the LICENSE file for details.
Ce projet est sous licence MIT - voir le fichier LICENSE pour les détails.
Maintainer / Mainteneur: valorisa
Contributors / Contributeurs: See GitHub contributors page
Q: Do I need a GitHub token for public repositories?
A: No, but you're limited to 60 requests/hour without authentication. With a token, you get 5000 requests/hour.
Q: Can I analyze private repositories?
A: Yes, generate a personal access token with repo scope at https://github.com/settings/tokens
Q: Does this work with GitHub Enterprise?
A: Yes, set GITHUB_API_URL environment variable to your GHE instance URL (e.g., https://github.company.com/api/v3)
Q: How do I handle rate limits in CI/CD pipelines?
A: Use multiple tokens with different quotas, or cache results with --output and reuse them within the same hour.
Q: Can I contribute new metrics?
A: Absolutely! Open an issue describing the metric, then submit a PR. See CONTRIBUTING.md for guidelines.
Q : Ai-je besoin d'un token GitHub pour les dépôts publics ?
R : Non, mais vous êtes limité à 60 requêtes/heure sans authentification. Avec un token, vous obtenez 5000 requêtes/heure.
Q : Puis-je analyser des dépôts privés ?
R : Oui, générez un token d'accès personnel avec scope repo sur https://github.com/settings/tokens
Q : Cela fonctionne-t-il avec GitHub Enterprise ?
R : Oui, définissez la variable d'environnement GITHUB_API_URL vers l'URL de votre instance GHE (ex : https://github.company.com/api/v3)
Q : Comment gérer les limites de taux dans les pipelines CI/CD ?
R : Utilisez plusieurs tokens avec différents quotas, ou mettez en cache les résultats avec --output et réutilisez-les dans la même heure.
Q : Puis-je contribuer de nouvelles métriques ?
R : Absolument ! Ouvrez une issue décrivant la métrique, puis soumettez une PR. Voir CONTRIBUTING.md pour les directives.
Made with ❤️ by the open-source community
About Section Data (for GitHub repository settings):
- Description: Powerful CLI tool for analyzing GitHub repository statistics (stars, forks, contributors, trends) using GitHub API v3. Export to JSON/CSV with zero config.
- Website: https://github.com/valorisa/github-repository-analyzer#readme
- Topics: python, cli, github-api, repository-stats, analytics, github-statistics, python3, pytest, data-analysis, csv-export, json-export, github-metrics, contributor-stats, repository-analysis, open-source-tool, developer-tools, api-client, rate-limiting, batch-processing, pre-commit-hooks