GitHubリポジトリ群の標準化を可視化・管理するツール
cat_repo_auditor.config.load_config による audit_config.toml の自動生成と読み込みpython -m cat_repo_auditor --user <name> でGitHubユーザーのリポジトリを監査(指定ファイルが存在するかを一覧表示)python -m pip install -r requirements.txt pytestpytest設定ファイル生成を確認(任意):
PYTHONPATH=src python - <<'PY'
from cat_repo_auditor.config import load_config
print(load_config()) # audit_config.toml が無ければ自動生成
PY
簡易監査を実行(ネットワークに接続し、必要に応じて GITHUB_TOKEN を設定):
python -m cat_repo_auditor --user <github-username> --limit 5
# カレントディレクトリの audit_config.toml を使用
※ 本READMEの以降のセクション(特徴、使い方、アーキテクチャなど)は将来的な構想メモです。現状の実装は上記の設定ローダーのみです。
cat-repo-auditorは、GitHubユーザーの複数リポジトリを監査し、標準化されたファイル構成の遵守状況を可視化するツールです。
# リポジトリをクローン
git clone https://github.com/YOUR_USERNAME/cat-repo-auditor.git
cd cat-repo-auditor
# 依存関係をインストール
pip install -r requirements.txt
# GitHub Personal Access Tokenを設定(推奨)
export GITHUB_TOKEN=your_github_token_here
python repo_auditor.py
または起動スクリプトを使用:
./start.sh
audit_config.tomlが存在しない場合、デフォルト設定で自動生成┌─────────────────────────────────────────────────────────────┐
│ Repository │ README │ AGENTS │ .gitignore │ Updated │
├─────────────────────────────────────────────────────────────┤
│ latest-project │ ✓ │ ✓ │ ✓ │ 2025-02 │ ← 最新(青色背景)
│ older-project-1 │ ✓ │ ✗ │ ✓ │ 2025-01 │ ← 欠落あり(赤色背景)
│ older-project-2 │ ✓ │ ✓ │ ✓ │ 2024-12 │
└─────────────────────────────────────────────────────────────┘
audit_config.tomlを編集することで、チェック項目や表示設定をカスタマイズできます:
# チェックするファイル/ディレクトリのリスト
check_items = [
"README.md",
"LICENSE",
".gitignore",
"CONTRIBUTING.md",
".github/workflows/ci.yml",
"pyproject.toml",
"Dockerfile",
]
# 表示設定
[display]
show_repo_name = true # リポジトリ名を表示
show_updated_at = true # 更新日時を表示
highlight_missing = true # 欠落項目を赤色で強調
設定ファイルを保存すると、アプリケーションを再起動せずに自動的に反映されます。
cat-repo-auditor/
├── repo_auditor.py # メインアプリケーション
├── audit_config.toml # 設定ファイル
├── requirements.txt # Python依存関係
├── start.sh # 起動スクリプト
├── .cache/ # キャッシュディレクトリ(自動生成)
│ ├── repos.json # リポジトリ一覧キャッシュ
│ └── <repo_name>.json # 個別リポジトリのチェック結果
├── README.md # 英語版README
├── README.ja.md # 日本語版README(このファイル)
└── LICENSE # MITライセンス
GitHubリポジトリの取得と監査を担当。
主要メソッド:
fetch_repositories(count: int) - 指定ユーザーの直近リポジトリを取得fetch_repo_details(repo_name: str, check_items: List[str]) - 個別リポジトリのファイル存在確認キャッシュ戦略:
TOMLファイルの変更を監視し、ホットリロードを実現。
動作原理:
Tkinterベースのグラフィカルユーザーインターフェース。
主要機能:
[GitHub API]
↓
[RepoAuditor] ←→ [キャッシュ]
↓
[RepoAuditorGUI]
↓
[ユーザー]
↓
[audit_config.toml] → [ConfigWatcher] → [ホットリロード]
このセクションは、GitHub Copilot、Cursor、Windsurf、ClaudeなどのCoding Agentが本プロジェクトをゼロから実装する際のガイドラインです。
mkdir cat-repo-auditor
cd cat-repo-auditor
touch repo_auditor.py audit_config.toml requirements.txt
requests>=2.31.0
# Note: tomllib is built into Python 3.11+
# For Python 3.10, install: tomli>=2.0.0
# デフォルト設定の例
check_items = [
"README.md",
".gitignore",
"LICENSE",
]
[display]
show_repo_name = true
show_updated_at = true
highlight_missing = true
以下の順序で実装を進めてください:
#!/usr/bin/env python3
import tkinter as tk
from tkinter import ttk
import threading
import json
import os
from pathlib import Path
from datetime import datetime
import requests
from typing import Dict, List, Any
import time
# Python 3.11+ uses tomllib, 3.10 uses tomli
try:
import tomllib
except ImportError:
try:
import tomli as tomllib
except ImportError:
tomllib = None # Fallback to manual parsing
必須メソッド:
__init__(self, username: str, cache_dir: str) - 初期化_get_headers(self) - GitHub API用ヘッダー生成fetch_repositories(self, count: int) - リポジトリ一覧取得fetch_repo_details(self, repo_name: str, check_items: List[str]) - ファイル存在確認キャッシュ実装の注意点:
repos.json: リポジトリ一覧を1時間キャッシュ<repo_name>.json: 個別リポジトリの結果を永続キャッシュGitHub API エンドポイント:
GET /users/{username}/repos?sort=updated&per_page={count}GET /repos/{username}/{repo}/contents/{filepath}レート制限対策:
GITHUB_TOKENからPersonal Access Tokenを取得必須メソッド:
__init__(self, config_path: str, callback) - 初期化start(self) - 監視開始stop(self) - 監視停止_watch(self) - ファイル変更監視ループ実装のポイント:
os.stat().st_mtimeでファイル更新時刻を確認必須メソッド:
__init__(self, root) - GUI初期化_create_widgets(self) - ウィジェット作成_load_config(self) - TOML設定読み込み_update_tree_columns(self) - Treeview列の動的更新_fetch_repos(self) - リポジトリ取得(非同期)_update_display(self) - 表示更新_update_status(self, message: str) - ステータスバー更新GUI実装の注意点:
columns = ["repo"] + check_items + ["updated"]
self.tree["columns"] = columns
self.tree["show"] = "headings" # ツリーアイコンを非表示
def _fetch_repos(self):
def fetch():
# GitHub APIを呼び出す
self.repos = self.auditor.fetch_repositories(20)
# メインスレッドで表示更新
self.root.after(0, self._update_display)
threading.Thread(target=fetch, daemon=True).start()
self.tree.tag_configure("latest", background="#e3f2fd") # 青色
self.tree.tag_configure("missing", background="#ffebee") # 赤色
def main():
root = tk.Tk()
app = RepoAuditorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
各クラスの主要メソッドをテスト:
# test_repo_auditor.py
import unittest
from repo_auditor import RepoAuditor, ConfigWatcher
class TestRepoAuditor(unittest.TestCase):
def setUp(self):
self.auditor = RepoAuditor("testuser", ".cache_test")
def test_fetch_repositories_with_cache(self):
# キャッシュが正しく動作するかテスト
repos1 = self.auditor.fetch_repositories(5)
repos2 = self.auditor.fetch_repositories(5)
self.assertEqual(repos1, repos2)
def test_fetch_repo_details_incremental(self):
# 差分取得が正しく動作するかテスト
details1 = self.auditor.fetch_repo_details("test-repo", ["README.md"])
details2 = self.auditor.fetch_repo_details("test-repo",
["README.md", "LICENSE"])
self.assertIn("LICENSE", details2)
実際のGitHub APIを使用したテスト:
export GITHUB_TOKEN=your_test_token
python -m pytest tests/integration/
python repo_auditor.pyで起動audit_config.tomlに新しい項目を追加try:
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 403:
# Rate limit exceeded
print("API rate limit exceeded. Please set GITHUB_TOKEN.")
elif e.response.status_code == 404:
# Repository not found
print(f"Repository not found: {repo_name}")
else:
raise
try:
response = requests.get(url, headers=headers, timeout=10)
except requests.exceptions.Timeout:
print("Request timed out. Please check your network connection.")
except requests.exceptions.ConnectionError:
print("Failed to connect to GitHub API.")
try:
with open(cache_file, "w") as f:
json.dump(data, f, indent=2)
except PermissionError:
print(f"Permission denied: {cache_file}")
except OSError as e:
print(f"Failed to write cache: {e}")
# リポジトリ一覧のキャッシュ有効期限を適切に設定
CACHE_EXPIRY_SECONDS = 3600 # 1時間
# mtimeチェックでキャッシュの鮮度を確認
cache_age = time.time() - cache_file.stat().st_mtime
if cache_age < CACHE_EXPIRY_SECONDS:
return cached_data
# 新しいチェック項目のみ取得
items_to_fetch = [item for item in check_items if item not in cached_data]
if items_to_fetch:
for item in items_to_fetch:
# APIを呼び出し
...
# キャッシュを更新
cached_data.update(new_results)
# 重い処理は別スレッドで実行
def _fetch_repos(self):
def fetch():
# GitHub APIを呼び出す
repos = self.auditor.fetch_repositories(20)
# メインスレッドで表示更新
self.root.after(0, lambda: self._update_display(repos))
threading.Thread(target=fetch, daemon=True).start()
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# 使用例
logger.debug(f"Fetching repositories for user: {self.username}")
logger.info(f"Cache hit for {repo_name}")
logger.warning(f"API rate limit approaching: {remaining} requests left")
# キャッシュディレクトリの内容を確認
ls -lh .cache/
# 個別キャッシュファイルの内容を確認
cat .cache/repos.json | jq .
cat .cache/my-repo.json | jq .
response = requests.get(url, headers=headers)
remaining = response.headers.get("X-RateLimit-Remaining")
reset_time = response.headers.get("X-RateLimit-Reset")
print(f"Rate limit: {remaining} requests remaining")
print(f"Resets at: {datetime.fromtimestamp(int(reset_time))}")
以下は、Coding Agentに本プロジェクトを実装させる際の推奨プロンプト例です:
あなたは熟練したPythonエンジニアです。以下の仕様に基づいて、
GitHubリポジトリ監査ツール「cat-repo-auditor」をゼロから実装してください。
【要件】
1. Python 3.10以上で動作すること
2. Tkinterを使用したGUIアプリケーション
3. GitHub APIを使用してユーザーのリポジトリを取得
4. TOML形式の設定ファイルでチェック項目を定義
5. 設定ファイルのホットリロード機能
6. インテリジェントなキャッシュ機構
【実装手順】
1. プロジェクト構造を作成
2. requirements.txtを作成
3. audit_config.tomlのデフォルト設定を作成
4. RepoAuditorクラスを実装
5. ConfigWatcherクラスを実装
6. RepoAuditorGUIクラスを実装
7. エントリーポイントを実装
【参考】
詳細な実装ガイドは README.ja.md の「開発ガイド(Coding Agent向け)」セクションを参照してください。
【制約】
- PEP 8コーディング規約に準拠
- 型ヒントを適切に使用
- エラーハンドリングを適切に実装
- コメントは日本語で記述
repo_auditor.pyの以下の行を編集:
self.username = "your_github_username" # ここを変更
プロジェクトタイプ別の設定例:
Python プロジェクト:
check_items = [
"README.md",
"LICENSE",
".gitignore",
"pyproject.toml",
"requirements.txt",
"setup.py",
"tests/",
".github/workflows/python-tests.yml",
]
Node.js プロジェクト:
check_items = [
"README.md",
"LICENSE",
".gitignore",
"package.json",
"package-lock.json",
"tsconfig.json",
"tests/",
".github/workflows/node-tests.yml",
]
React プロジェクト:
check_items = [
"README.md",
"LICENSE",
"package.json",
"public/",
"src/",
".env.example",
"Dockerfile",
".github/workflows/deploy.yml",
]
設定ファイルにユーザー名を追加:
[users]
primary = "your_username"
secondary = "another_username"
コードで対応:
users = self.config.get("users", {})
for key, username in users.items():
auditor = RepoAuditor(username)
# 監査処理
症状:
Error: API rate limit exceeded
解決方法:
export GITHUB_TOKEN=ghp_your_token_here
症状:
ModuleNotFoundError: No module named '_tkinter'
解決方法(Ubuntu/Debian):
sudo apt-get install python3-tk
解決方法(macOS):
brew install python-tk
解決方法:
原因:
repoスコープが必要解決方法: トークンに以下のスコープを付与:
repo(プライベートリポジトリへのアクセス)read:org(組織リポジトリへのアクセス)新機能を追加する場合、対応するテストも追加してください:
python -m pytest tests/